feat(shipping-notice): 添加 MinerU 订单附件表格结构化功能,更新环境配置和数据模型以支持新布局解析和文档模板管理
This commit is contained in:
1 parent
c4095b08da
commit
c35223d49d
148 files changed
+15709
-1353
No files matched your search
@@ -88,6 +88,18 @@ SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
# MinerU 订单附件表格结构化(服务地址由环境/Secret 注入,未配置时保持关闭)
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=4
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
SHIPPING_NOTICE_LAYOUT_PARSER_REVISION=v3
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
|
||||
@@ -78,6 +78,18 @@ SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
# MinerU 订单附件表格结构化(服务地址由 Jenkins/系统环境注入,未配置时保持关闭)
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=4
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
SHIPPING_NOTICE_LAYOUT_PARSER_REVISION=v3
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
|
||||
@@ -98,6 +98,18 @@ SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
# MinerU 订单附件表格结构化(服务地址由环境/Secret 注入,未配置时保持关闭)
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL=http://192.168.100.192:8100/
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS=10
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS=300
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=4
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS=1000000
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES=2000000
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
SHIPPING_NOTICE_LAYOUT_PARSER_REVISION=v3
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
|
||||
@@ -24,5 +24,7 @@ import app.api.admin.shipping_customers # noqa: F401
|
||||
import app.api.admin.shipping_identity_rules # noqa: F401
|
||||
import app.api.admin.shipping_inventory # noqa: F401
|
||||
import app.api.admin.shipping_order_schema # noqa: F401
|
||||
import app.api.admin.shipping_order_document_profiles # noqa: F401
|
||||
import app.api.admin.shipping_document_layouts # noqa: F401
|
||||
|
||||
__all__ = ['admin_bp']
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_document_layouts.py
|
||||
|
||||
用途:提供发货通知 Document 布局版本诊断和显式重解析管理员 API。
|
||||
依赖:admin blueprint、require_admin、document_layout.lifecycle。
|
||||
逻辑:响应只含状态/checksum/计数,不返回 HTML、bbox、正文或 Provider 原始输出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.document_layout import lifecycle
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""读取当前管理员主键。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/documents/<int:document_id>/layout-versions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_document_layout_versions(document_id: int):
|
||||
"""列出单个 Document 的布局解析版本安全摘要。"""
|
||||
return ok(
|
||||
lifecycle.list_layout_versions(document_id), request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/documents/<int:document_id>/layout-reparse', methods=['POST'])
|
||||
@require_admin
|
||||
def reparse_shipping_document_layout(document_id: int):
|
||||
"""显式创建或复用当前活动布局版本。"""
|
||||
return ok(
|
||||
lifecycle.request_layout_reparse(document_id, created_by_id=_actor_id()),
|
||||
request_id=getattr(g, 'request_id', None), status=202,
|
||||
)
|
||||
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_order_document_profiles.py
|
||||
|
||||
用途:提供订单文档模板 Profile 的管理员版本治理 API。
|
||||
依赖:admin blueprint、require_admin、order_document_profile_service。
|
||||
逻辑:路由只转换请求和操作者;版本、Schema、字段及发布门禁全部由服务层执行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice import order_document_profile_service as service
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""读取管理员身份。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _ok(data, *, status: int = 200):
|
||||
"""返回统一成功 envelope。"""
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profiles():
|
||||
"""列出全部模板 Profile 版本。"""
|
||||
return _ok(service.list_profiles())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profile_samples():
|
||||
"""列出可用于建立 Profile 的 MinerU 样本文档。"""
|
||||
try:
|
||||
limit = int(request.args.get('limit', '50'))
|
||||
except ValueError as exc:
|
||||
raise service.ValidationError(
|
||||
'limit is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
) from exc
|
||||
return _ok(service.list_sample_documents(limit=limit))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples/<int:document_id>/tables', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_sample_tables(document_id: int):
|
||||
"""读取样本文档的结构化表格预览。"""
|
||||
return _ok(service.get_sample_tables(document_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/from-sample', methods=['POST'])
|
||||
@require_admin
|
||||
def create_order_document_profile_from_sample():
|
||||
"""由真实样本和结构化列选择生成后端计算指纹的 Profile 草稿。"""
|
||||
return _ok(service.create_draft_from_sample(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/from-sample', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_order_document_profile_from_sample(profile_id: int):
|
||||
"""用新样本和乐观锁整体更新 Profile 草稿,不允许浏览器提供结构指纹。"""
|
||||
return _ok(service.create_draft_from_sample(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_order_document_profile():
|
||||
"""创建一个模板 Profile 草稿。"""
|
||||
return _ok(service.save_draft(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_order_document_profile(profile_id: int):
|
||||
"""按乐观锁整体更新模板 Profile 草稿。"""
|
||||
return _ok(service.save_draft(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/clone', methods=['POST'])
|
||||
@require_admin
|
||||
def clone_order_document_profile(profile_id: int):
|
||||
"""从发布/退役版本创建同编码下一草稿。"""
|
||||
return _ok(service.clone_draft(profile_id, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_order_document_profile(profile_id: int):
|
||||
"""发布草稿并退役同模板旧版本。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(service.publish(
|
||||
profile_id, actor_id=_actor_id(), expected_lock_version=data.get('expected_lock_version'),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_order_document_profile(profile_id: int):
|
||||
"""手工退役当前发布模板。"""
|
||||
return _ok(service.retire(profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_order_document_profile(profile_id: int):
|
||||
"""删除错误草稿。"""
|
||||
service.delete_draft(profile_id)
|
||||
return '', 204
|
||||
@@ -8,6 +8,7 @@ backend/app/api/admin/shipping_order_extraction.py
|
||||
|
||||
from flask import g, request
|
||||
|
||||
from app import db
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
@@ -70,3 +71,85 @@ def get_shipping_order_extraction_diagnostic_run_detail(run_no: str):
|
||||
run_no=run_no,
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-quality-batches', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_order_extraction_quality_batches():
|
||||
"""列出指定 Owner 可用于自动建单门禁的已批准、仍达标批次。"""
|
||||
owner_agent_id = _query_int('owner_agent_id', 0)
|
||||
if owner_agent_id <= 0:
|
||||
raise ValidationError('owner_agent_id must be positive')
|
||||
from app.services.shipping_notice.order_extraction_quality_service import list_approved_quality_batches
|
||||
|
||||
return ok(
|
||||
list_approved_quality_batches(owner_agent_id=owner_agent_id),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-quality-batches', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_order_extraction_quality_batch():
|
||||
"""创建 L7 影子验收批次;仅锁定 Owner/Schema,不复制任何订单内容。"""
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
try:
|
||||
owner_agent_id = int(body.get('owner_agent_id'))
|
||||
schema_version_id = int(body.get('schema_version_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('owner_agent_id and schema_version_id are required') from exc
|
||||
from app.services.shipping_notice.order_extraction_quality_service import (
|
||||
create_quality_batch, serialize_quality_batch,
|
||||
)
|
||||
|
||||
batch = create_quality_batch(
|
||||
owner_agent_id=owner_agent_id, schema_version_id=schema_version_id,
|
||||
actor_id=g.current_user.id,
|
||||
)
|
||||
return ok(
|
||||
serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None), status=201,
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-quality-batches/<int:batch_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_extraction_quality_batch(batch_id: int):
|
||||
"""读取批次脱敏指标和批准状态,不返回 Run 内容、订单值或单条标签。"""
|
||||
from app.models import ShippingOrderExtractionQualityBatch
|
||||
from app.services.shipping_notice.order_extraction_quality_service import serialize_quality_batch
|
||||
|
||||
batch = db.session.get(ShippingOrderExtractionQualityBatch, batch_id)
|
||||
if batch is None:
|
||||
from app.core.errors import NotFoundError
|
||||
raise NotFoundError('Quality batch not found')
|
||||
return ok(serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-quality-batches/<int:batch_id>/runs/<run_no>/label', methods=['PUT'])
|
||||
@require_admin
|
||||
def label_shipping_order_extraction_quality_run(batch_id: int, run_no: str):
|
||||
"""提交当前管理员的匿名质量标签;同管理员重提为幂等覆盖。"""
|
||||
from app.services.shipping_notice.order_extraction_quality_service import save_quality_label, serialize_quality_batch
|
||||
|
||||
batch = save_quality_label(
|
||||
batch_id=batch_id, run_no=run_no, actor_id=g.current_user.id,
|
||||
payload=request.get_json(silent=True),
|
||||
)
|
||||
return ok(serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-quality-batches/<int:batch_id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_shipping_order_extraction_quality_batch(batch_id: int):
|
||||
"""提交 business/technical 批准;同一管理员不能承担两个角色。"""
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
from app.services.shipping_notice.order_extraction_quality_service import approve_quality_batch, serialize_quality_batch
|
||||
|
||||
batch = approve_quality_batch(
|
||||
batch_id=batch_id, role=str(body.get('role') or ''), actor_id=g.current_user.id,
|
||||
)
|
||||
return ok(serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None))
|
||||
@@ -33,6 +33,15 @@ def get_shipping_order_schema():
|
||||
return _ok(service.get_state())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/auto-creation-policy', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def shipping_order_auto_creation_policy():
|
||||
"""读取或更新订单解析自动建单总开关;字段阈值由 Schema 草稿维护。"""
|
||||
if request.method == 'GET':
|
||||
return _ok(service.get_auto_creation_policy())
|
||||
return _ok(service.save_auto_creation_policy(request.get_json(silent=True) or {}, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema', methods=['POST'])
|
||||
@require_admin
|
||||
def initialize_shipping_order_schema():
|
||||
|
||||
@@ -956,6 +956,36 @@ def workspace_retry_shipping_order_extraction_run(run_no: str):
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/reparse', methods=['POST'])
|
||||
def workspace_reparse_shipping_order_extraction_run(run_no: str):
|
||||
"""
|
||||
使用当前发布规则重新识别一个终态订单抽取 Run。
|
||||
|
||||
核心逻辑:只接收受控原因与可选备注,服务层复用原始 Intake 创建新的版本化 Run;
|
||||
不复用失败重试的冻结 Provider 缓存,也不允许前端传入 Schema、Binding 或附件内容。
|
||||
"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
reparse_order_extraction_run,
|
||||
serialize_order_extraction_run,
|
||||
)
|
||||
|
||||
run, reused = reparse_order_extraction_run(
|
||||
user_id=user.id,
|
||||
run_no=run_no,
|
||||
reason=str(body.get('reason') or ''),
|
||||
comment=str(body.get('comment') or '') or None,
|
||||
)
|
||||
db.session.commit()
|
||||
return ok(
|
||||
{'run': serialize_order_extraction_run(run), 'reused': reused},
|
||||
request_id=getattr(g, 'request_id', None), status=202,
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['GET'])
|
||||
def workspace_list_shipping_order_extraction_runs():
|
||||
"""列出当前用户订单抽取 Run,可按 HXOPS 会话过滤。"""
|
||||
|
||||
@@ -462,6 +462,37 @@ class Config:
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6')
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED = os.getenv(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', 'false'
|
||||
).lower() == 'true'
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL = os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL', '').strip()
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS', '10')
|
||||
)
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE = int(
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', '4')
|
||||
)
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY = int(
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY', '2')
|
||||
)
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS', str(1_000_000))
|
||||
)
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES = int(
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', str(2_000_000))
|
||||
)
|
||||
SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS = int(
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS', '3')
|
||||
)
|
||||
SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS', '360')
|
||||
)
|
||||
SHIPPING_NOTICE_LAYOUT_PARSER_REVISION = os.getenv(
|
||||
'SHIPPING_NOTICE_LAYOUT_PARSER_REVISION', 'v3'
|
||||
).strip() or 'v3'
|
||||
# EML 附件提取安全上限(阶段一对齐:只抽取文本,不执行宏/脚本)
|
||||
# parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析
|
||||
# parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文
|
||||
|
||||
@@ -5,4 +5,4 @@ backend/app/jobs/handlers/__init__.py
|
||||
逻辑:Wave 2 起在 worker 启动前 import 本包。
|
||||
"""
|
||||
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, shipping_order_extraction, wecom_directory_sync # noqa: F401
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_document_layout, shipping_notice_parse, shipping_notice_run, shipping_order_extraction, wecom_directory_sync # noqa: F401
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_document_layout.py
|
||||
|
||||
用途:独立执行单份 ShippingNoticeDocument 的 MinerU 布局解析任务。
|
||||
依赖:Layout lifecycle/runtime、FileAsset、通用 Job queue。
|
||||
逻辑:按 job attempt 领取版本 lease,读取对象存储调用 MinerU;收口时旧 lease 无权覆盖新版本。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.extensions import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import FileAsset, Job, ShippingDocumentLayoutVersion
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
claim_layout_version,
|
||||
complete_layout_version,
|
||||
sync_layout_after_job_failure,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.runtime import build_mineru_table_snapshot
|
||||
|
||||
|
||||
LAYOUT_JOB_ERROR = 'shipping_document_layout_provider_failed'
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_DOCUMENT_LAYOUT)
|
||||
def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行单文档布局任务;Job 和版本均使用相同 attempt 代次条件收口。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文,用于记录仅运维可见的异常堆栈。
|
||||
payload: 通用队列载荷,只读取 job_id;布局版本 ID 从冻结 Job 载荷读取。
|
||||
|
||||
Returns:
|
||||
None。成功时同时完成布局版本与 Job;失败时按通用重试策略重新排队。
|
||||
"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
return
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
version_id = int((job.payload_json or {}).get('layout_version_id') or 0)
|
||||
version = db.session.get(ShippingDocumentLayoutVersion, version_id) if version_id else None
|
||||
if version is None:
|
||||
fail_job(job.id, error='layout version not found', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
if version.status in {'ready', 'needs_review', 'failed', 'unsupported'}:
|
||||
finish_job(job.id, result={'status': version.status, 'skipped': True}, owned_attempt=owned_attempt)
|
||||
return
|
||||
claimed = claim_layout_version(version.id, job_id=job.id, owned_attempt=owned_attempt)
|
||||
if claimed is None:
|
||||
finish_job(job.id, result={'status': 'stale', 'skipped': True}, owned_attempt=owned_attempt)
|
||||
return
|
||||
version, lease = claimed
|
||||
try:
|
||||
document = version.document
|
||||
asset = db.session.get(FileAsset, int(document.asset_id or 0))
|
||||
if asset is None:
|
||||
raise ValueError('layout document asset is unavailable')
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename=str(document.filename or asset.original_filename or 'document.pdf'),
|
||||
content=read_asset_bytes(asset),
|
||||
document_id=document.id,
|
||||
content_hash=document.content_hash,
|
||||
)
|
||||
if snapshot is None:
|
||||
snapshot = {
|
||||
'snapshot_version': version.contract_version,
|
||||
'provider': version.parser_name, 'backend': version.backend,
|
||||
'status': 'unsupported', 'tables': [],
|
||||
'issues': ['shipping_document_layout_input_unsupported'],
|
||||
}
|
||||
if complete_layout_version(version.id, lease_token=lease, snapshot=snapshot):
|
||||
finish_job(
|
||||
job.id, result={'status': str(snapshot.get('status') or 'failed')},
|
||||
message='文档版面解析完成', owned_attempt=owned_attempt,
|
||||
)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if ctx.logger is not None:
|
||||
ctx.logger.exception(
|
||||
'shipping_document_layout_failed job_id=%s version_id=%s', job.id, version.id,
|
||||
)
|
||||
fail_job(job.id, error=LAYOUT_JOB_ERROR, retryable=True, owned_attempt=owned_attempt)
|
||||
sync_layout_after_job_failure(job.id)
|
||||
raise
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
用途:消费订单抽取领域 Run,调用显式绑定的 Dify Workflow 并持久化订单结果。
|
||||
依赖:Job queue、AgentRuntimeBinding、order_extraction_workflow、Run 状态机。
|
||||
逻辑:Job 只承载执行尝试;Run 是业务真相。结果先完整落库并进入 result_persisted,再收口 completed/needs_review。
|
||||
依赖:Job queue、AgentRuntimeBinding、order_extraction_workflow、Run 状态机、provider_guard。
|
||||
逻辑:Job 只承载执行尝试;Run 是业务真相。线程快照须含 provider_config_json/schema_version_id;
|
||||
仅 Dify 传输类失败累计熔断。结果先完整落库并进入 result_persisted,再收口 completed/needs_review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -50,12 +51,22 @@ from app.services.shipping_notice.order_extraction_provider_guard import (
|
||||
)
|
||||
|
||||
|
||||
# 仅 Dify 传输类失败累计熔断;本地编程错误与 CIRCUIT_OPEN 自身不得拉长冷却窗。
|
||||
_PROVIDER_CIRCUIT_FAILURE_CODES = frozenset({
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED',
|
||||
})
|
||||
|
||||
|
||||
def _execute_dify_unit_with_retry(
|
||||
*, app, run_snapshot: dict, unit_snapshot: dict, provider_snapshot: dict, timeout_seconds: int,
|
||||
max_attempts: int, backoff_ms: int, job_id: int, job_attempt: int,
|
||||
provider_max_concurrency: int, circuit_failure_threshold: int, circuit_cooldown_seconds: int,
|
||||
) -> dict:
|
||||
"""在线程独立应用上下文中用纯快照执行网络调用,并做有限指数退避重试。"""
|
||||
"""在线程独立应用上下文中用纯快照执行网络调用,并做有限指数退避重试。
|
||||
|
||||
核心逻辑:熔断仅统计 Dify 超时/请求失败;本地异常与 CIRCUIT_OPEN 不拉长冷却。
|
||||
"""
|
||||
last_error: Exception | None = None
|
||||
started = time.perf_counter()
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
@@ -84,7 +95,8 @@ def _execute_dify_unit_with_retry(
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
|
||||
if retryable:
|
||||
# [STEP] 仅传输类 Provider 失败累计熔断,避免本地异常或开路自身延长冷却。
|
||||
if isinstance(exc, AppError) and getattr(exc, 'code', None) in _PROVIDER_CIRCUIT_FAILURE_CODES:
|
||||
record_provider_failure(
|
||||
int(provider_snapshot['id']), threshold=circuit_failure_threshold,
|
||||
cooldown_seconds=circuit_cooldown_seconds,
|
||||
@@ -180,7 +192,16 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
run.attempt_count = owned_attempt
|
||||
db.session.commit()
|
||||
|
||||
timeout_seconds = int((run.provider_config_json or {}).get('timeout_seconds') or 900)
|
||||
run_config = run.provider_config_json if isinstance(run.provider_config_json, dict) else {}
|
||||
if bool(run_config.get('auto_create_enabled')):
|
||||
from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch
|
||||
|
||||
require_approved_quality_batch(
|
||||
batch_id=run.quality_batch_id,
|
||||
owner_agent_id=int(run.owner_agent_id),
|
||||
schema_version_id=int(run.schema_version_id),
|
||||
)
|
||||
timeout_seconds = int(run_config.get('timeout_seconds') or 900)
|
||||
saved_provider_result = run.provider_result_json if isinstance(run.provider_result_json, dict) else {}
|
||||
saved_orders = saved_provider_result.get('orders')
|
||||
if isinstance(saved_orders, list) and all(isinstance(item, dict) for item in saved_orders):
|
||||
@@ -243,8 +264,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
with ThreadPoolExecutor(max_workers=min(concurrency, len(dify_units) or 1)) as pool:
|
||||
run_snapshot = {
|
||||
'id': run.id, 'run_no': run.run_no, 'user_id': run.user_id,
|
||||
'schema_version_id': run.schema_version_id,
|
||||
'input_snapshot_hash': run.input_snapshot_hash,
|
||||
'input_snapshot_json': run.input_snapshot_json,
|
||||
'provider_config_json': run.provider_config_json,
|
||||
}
|
||||
provider_snapshot = {
|
||||
'id': provider.id, 'api_base_url': provider.api_base_url,
|
||||
|
||||
@@ -983,6 +983,12 @@ def process_next_job(
|
||||
)
|
||||
|
||||
on_recovered = sync_order_extraction_run_after_job_recovery
|
||||
elif normalized_type == JobType.SHIPPING_DOCUMENT_LAYOUT.value:
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
sync_layout_after_job_recovery,
|
||||
)
|
||||
|
||||
on_recovered = sync_layout_after_job_recovery
|
||||
recover_stale_jobs(
|
||||
domain=domain,
|
||||
timeout_seconds=timeout_seconds,
|
||||
|
||||
@@ -17,6 +17,7 @@ class JobType(StrEnum):
|
||||
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
|
||||
SHIPPING_NOTICE_PARSE = 'shipping_notice_parse'
|
||||
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
||||
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
|
||||
SCHEDULE_RUN = 'schedule_run'
|
||||
FILE_CHECK_RUN = 'file_check_run'
|
||||
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
|
||||
@@ -50,7 +51,10 @@ _HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
|
||||
# worker --queues 参数 → 可消费的 KbJob.job_type 集合
|
||||
QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
|
||||
'shipping': frozenset({'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction'}),
|
||||
'shipping': frozenset({
|
||||
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
||||
'shipping_document_layout',
|
||||
}),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -52,6 +52,8 @@ from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionRunIntake,
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.models.shipping_order_document_profile import ShippingOrderDocumentProfile
|
||||
from app.models.shipping_document_layout import ShippingDocumentLayoutVersion
|
||||
from app.models.shipping_inventory_config import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryExternalMapping,
|
||||
@@ -80,6 +82,10 @@ from app.models.shipping_customer import (
|
||||
)
|
||||
from app.models.shipping_customer_import import ShippingCustomerImportBatch, ShippingCustomerImportRow
|
||||
from app.models.shipping_customer_resolution import ShippingCustomerShadowMatch, ShippingCustomerShadowResolution
|
||||
from app.models.shipping_order_extraction_quality import (
|
||||
ShippingOrderExtractionQualityBatch,
|
||||
ShippingOrderExtractionQualityLabel,
|
||||
)
|
||||
from app.models.shipping_identity_rule import (
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityEvidence,
|
||||
@@ -144,6 +150,10 @@ __all__ = [
|
||||
'ShippingOrderExtractionUnit',
|
||||
'ShippingOrderExtractionProgressEvent',
|
||||
'ShippingOrderExtractionDiagnosticAudit',
|
||||
'ShippingOrderExtractionQualityBatch',
|
||||
'ShippingOrderExtractionQualityLabel',
|
||||
'ShippingOrderDocumentProfile',
|
||||
'ShippingDocumentLayoutVersion',
|
||||
'ShippingCustomer',
|
||||
'ShippingCustomerIdentifier',
|
||||
'ShippingCustomerExternalRef',
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/models/agent_runtime_binding.py
|
||||
|
||||
用途:定义用户入口 Agent 到内部运行能力 Provider 的显式绑定。
|
||||
依赖:agents 表。
|
||||
逻辑:业务代码只按 owner_agent_id + capability_code 解析 Provider;Dify App ID、Key 和 URL 继续由 Provider Agent 保存。
|
||||
逻辑:业务代码按 owner_agent_id + capability_code 解析 Provider;执行策略仅保存通用超时与重试参数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,6 +34,9 @@ class AgentRuntimeBinding(Base):
|
||||
ForeignKey('agents.id'), nullable=False, index=True,
|
||||
)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default='1', nullable=False)
|
||||
quality_batch_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_quality_batches.id'), nullable=True, index=True,
|
||||
)
|
||||
config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
@@ -65,6 +65,23 @@ class Job(Base):
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
),
|
||||
Index(
|
||||
'uq_jobs_shipping_document_layout_active_ref',
|
||||
'domain',
|
||||
'job_type',
|
||||
'business_ref',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
"job_type = 'shipping_document_layout' "
|
||||
"AND status IN ('queued', 'running') "
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"job_type = 'shipping_document_layout' "
|
||||
"AND status IN ('queued', 'running') "
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
|
||||
@@ -509,6 +509,15 @@ class ShippingNoticeDocument(Base):
|
||||
parse_status: Mapped[str] = mapped_column(String(32), default='pending', nullable=False)
|
||||
extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
current_layout_version_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey(
|
||||
'shipping_document_layout_versions.id',
|
||||
name='fk_shipping_notice_documents_current_layout_version',
|
||||
ondelete='SET NULL',
|
||||
use_alter=True,
|
||||
),
|
||||
nullable=True,
|
||||
)
|
||||
order_extraction_status: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
default='not_started',
|
||||
@@ -522,6 +531,19 @@ class ShippingNoticeDocument(Base):
|
||||
order_extraction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
current_layout_version = relationship(
|
||||
'ShippingDocumentLayoutVersion',
|
||||
foreign_keys=[current_layout_version_id],
|
||||
post_update=True,
|
||||
)
|
||||
layout_versions = relationship(
|
||||
'ShippingDocumentLayoutVersion',
|
||||
foreign_keys='ShippingDocumentLayoutVersion.document_id',
|
||||
back_populates='document',
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class ShippingNoticeCandidate(Base):
|
||||
"""
|
||||
订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。
|
||||
@@ -533,7 +555,10 @@ class ShippingNoticeCandidate(Base):
|
||||
__tablename__ = 'shipping_notice_candidates'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'),
|
||||
UniqueConstraint('intake_id', 'candidate_key', name='uq_shipping_notice_candidates_intake_key'),
|
||||
UniqueConstraint(
|
||||
'intake_id', 'candidate_key', 'order_extraction_run_id',
|
||||
name='uq_shipping_notice_candidates_intake_key_run',
|
||||
),
|
||||
# 保证主文档与 Candidate 同属一 Intake,禁止跨 Intake 挂接
|
||||
ForeignKeyConstraint(
|
||||
['primary_document_id', 'intake_id'],
|
||||
@@ -566,6 +591,11 @@ class ShippingNoticeCandidate(Base):
|
||||
order_extraction_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
# 仅当前版本候选可进入建单;旧版本保留为只读审计和重新识别失败时的回退依据。
|
||||
is_current_version: Mapped[bool] = mapped_column(
|
||||
Boolean, default=True, server_default=text('true'), nullable=False, index=True,
|
||||
)
|
||||
selected_before_superseded: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
|
||||
extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
classification_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
field_confidence_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
backend/app/models/shipping_document_layout.py
|
||||
|
||||
用途:持久化每份发货通知 Document 的版本化版面解析生命周期、冻结快照和质量结果。
|
||||
依赖:shipping_notice_documents、jobs、SQLAlchemy Base。
|
||||
逻辑:同一 Document 版本递增;运行租约隔离旧 Worker,只有成功版本可成为 Document 当前布局。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingDocumentLayoutVersion(Base):
|
||||
"""单文档版面解析版本;payload/checksum 一旦完成即不可原地改写。"""
|
||||
|
||||
__tablename__ = 'shipping_document_layout_versions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('document_id', 'version', name='uq_shipping_document_layout_document_version'),
|
||||
CheckConstraint(
|
||||
"status IN ('queued', 'running', 'ready', 'needs_review', 'failed', 'unsupported')",
|
||||
name='ck_shipping_document_layout_status',
|
||||
),
|
||||
Index('ix_shipping_document_layout_document_status', 'document_id', 'status'),
|
||||
Index('ix_shipping_document_layout_content_parser', 'source_content_hash', 'parser_key'),
|
||||
Index(
|
||||
'uq_shipping_document_layout_one_active',
|
||||
'document_id',
|
||||
unique=True,
|
||||
postgresql_where=text("status IN ('queued', 'running')"),
|
||||
sqlite_where=text("status IN ('queued', 'running')"),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(24), default='queued', server_default='queued', nullable=False)
|
||||
source_content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
parser_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
parser_name: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
backend: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
contract_version: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
payload_size_bytes: Mapped[int] = mapped_column(Integer, default=0, server_default='0', nullable=False)
|
||||
quality_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
issues_json: Mapped[list] = mapped_column(JSON, default=list, nullable=False)
|
||||
job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True, index=True)
|
||||
lease_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
attempt_count: Mapped[int] = mapped_column(Integer, default=0, server_default='0', nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
document = relationship(
|
||||
'ShippingNoticeDocument', foreign_keys=[document_id], back_populates='layout_versions',
|
||||
)
|
||||
job = relationship('Job', foreign_keys=[job_id])
|
||||
@@ -0,0 +1,69 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_document_profile.py
|
||||
|
||||
用途:保存订单文档模板解析 Profile 的草稿、不可变发布版本及 Schema 绑定。
|
||||
依赖:shipping_order_schema_versions、users、SQLAlchemy Base。
|
||||
逻辑:同一模板编码按版本递增;发布版本冻结结构指纹、固定列规则和稳定字段 ID,Run 再复制完整快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingOrderDocumentProfile(Base):
|
||||
"""版本化订单文档模板解析配置;published/retired 行不可原地修改。"""
|
||||
|
||||
__tablename__ = 'shipping_order_document_profiles'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('profile_code', 'version', name='uq_shipping_order_document_profiles_code_version'),
|
||||
CheckConstraint(
|
||||
"status IN ('draft', 'published', 'retired')",
|
||||
name='ck_shipping_order_document_profiles_status',
|
||||
),
|
||||
Index('ix_shipping_order_document_profiles_schema_status', 'schema_version_id', 'status'),
|
||||
Index('ix_shipping_order_document_profiles_fingerprint', 'structure_fingerprint'),
|
||||
Index(
|
||||
'uq_shipping_order_document_profiles_one_published',
|
||||
'profile_code',
|
||||
unique=True,
|
||||
postgresql_where=text("status = 'published'"),
|
||||
sqlite_where=text("status = 'published'"),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
|
||||
schema_version_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_schema_versions.id'), nullable=False,
|
||||
)
|
||||
structure_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
source_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_document_profiles.id'), nullable=True,
|
||||
)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
schema_version = relationship('ShippingOrderSchemaVersion')
|
||||
source_profile: Mapped[Optional['ShippingOrderDocumentProfile']] = relationship(
|
||||
remote_side='ShippingOrderDocumentProfile.id', foreign_keys=[source_profile_id],
|
||||
)
|
||||
@@ -0,0 +1,83 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_extraction_quality.py
|
||||
|
||||
用途:保存订单抽取 L7 影子验收批次、双人匿名标签和双角色批准事实。
|
||||
依赖:Agent、User、ShippingOrderSchemaVersion、ShippingOrderExtractionRun。
|
||||
逻辑:批次锁定 owner/schema/阈值;同 Run 两名管理员标签一致后计入指标,达标后双人批准供 Runtime Binding 门禁引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingOrderExtractionQualityBatch(Base):
|
||||
"""L7 影子验收批次;批准后成为不可变自动建单发布凭证。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_quality_batches'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('batch_no', name='uq_shipping_order_extraction_quality_batches_no'),
|
||||
CheckConstraint(
|
||||
"status IN ('collecting', 'ready', 'approved', 'rejected')",
|
||||
name='ck_shipping_order_extraction_quality_batches_status',
|
||||
),
|
||||
Index('ix_shipping_order_extraction_quality_batches_owner_created', 'owner_agent_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
batch_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
owner_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), nullable=False, index=True)
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
threshold_version: Mapped[str] = mapped_column(String(32), nullable=False, default='l7.v1', server_default='l7.v1')
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='collecting', server_default='collecting')
|
||||
created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
business_approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
business_approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
technical_approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
technical_approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
rejected_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
rejected_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
rejection_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
labels: Mapped[list['ShippingOrderExtractionQualityLabel']] = relationship(
|
||||
back_populates='batch', cascade='all, delete-orphan', order_by='ShippingOrderExtractionQualityLabel.id',
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderExtractionQualityLabel(Base):
|
||||
"""单个管理员对真实 Run 提交的匿名质量计数;不保存订单字段值或正文。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_quality_labels'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('batch_id', 'run_id', 'reviewer_id', name='uq_shipping_order_quality_label_reviewer'),
|
||||
CheckConstraint('core_expected_count >= 0', name='ck_shipping_order_quality_expected_nonnegative'),
|
||||
CheckConstraint('core_extracted_count >= 0', name='ck_shipping_order_quality_extracted_nonnegative'),
|
||||
CheckConstraint('core_correct_count >= 0', name='ck_shipping_order_quality_correct_nonnegative'),
|
||||
Index('ix_shipping_order_quality_labels_batch_run', 'batch_id', 'run_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
batch_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_quality_batches.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extraction_runs.id'), nullable=False)
|
||||
reviewer_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
core_expected_count: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
core_extracted_count: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
core_correct_count: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
wrong_merge: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false')
|
||||
wrong_split: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false')
|
||||
wrong_auto_create: Mapped[bool] = mapped_column(nullable=False, default=False, server_default='false')
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
batch: Mapped['ShippingOrderExtractionQualityBatch'] = relationship(back_populates='labels')
|
||||
@@ -3,7 +3,7 @@ backend/app/models/shipping_order_extraction_run.py
|
||||
|
||||
用途:定义建单前订单抽取的领域运行记录及其冻结 Intake 集合。
|
||||
依赖:agents、users、jobs、shipping_notice_intakes、shipping_order_schema_versions。
|
||||
逻辑:Run 保存用户可见生命周期和不可变输入快照;通用 Job 只承担执行尝试,Candidate/Extraction 通过 run_id 回溯本次运行。
|
||||
逻辑:Run 保存用户可见生命周期和不可变输入快照;自动建单策略随 Schema 快照冻结。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -65,8 +65,21 @@ class ShippingOrderExtractionRun(Base):
|
||||
provider_agent_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('agents.id'), nullable=True, index=True,
|
||||
)
|
||||
quality_batch_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_quality_batches.id'), nullable=True, index=True,
|
||||
)
|
||||
provider_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
provider_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
# 重新识别创建新 Run;谱系字段保留旧结果,禁止用原地覆盖破坏审计事实。
|
||||
reparse_of_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
superseded_by_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
reparse_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
reparse_comment: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
||||
schema_version_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_schema_versions.id'), nullable=False,
|
||||
@@ -108,6 +121,12 @@ class ShippingOrderExtractionRun(Base):
|
||||
intakes: Mapped[list['ShippingOrderExtractionRunIntake']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderExtractionRunIntake.position',
|
||||
)
|
||||
reparse_source: Mapped[Optional['ShippingOrderExtractionRun']] = relationship(
|
||||
'ShippingOrderExtractionRun', foreign_keys=[reparse_of_run_id], remote_side='ShippingOrderExtractionRun.id',
|
||||
)
|
||||
superseding_run: Mapped[Optional['ShippingOrderExtractionRun']] = relationship(
|
||||
'ShippingOrderExtractionRun', foreign_keys=[superseded_by_run_id], remote_side='ShippingOrderExtractionRun.id',
|
||||
)
|
||||
extraction_plan: Mapped[Optional['ShippingOrderExtractionPlan']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', uselist=False,
|
||||
)
|
||||
|
||||
@@ -55,6 +55,8 @@ class ShippingOrderSchema(Base):
|
||||
schema_code: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
# 自动建单是订单解析的运行策略,不属于不可变字段模板版本。
|
||||
auto_creation_policy_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
@@ -240,7 +242,7 @@ class ShippingOrderLine(Base):
|
||||
|
||||
|
||||
class ShippingOrderFieldObservation(Base):
|
||||
"""某字段来自某 Document/解析器的原始观察及可回查证据。"""
|
||||
"""某字段来自某 Document/解析器的原始观察及可回查文本或版面证据。"""
|
||||
|
||||
__tablename__ = 'shipping_order_field_observations'
|
||||
__table_args__ = (Index('ix_shipping_order_observations_extraction_field', 'extraction_id', 'field_id'),)
|
||||
@@ -255,6 +257,8 @@ class ShippingOrderFieldObservation(Base):
|
||||
raw_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
||||
normalized_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
||||
evidence_quote: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
evidence_ref: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
evidence_metadata_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
confidence: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 4), nullable=True)
|
||||
evidence_verified: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
@@ -17,6 +17,13 @@ from app.services.agent_registry.catalog import get_catalog_entry
|
||||
from app.services.agent_registry.resolver import resolve_effective_role
|
||||
|
||||
|
||||
_EXECUTOR_GOVERNANCE_DEFAULTS = {
|
||||
'provider_max_concurrency': 4,
|
||||
'circuit_failure_threshold': 5,
|
||||
'circuit_cooldown_seconds': 60,
|
||||
}
|
||||
|
||||
|
||||
def _capability_definition(owner: Agent, capability_code: str) -> dict[str, Any]:
|
||||
"""读取 owner Agent Catalog 中声明的能力定义;未声明能力不可由管理员任意绑定。"""
|
||||
entry = get_catalog_entry(owner.agent_code) or {}
|
||||
@@ -37,13 +44,7 @@ def _normalize_config(raw: Any) -> dict[str, Any]:
|
||||
raw = {}
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError('config must be an object', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
|
||||
unknown = set(raw) - {
|
||||
'timeout_seconds', 'max_attempts', 'unit_concurrency',
|
||||
'unit_max_attempts', 'unit_retry_backoff_ms',
|
||||
'max_model_units', 'provider_max_concurrency',
|
||||
'circuit_failure_threshold', 'circuit_cooldown_seconds',
|
||||
'auto_create_enabled',
|
||||
}
|
||||
unknown = set(raw) - {'timeout_seconds', 'max_attempts', 'auto_create_enabled'}
|
||||
if unknown:
|
||||
raise ValidationError(
|
||||
'Unsupported runtime binding config keys',
|
||||
@@ -53,14 +54,6 @@ def _normalize_config(raw: Any) -> dict[str, Any]:
|
||||
try:
|
||||
timeout_seconds = int(raw.get('timeout_seconds', 900))
|
||||
max_attempts = int(raw.get('max_attempts', 3))
|
||||
unit_concurrency = int(raw.get('unit_concurrency', 2))
|
||||
unit_max_attempts = int(raw.get('unit_max_attempts', 2))
|
||||
unit_retry_backoff_ms = int(raw.get('unit_retry_backoff_ms', 500))
|
||||
max_model_units = int(raw.get('max_model_units', 20))
|
||||
provider_max_concurrency = int(raw.get('provider_max_concurrency', 4))
|
||||
circuit_failure_threshold = int(raw.get('circuit_failure_threshold', 5))
|
||||
circuit_cooldown_seconds = int(raw.get('circuit_cooldown_seconds', 60))
|
||||
auto_create_enabled = raw.get('auto_create_enabled', False)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Runtime binding execution settings must be integers',
|
||||
@@ -71,34 +64,34 @@ def _normalize_config(raw: Any) -> dict[str, Any]:
|
||||
'Runtime binding config is outside allowed limits',
|
||||
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
|
||||
)
|
||||
if not 2 <= unit_concurrency <= 4 or not 1 <= unit_max_attempts <= 3:
|
||||
raise ValidationError(
|
||||
'Runtime binding unit concurrency/attempts are outside allowed limits',
|
||||
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
|
||||
)
|
||||
if not 100 <= unit_retry_backoff_ms <= 5000:
|
||||
raise ValidationError(
|
||||
'Runtime binding unit retry backoff is outside allowed limits',
|
||||
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
|
||||
)
|
||||
if not 1 <= max_model_units <= 100 or not 1 <= provider_max_concurrency <= 20:
|
||||
raise ValidationError('Runtime binding provider budget is outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
|
||||
if not 2 <= circuit_failure_threshold <= 20 or not 10 <= circuit_cooldown_seconds <= 600:
|
||||
raise ValidationError('Runtime binding circuit settings are outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
|
||||
if not isinstance(auto_create_enabled, bool):
|
||||
raise ValidationError('Runtime binding auto-create gate must be boolean', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
|
||||
return {
|
||||
result = {
|
||||
'timeout_seconds': timeout_seconds,
|
||||
'max_attempts': max_attempts,
|
||||
'unit_concurrency': unit_concurrency,
|
||||
'unit_max_attempts': unit_max_attempts,
|
||||
'unit_retry_backoff_ms': unit_retry_backoff_ms,
|
||||
'max_model_units': max_model_units,
|
||||
'provider_max_concurrency': provider_max_concurrency,
|
||||
'circuit_failure_threshold': circuit_failure_threshold,
|
||||
'circuit_cooldown_seconds': circuit_cooldown_seconds,
|
||||
'auto_create_enabled': auto_create_enabled,
|
||||
}
|
||||
if 'auto_create_enabled' in raw:
|
||||
if not isinstance(raw['auto_create_enabled'], bool):
|
||||
raise ValidationError('auto_create_enabled must be boolean', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
|
||||
result['auto_create_enabled'] = raw['auto_create_enabled']
|
||||
return result
|
||||
|
||||
|
||||
def resolve_executor_governance(provider: Agent) -> dict[str, int]:
|
||||
"""读取内部执行器全局治理,供新 Run 冻结并避免入口应用绕过 Provider 保护。"""
|
||||
raw_extra = provider.extra_config if isinstance(provider.extra_config, dict) else {}
|
||||
raw = raw_extra.get('order_extraction_governance') if isinstance(raw_extra.get('order_extraction_governance'), dict) else {}
|
||||
try:
|
||||
config = {
|
||||
'provider_max_concurrency': int(raw.get('provider_max_concurrency', _EXECUTOR_GOVERNANCE_DEFAULTS['provider_max_concurrency'])),
|
||||
'circuit_failure_threshold': int(raw.get('circuit_failure_threshold', _EXECUTOR_GOVERNANCE_DEFAULTS['circuit_failure_threshold'])),
|
||||
'circuit_cooldown_seconds': int(raw.get('circuit_cooldown_seconds', _EXECUTOR_GOVERNANCE_DEFAULTS['circuit_cooldown_seconds'])),
|
||||
}
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Internal executor governance settings must be integers', code='AGENT.EXECUTOR_GOVERNANCE_INVALID') from exc
|
||||
if not 1 <= config['provider_max_concurrency'] <= 20:
|
||||
raise ValidationError('Internal executor concurrency is outside allowed limits', code='AGENT.EXECUTOR_GOVERNANCE_INVALID')
|
||||
if not 2 <= config['circuit_failure_threshold'] <= 20 or not 10 <= config['circuit_cooldown_seconds'] <= 600:
|
||||
raise ValidationError('Internal executor circuit settings are outside allowed limits', code='AGENT.EXECUTOR_GOVERNANCE_INVALID')
|
||||
return config
|
||||
|
||||
|
||||
def _validate_provider(provider: Agent, definition: dict[str, Any]) -> None:
|
||||
@@ -145,6 +138,7 @@ def serialize_runtime_binding(binding: AgentRuntimeBinding) -> dict[str, Any]:
|
||||
'is_active': provider.is_active,
|
||||
} if provider else None,
|
||||
'enabled': bool(binding.enabled),
|
||||
'quality_batch_id': binding.quality_batch_id,
|
||||
'config': dict(binding.config_json or {}),
|
||||
}
|
||||
|
||||
@@ -166,10 +160,11 @@ def save_runtime_binding(
|
||||
capability_code: str,
|
||||
provider_agent_id: int,
|
||||
enabled: bool,
|
||||
quality_batch_id: int | None = None,
|
||||
config: Any,
|
||||
commit: bool = True,
|
||||
) -> AgentRuntimeBinding:
|
||||
"""创建或更新能力绑定;owner/provider 必须是不同 Agent 且满足 Catalog 约束。"""
|
||||
"""创建或更新能力绑定;开启自动建单时必须引用已批准质量批次。"""
|
||||
owner = db.session.get(Agent, owner_agent_id)
|
||||
provider = db.session.get(Agent, provider_agent_id)
|
||||
if owner is None or provider is None:
|
||||
@@ -181,6 +176,15 @@ def save_runtime_binding(
|
||||
if enabled:
|
||||
_validate_provider(provider, definition)
|
||||
normalized_config = _normalize_config(config)
|
||||
if code == 'shipping.order_extraction' and normalized_config.get('auto_create_enabled'):
|
||||
from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch
|
||||
from app.services.shipping_notice.order_schema.runtime import published_version
|
||||
|
||||
require_approved_quality_batch(
|
||||
batch_id=quality_batch_id,
|
||||
owner_agent_id=owner.id,
|
||||
schema_version_id=int(published_version().id),
|
||||
)
|
||||
binding = AgentRuntimeBinding.query.filter_by(
|
||||
owner_agent_id=owner.id, capability_code=code,
|
||||
).first()
|
||||
@@ -189,6 +193,7 @@ def save_runtime_binding(
|
||||
db.session.add(binding)
|
||||
binding.provider_agent_id = provider.id
|
||||
binding.enabled = bool(enabled)
|
||||
binding.quality_batch_id = int(quality_batch_id) if quality_batch_id is not None else None
|
||||
binding.config_json = normalized_config
|
||||
if commit:
|
||||
db.session.commit()
|
||||
|
||||
@@ -560,6 +560,7 @@ def create_shipping_batch_from_candidates(
|
||||
.filter(
|
||||
ShippingNoticeCandidate.candidate_no.in_(candidate_nos),
|
||||
ShippingNoticeCandidate.intake_id.in_([int(item.id) for item in intakes]),
|
||||
ShippingNoticeCandidate.is_current_version.is_(True),
|
||||
)
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
.with_for_update()
|
||||
@@ -582,6 +583,7 @@ def create_shipping_batch_from_candidates(
|
||||
ShippingNoticeCandidate.intake_id.in_([int(item.id) for item in intakes]),
|
||||
ShippingNoticeCandidate.selected.is_(True),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
ShippingNoticeCandidate.is_current_version.is_(True),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
@@ -612,6 +614,8 @@ def create_shipping_batch_from_candidates(
|
||||
raise ConflictError(code='SHIPPING_NOTICE.INTAKE_EXPIRED', message='接入记录已过期')
|
||||
if not candidate.selected:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED', message='订单候选未选中')
|
||||
if not candidate.is_current_version:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SUPERSEDED', message='订单候选已被重新识别版本替代')
|
||||
if candidate.consumed_task_id is not None:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
||||
if str(candidate.validation_status or '') != 'ready' or candidate.conflicts_json:
|
||||
|
||||
@@ -66,11 +66,30 @@ def _refresh_candidate(candidate: ShippingNoticeCandidate, intake: ShippingNotic
|
||||
return result
|
||||
|
||||
|
||||
def _append_manual_review_history(
|
||||
structured: dict[str, Any], *, user_id: int, before_summary: dict[str, Any],
|
||||
before_conflicts: list[Any], before_status: str, after_summary: dict[str, Any],
|
||||
) -> None:
|
||||
"""追加不可变人工修订快照,保留规则/LLM 结果被人工更正前的审核依据。"""
|
||||
history = list(structured.get('manual_review_history') or [])
|
||||
history.append({
|
||||
'action': 'business_summary_edited',
|
||||
'actor_user_id': int(user_id),
|
||||
'edited_at': datetime.utcnow().isoformat(),
|
||||
'before_summary': before_summary,
|
||||
'before_conflicts': before_conflicts,
|
||||
'before_validation_status': before_status,
|
||||
'after_summary': after_summary,
|
||||
})
|
||||
structured['manual_review_history'] = history
|
||||
|
||||
|
||||
def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None = None, business_summary: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
更新候选选择状态或人工修订后的业务摘要。
|
||||
|
||||
核心逻辑:已消费候选禁止修改;摘要变化时清除冲突、置 ready 并重算双指纹与判重。
|
||||
核心逻辑:已消费候选禁止修改;人工摘要通过统一校验后保留修订前快照,
|
||||
再清除已人工处理的冲突、置 ready 并重算双指纹与判重。
|
||||
"""
|
||||
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
|
||||
if candidate.consumed_task_id is not None or intake.parse_status == 'consumed':
|
||||
@@ -84,6 +103,17 @@ def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None =
|
||||
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='business_summary 必须为对象')
|
||||
normalized_summary = normalize_candidate_business_summary(business_summary)
|
||||
structured = dict(candidate.structured_result_json or {})
|
||||
before_summary = dict(structured.get('business_summary') or {})
|
||||
before_conflicts = list(candidate.conflicts_json or [])
|
||||
before_status = str(candidate.validation_status or '')
|
||||
_append_manual_review_history(
|
||||
structured,
|
||||
user_id=user_id,
|
||||
before_summary=before_summary,
|
||||
before_conflicts=before_conflicts,
|
||||
before_status=before_status,
|
||||
after_summary=normalized_summary,
|
||||
)
|
||||
structured['business_summary'] = normalized_summary
|
||||
structured['manual_edited'] = True
|
||||
candidate.structured_result_json = structured
|
||||
|
||||
@@ -87,6 +87,7 @@ def persist_deterministic_context_fields(
|
||||
'id': decision.id, 'field_id': field_id, 'field_code': field_code, 'line_id': None,
|
||||
'status': decision.decision_status, 'value': value, 'reason_code': decision.reason_code,
|
||||
'observation_ids': list(decision.supporting_observation_ids_json or []),
|
||||
'confidence': 1.0 if value is not None else 0.0,
|
||||
})
|
||||
continue
|
||||
|
||||
@@ -99,6 +100,8 @@ def persist_deterministic_context_fields(
|
||||
extraction_id=extraction.id, line_id=None, field_id=field_id,
|
||||
source_document_id=None, source_type='mail_header', extractor='deterministic_context',
|
||||
raw_value_json=value, normalized_value_json=value, evidence_quote=None,
|
||||
evidence_ref=f'mail_header:{option_key}',
|
||||
evidence_metadata_json={'kind': 'mail_header', 'option_key': option_key},
|
||||
confidence=Decimal('1.0000'), evidence_verified=True,
|
||||
)
|
||||
db.session.add(observation)
|
||||
@@ -123,6 +126,7 @@ def persist_deterministic_context_fields(
|
||||
'id': observation.id, 'field_id': field_id, 'line_id': None,
|
||||
'source_type': 'mail_header', 'document_id': None,
|
||||
'value': value, 'evidence_verified': True,
|
||||
'evidence_ref': observation.evidence_ref, 'evidence_kind': 'mail_header',
|
||||
})
|
||||
elif config.get('required'):
|
||||
blocked.append(field_code)
|
||||
@@ -130,5 +134,6 @@ def persist_deterministic_context_fields(
|
||||
'id': decision.id, 'field_id': field_id, 'field_code': field_code, 'line_id': None,
|
||||
'status': status, 'value': value, 'reason_code': reason,
|
||||
'observation_ids': list(decision.supporting_observation_ids_json or []),
|
||||
'confidence': 1.0 if observation is not None else 0.0,
|
||||
})
|
||||
return header, observations, decisions, blocked
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTaskInventoryLink
|
||||
from app.models import ShippingNoticeCandidate, ShippingOrderExtractionRun, ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_PARSE_OK,
|
||||
@@ -371,12 +371,37 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
return match_result
|
||||
|
||||
# [STEP 4] Task 不再回退到旧 Chatflow 重新抽取;只有 Intake Run 可以执行订单识别。
|
||||
# [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。
|
||||
if decision == "reparse":
|
||||
candidate = (
|
||||
db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id))
|
||||
if task.source_candidate_id else None
|
||||
)
|
||||
source_run_id = candidate.order_extraction_run_id if candidate is not None else None
|
||||
if source_run_id:
|
||||
from app.services.shipping_notice.order_extraction_run_service import reparse_order_extraction_run
|
||||
|
||||
run = db.session.get(ShippingOrderExtractionRun, source_run_id)
|
||||
if run is not None:
|
||||
replacement, reused = reparse_order_extraction_run(
|
||||
user_id=int(task.user_id), run_no=run.run_no, reason="other", comment=comment or None,
|
||||
)
|
||||
log_task_action_event(
|
||||
task, "notice_reparse_requested", action="reparse", source=event_source, comment=comment,
|
||||
extra={"source_run_no": run.run_no, "replacement_run_no": replacement.run_no, "reused": reused},
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human", task=task,
|
||||
message="已使用当前发布规则重新识别原始发货通知,请等待新版结果后审核。",
|
||||
data={**serialize_task_for_tool(task), "order_extraction_run_no": replacement.run_no},
|
||||
checkpoint=task.review_status or "parse_review", stop_agent_turn=True,
|
||||
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="订单重新识别必须从原始发货通知重新上传并创建后台识别任务。",
|
||||
message="当前任务无法追溯到可重新识别的原始 Run,请重新上传发货通知。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=task.review_status or "parse_review",
|
||||
stop_agent_turn=True,
|
||||
|
||||
@@ -157,6 +157,7 @@ def _upsert_document(
|
||||
warnings: list[str],
|
||||
asset_id: int | None,
|
||||
classification: str,
|
||||
layout_snapshot: dict[str, Any] | None = None,
|
||||
) -> ShippingNoticeDocument:
|
||||
row = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
@@ -184,6 +185,10 @@ def _upsert_document(
|
||||
row.classification = classification
|
||||
row.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
if isinstance(layout_snapshot, dict):
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
|
||||
record_inline_layout_snapshot(row, layout_snapshot)
|
||||
# 按 Document→Asset 关联边增减引用,避免「已 referenced」跳过 +1 导致漏计多文档共用
|
||||
new_asset_id = int(asset_id) if asset_id else None
|
||||
if previous_asset_id and previous_asset_id != new_asset_id:
|
||||
@@ -460,6 +465,8 @@ def persist_documents_and_candidates(
|
||||
|
||||
# [STEP 1] 正文 Document:仅邮件级上下文,不生成 Candidate
|
||||
if is_eml:
|
||||
html_tables = email_meta.pop('body_html_tables', [])
|
||||
canonical_html_tables = [str(item) for item in html_tables if str(item).strip()]
|
||||
body_summary = parse_intake_business_summary(
|
||||
extracted_text=body_text,
|
||||
source_type='email',
|
||||
@@ -472,7 +479,11 @@ def persist_documents_and_candidates(
|
||||
parse_status='parsed' if body_text.strip() else 'empty',
|
||||
business_summary=body_summary,
|
||||
)
|
||||
body_hash = hashlib.sha256(body_text.encode('utf-8')).hexdigest().lower() if body_text else None
|
||||
body_hash_source = '\x1f'.join([body_text, *canonical_html_tables]).strip('\x1f')
|
||||
body_hash = (
|
||||
hashlib.sha256(body_hash_source.encode('utf-8')).hexdigest().lower()
|
||||
if body_hash_source else None
|
||||
)
|
||||
body_doc = _upsert_document(
|
||||
intake=intake,
|
||||
attachment_key=BODY_ATTACHMENT_KEY,
|
||||
@@ -485,6 +496,29 @@ def persist_documents_and_candidates(
|
||||
asset_id=None,
|
||||
classification=body_class,
|
||||
)
|
||||
if canonical_html_tables and body_doc.content_hash:
|
||||
from app.services.shipping_notice.document_layout.html_layout import (
|
||||
build_html_layout_candidate,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
record_inline_layout_snapshot,
|
||||
)
|
||||
|
||||
layout = build_html_layout_candidate(
|
||||
document_id=int(body_doc.id), content_hash=str(body_doc.content_hash),
|
||||
tables=canonical_html_tables,
|
||||
)
|
||||
record_inline_layout_snapshot(
|
||||
body_doc,
|
||||
{
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'eml-html-dom', 'provider_version': 'v1',
|
||||
'backend': 'html', 'status': 'needs_review',
|
||||
'tables': [], 'layout_candidate': layout.model_dump(mode='json'),
|
||||
'issues': [item.code for item in layout.quality.issues],
|
||||
},
|
||||
parser_key='eml-html-dom:shipping_document_layout.v1:v1',
|
||||
)
|
||||
active_keys.add(BODY_ATTACHMENT_KEY)
|
||||
documents.append(body_doc)
|
||||
|
||||
@@ -549,6 +583,7 @@ def persist_documents_and_candidates(
|
||||
parse_status=att_status,
|
||||
extracted_text=att_text or None,
|
||||
warnings=[str(w) for w in (item.get('warnings') or [])],
|
||||
layout_snapshot=item.get('layout_snapshot') if isinstance(item.get('layout_snapshot'), dict) else None,
|
||||
asset_id=asset_id,
|
||||
classification=classification,
|
||||
)
|
||||
@@ -612,6 +647,7 @@ def persist_documents_and_candidates(
|
||||
parse_status='parsed',
|
||||
extracted_text=str(result.text or '') or None,
|
||||
warnings=list(result.warnings or []),
|
||||
layout_snapshot=meta.get('layout_snapshot') if isinstance(meta.get('layout_snapshot'), dict) else None,
|
||||
asset_id=int(parent_asset.id),
|
||||
classification=file_class,
|
||||
)
|
||||
@@ -682,11 +718,17 @@ def persist_documents_and_candidates(
|
||||
strip_attachment_payloads(meta)
|
||||
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts
|
||||
|
||||
layout_versions = schedule_document_layouts(
|
||||
documents, created_by_id=int(intake.user_id) if intake.user_id else None,
|
||||
)
|
||||
return {
|
||||
'document_count': len(documents),
|
||||
'candidate_count': len(candidates),
|
||||
'linked_asset_count': linked_asset_count,
|
||||
'created_asset_count': created_asset_count,
|
||||
'layout_version_count': len(layout_versions),
|
||||
'documents': [_serialize_document_brief(d, include_text=False) for d in documents],
|
||||
'candidates': [_serialize_candidate_brief(c) for c in candidates],
|
||||
}
|
||||
|
||||
@@ -45,6 +45,29 @@ from app.services.shipping_notice.document_layout.html_table import (
|
||||
map_html_table_to_schema,
|
||||
parse_html_grid,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import (
|
||||
PositionedCharacter,
|
||||
TextAlignedCell,
|
||||
TextCellAlignmentResult,
|
||||
align_html_cells_from_positioned_text,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
NativePdfPage,
|
||||
build_native_pdf_layout_candidate,
|
||||
extract_native_pdf_pages,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import (
|
||||
OcrCellEvidence,
|
||||
OcrLine,
|
||||
OcrTableEvidence,
|
||||
build_ocr_table_evidence,
|
||||
extract_ocr_lines,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.schema_mapping import (
|
||||
layout_table_to_grid,
|
||||
map_layout_document_to_schema,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'LAYOUT_SCHEMA_VERSION',
|
||||
@@ -67,6 +90,21 @@ __all__ = [
|
||||
'MinerUClientConfig',
|
||||
'MinerUParseCandidate',
|
||||
'MinerUTextCandidate',
|
||||
'PositionedCharacter',
|
||||
'TextAlignedCell',
|
||||
'TextCellAlignmentResult',
|
||||
'NativePdfPage',
|
||||
'build_native_pdf_layout_candidate',
|
||||
'extract_native_pdf_pages',
|
||||
'build_html_layout_candidate',
|
||||
'OcrCellEvidence',
|
||||
'OcrLine',
|
||||
'OcrTableEvidence',
|
||||
'build_ocr_table_evidence',
|
||||
'extract_ocr_lines',
|
||||
'layout_table_to_grid',
|
||||
'map_layout_document_to_schema',
|
||||
'align_html_cells_from_positioned_text',
|
||||
'canonical_layout_checksum',
|
||||
'evaluate_layout',
|
||||
'inspect_mineru_capabilities',
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/evaluation.py
|
||||
|
||||
用途:定义版面解析人工真值格式并计算阶段 L0/L2/L3 的表格与单元格质量指标。
|
||||
用途:定义版面和 PDF 订单行人工真值格式,并计算阶段 L0/L2/L3 的质量指标与安全门禁。
|
||||
依赖:Pydantic 2、document_layout.contracts。
|
||||
逻辑:人工标注保存期望表格/单元格位置;候选解析结果按页与几何交并比匹配,输出可审计指标而非业务订单值。
|
||||
逻辑:人工标注保存期望表格/单元格位置及订单行事实;候选解析结果按页与几何交并比匹配,
|
||||
再由匿名聚合指标验证删除项和高风险字段不会被错误自动放行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,6 +20,15 @@ from app.services.shipping_notice.document_layout.contracts import (
|
||||
|
||||
|
||||
ANNOTATION_SCHEMA_VERSION = 'shipping_document_layout_annotation.v1'
|
||||
PDF_ORDER_TRUTH_SCHEMA_VERSION = 'shipping_pdf_order_truth.v1'
|
||||
REQUIRED_PDF_ORDER_SAMPLE_CATEGORIES = frozenset({
|
||||
'normal_multi_line', 'continued_row', 'deleted_line', 'cross_page_header',
|
||||
'scanned_ocr', 'unreadable_pdf',
|
||||
})
|
||||
HIGH_RISK_PDF_ORDER_FIELDS = frozenset({
|
||||
'line_no', 'part_number', 'customer_part_number', 'aws_part_number',
|
||||
'reservation_id', 'qty', 'unit_price', 'amount', 'required_date',
|
||||
})
|
||||
|
||||
|
||||
class LayoutAnnotationModel(BaseModel):
|
||||
@@ -27,6 +37,139 @@ class LayoutAnnotationModel(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class AnnotatedOrderField(LayoutAnnotationModel):
|
||||
"""保存一项高风险订单字段真值及其版面单元格证据引用。"""
|
||||
|
||||
field_code: str = Field(min_length=1, max_length=80)
|
||||
value: str | int | float
|
||||
evidence_cell_ids: list[str] = Field(min_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_high_risk_evidence(self) -> 'AnnotatedOrderField':
|
||||
"""高风险字段必须能回指至少一个人工确认的版面单元格。"""
|
||||
if self.field_code not in HIGH_RISK_PDF_ORDER_FIELDS:
|
||||
raise ValueError('order truth may only contain high-risk field codes')
|
||||
if len(self.evidence_cell_ids) != len(set(self.evidence_cell_ids)):
|
||||
raise ValueError('order field evidence_cell_ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class AnnotatedOrderLine(LayoutAnnotationModel):
|
||||
"""记录视觉行块、删除归属及可自动放行前必须校验的订单字段真值。"""
|
||||
|
||||
line_id: str = Field(min_length=1, max_length=160)
|
||||
table_annotation_id: str = Field(min_length=1, max_length=160)
|
||||
line_cell_ids: list[str] = Field(min_length=1)
|
||||
status: str = Field(pattern=r'^(active|deleted|needs_review)$')
|
||||
fields: list[AnnotatedOrderField] = Field(default_factory=list)
|
||||
deletion_marker_cell_id: str | None = None
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_line_status(self) -> 'AnnotatedOrderLine':
|
||||
"""删除项必须有独立删除证据;待复核项不能被伪装成可放行字段。"""
|
||||
if len(self.line_cell_ids) != len(set(self.line_cell_ids)):
|
||||
raise ValueError('order line cell ids must be unique')
|
||||
if self.status == 'deleted' and not self.deletion_marker_cell_id:
|
||||
raise ValueError('deleted order line requires deletion_marker_cell_id')
|
||||
if self.status != 'deleted' and self.deletion_marker_cell_id:
|
||||
raise ValueError('only deleted order line may reference deletion marker')
|
||||
codes = [item.field_code for item in self.fields]
|
||||
if len(codes) != len(set(codes)):
|
||||
raise ValueError('order line field codes must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class PdfOrderTruthAnnotation(LayoutAnnotationModel):
|
||||
"""保存脱敏 PDF 订单真值,驱动行重建、删除归属和自动放行的阶段 Review。"""
|
||||
|
||||
schema_version: str = PDF_ORDER_TRUTH_SCHEMA_VERSION
|
||||
sample_id: str = Field(min_length=1, max_length=160)
|
||||
content_hash: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
categories: list[str] = Field(min_length=1)
|
||||
lines: list[AnnotatedOrderLine] = Field(min_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_pdf_order_truth(self) -> 'PdfOrderTruthAnnotation':
|
||||
"""保证样本类别、行标识和删除项审计引用在真值录入时即可发现错误。"""
|
||||
if self.schema_version != PDF_ORDER_TRUTH_SCHEMA_VERSION:
|
||||
raise ValueError('unsupported PDF order truth schema_version')
|
||||
if len(self.categories) != len(set(self.categories)):
|
||||
raise ValueError('PDF order truth categories must be unique')
|
||||
line_ids = [item.line_id for item in self.lines]
|
||||
if len(line_ids) != len(set(line_ids)):
|
||||
raise ValueError('PDF order truth line ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class PdfOrderQualityMetrics(LayoutAnnotationModel):
|
||||
"""汇总脱敏真值集的行级结果,不包含 PDF 原文、字段值或用户身份。"""
|
||||
|
||||
active_truth_lines: int = Field(ge=0)
|
||||
deleted_truth_lines: int = Field(ge=0)
|
||||
active_lines_auto_released: int = Field(ge=0)
|
||||
active_lines_misdeleted: int = Field(ge=0)
|
||||
high_risk_auto_released_fields: int = Field(ge=0)
|
||||
incorrect_high_risk_auto_released_fields: int = Field(ge=0)
|
||||
unreliable_truth_lines: int = Field(ge=0)
|
||||
unreliable_lines_sent_to_review: int = Field(ge=0)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_metric_totals(self) -> 'PdfOrderQualityMetrics':
|
||||
"""拒绝分子大于分母的指标,避免用无效数据错误开启自动放行。"""
|
||||
if self.active_lines_misdeleted > self.active_truth_lines:
|
||||
raise ValueError('misdeleted active lines exceed active truth lines')
|
||||
if self.incorrect_high_risk_auto_released_fields > self.high_risk_auto_released_fields:
|
||||
raise ValueError('incorrect high-risk fields exceed auto-released fields')
|
||||
if self.unreliable_lines_sent_to_review > self.unreliable_truth_lines:
|
||||
raise ValueError('reviewed unreliable lines exceed unreliable truth lines')
|
||||
return self
|
||||
|
||||
|
||||
class PdfOrderQualityGate(LayoutAnnotationModel):
|
||||
"""表达安全优先的 PDF 自动放行结论及其不可绕过的失败原因。"""
|
||||
|
||||
passed: bool
|
||||
reasons: list[str]
|
||||
|
||||
|
||||
def review_pdf_order_quality_gate(
|
||||
annotations: list[dict | PdfOrderTruthAnnotation],
|
||||
metrics: dict | PdfOrderQualityMetrics,
|
||||
) -> PdfOrderQualityGate:
|
||||
"""
|
||||
审查 PDF 订单 IDP 的阶段质量门禁。
|
||||
|
||||
核心逻辑:要求六类脱敏真值样本齐全;并强制有效行零误删、高风险自动放行字段零错误、
|
||||
所有不可靠行均已转人工复核。覆盖率不设最低值,避免为提高自动化比例降低安全边界。
|
||||
|
||||
Args:
|
||||
annotations: 业务确认的 PDF 订单真值;每个样本仅保存 hash、类别和脱敏行事实。
|
||||
metrics: 对同一真值集计算的匿名行级质量计数。
|
||||
|
||||
Returns:
|
||||
PdfOrderQualityGate: passed 为 True 才允许后续阶段尝试自动放行。
|
||||
"""
|
||||
truth = [
|
||||
item if isinstance(item, PdfOrderTruthAnnotation) else PdfOrderTruthAnnotation.model_validate(item)
|
||||
for item in annotations
|
||||
]
|
||||
quality = metrics if isinstance(metrics, PdfOrderQualityMetrics) else PdfOrderQualityMetrics.model_validate(metrics)
|
||||
reasons: list[str] = []
|
||||
if not truth:
|
||||
reasons.append('pdf_order_truth_set_missing')
|
||||
categories = {category for item in truth for category in item.categories}
|
||||
missing_categories = sorted(REQUIRED_PDF_ORDER_SAMPLE_CATEGORIES - categories)
|
||||
if missing_categories:
|
||||
reasons.append(f"pdf_order_truth_categories_missing:{','.join(missing_categories)}")
|
||||
if quality.active_lines_misdeleted:
|
||||
reasons.append('active_order_line_misdeleted')
|
||||
if quality.incorrect_high_risk_auto_released_fields:
|
||||
reasons.append('incorrect_high_risk_field_auto_released')
|
||||
if quality.unreliable_lines_sent_to_review != quality.unreliable_truth_lines:
|
||||
reasons.append('unreliable_order_line_not_sent_to_review')
|
||||
return PdfOrderQualityGate(passed=not reasons, reasons=reasons)
|
||||
|
||||
|
||||
class AnnotatedCell(LayoutAnnotationModel):
|
||||
"""记录人工确认的单元格位置、列归属和可选业务字段,不保存邮件身份信息。"""
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/html_layout.py
|
||||
|
||||
用途:把 EML 正文中受控 HTML table 转换为统一 shipping_document_layout.v1 逻辑布局候选。
|
||||
依赖:BeautifulSoup HTML 网格解析、布局契约。
|
||||
逻辑:DOM 直接证明 rowspan/colspan;坐标仅表示逻辑行列,不冒充屏幕像素,结果固定 needs_review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import (
|
||||
LayoutBBox,
|
||||
LayoutCell,
|
||||
LayoutDocument,
|
||||
LayoutIssue,
|
||||
LayoutPage,
|
||||
LayoutParserInfo,
|
||||
LayoutQuality,
|
||||
LayoutRow,
|
||||
LayoutTable,
|
||||
normalize_layout_text,
|
||||
stable_layout_id,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
|
||||
|
||||
def build_html_layout_candidate(
|
||||
*, document_id: int, content_hash: str, tables: list[str],
|
||||
) -> LayoutDocument:
|
||||
"""
|
||||
将已清洗 HTML 表格列表转换为逻辑坐标布局。
|
||||
|
||||
Args:
|
||||
document_id: email_body Document 主键。
|
||||
content_hash: 正文文本哈希,用于稳定对象 ID。
|
||||
tables: 只包含 table/tr/th/td 及跨度属性的清洗片段。
|
||||
Returns:
|
||||
DOM 行列可追溯但没有浏览器像素证据的 needs_review 布局。
|
||||
"""
|
||||
parsed = []
|
||||
issues: list[LayoutIssue] = [LayoutIssue(
|
||||
code='html_logical_coordinates_only', severity='blocking', page_no=1,
|
||||
)]
|
||||
for index, html in enumerate(tables):
|
||||
table_ref = stable_layout_id('html-source-table', content_hash, index)
|
||||
try:
|
||||
parsed.append((index, parse_html_grid(html, table_id=table_ref)))
|
||||
except Exception:
|
||||
issues.append(LayoutIssue(
|
||||
code='html_table_invalid', severity='blocking', page_no=1,
|
||||
table_id=table_ref,
|
||||
))
|
||||
page_width = float(max((grid.column_count for _index, grid in parsed), default=1))
|
||||
page_height = float(max(
|
||||
sum(grid.row_count for _index, grid in parsed) + max(len(parsed) - 1, 0), 1,
|
||||
))
|
||||
offset = 0.0
|
||||
layout_tables: list[LayoutTable] = []
|
||||
for table_index, grid in parsed:
|
||||
table_id = stable_layout_id('table', content_hash, 1, table_index)
|
||||
table_bbox = LayoutBBox(
|
||||
x0=0, y0=offset, x1=float(grid.column_count), y1=offset + grid.row_count,
|
||||
)
|
||||
rows: list[LayoutRow] = []
|
||||
for row_index in range(grid.row_count):
|
||||
source_cells = [item for item in grid.cells if item.row_index == row_index]
|
||||
if not source_cells:
|
||||
continue
|
||||
role = 'header' if all(item.is_header for item in source_cells) else 'data'
|
||||
cells = []
|
||||
for source in sorted(source_cells, key=lambda item: item.column_index):
|
||||
bbox = LayoutBBox(
|
||||
x0=float(source.column_index), y0=offset + source.row_index,
|
||||
x1=float(source.column_index + source.column_span),
|
||||
y1=offset + source.row_index + source.row_span,
|
||||
)
|
||||
cells.append(LayoutCell(
|
||||
cell_id=stable_layout_id(
|
||||
'cell', content_hash, 1, table_index,
|
||||
source.row_index, source.column_index,
|
||||
),
|
||||
row_index=source.row_index, column_index=source.column_index,
|
||||
row_span=source.row_span, column_span=source.column_span,
|
||||
text=source.text, normalized_text=normalize_layout_text(source.text),
|
||||
bbox=bbox,
|
||||
normalized_bbox=_normalized(bbox, page_width, page_height),
|
||||
source='html', confidence=1, role=role,
|
||||
))
|
||||
rows.append(LayoutRow(
|
||||
row_id=stable_layout_id('row', content_hash, 1, table_index, row_index),
|
||||
row_index=row_index, cells=cells, role=role,
|
||||
))
|
||||
layout_tables.append(LayoutTable(
|
||||
table_id=table_id, bbox=table_bbox,
|
||||
normalized_bbox=_normalized(table_bbox, page_width, page_height),
|
||||
rows=rows,
|
||||
header_row_indices=[item.row_index for item in rows if item.role == 'header'],
|
||||
confidence=1, status='needs_review',
|
||||
))
|
||||
offset += grid.row_count + 1
|
||||
if not layout_tables:
|
||||
issues.append(LayoutIssue(code='html_table_structure_missing', severity='blocking', page_no=1))
|
||||
return LayoutDocument(
|
||||
document_id=document_id, content_hash=content_hash,
|
||||
parser=LayoutParserInfo(name='eml-html-dom', version='v1'),
|
||||
pages=[LayoutPage(
|
||||
page_no=1, width=page_width, height=page_height,
|
||||
tokens=[], tables=layout_tables,
|
||||
)],
|
||||
quality=LayoutQuality(status='needs_review', confidence=0, issues=issues),
|
||||
)
|
||||
|
||||
|
||||
def _normalized(bbox: LayoutBBox, width: float, height: float) -> LayoutBBox:
|
||||
"""将 DOM 逻辑网格坐标转换为 0..1。"""
|
||||
return LayoutBBox(
|
||||
x0=bbox.x0 / width, y0=bbox.y0 / height,
|
||||
x1=bbox.x1 / width, y1=bbox.y1 / height,
|
||||
)
|
||||
@@ -230,6 +230,28 @@ def map_html_table_to_schema(
|
||||
包含列诊断、有效/删除/汇总行和 evidence_ref 的映射结果。
|
||||
"""
|
||||
grid = parse_html_grid(html, table_id=table_id)
|
||||
return map_html_grid_to_schema(
|
||||
grid, page_no=page_no, table_id=table_id, contract=contract,
|
||||
)
|
||||
|
||||
|
||||
def map_html_grid_to_schema(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
page_no: int,
|
||||
table_id: str,
|
||||
contract: TableHeaderContract,
|
||||
) -> HtmlTableMappingResult:
|
||||
"""
|
||||
按冻结 Schema 映射已验证网格,并保留网格自身 cell_id 作为证据身份。
|
||||
|
||||
Args:
|
||||
grid: 来自 HTML 或 layout.v1 的固定矩形网格。
|
||||
page_no/table_id: 当前布局契约中的来源位置。
|
||||
contract: Run 冻结 Schema 编译出的精确表头契约。
|
||||
Returns:
|
||||
复用统一安全规则的列、行和字段候选。
|
||||
"""
|
||||
header_index, score = _select_header_row(grid, contract)
|
||||
if header_index is None:
|
||||
return HtmlTableMappingResult(
|
||||
@@ -271,6 +293,7 @@ def map_html_table_to_schema(
|
||||
for row_index in range(grid.row_count)
|
||||
if row_index > header_index
|
||||
]
|
||||
issues.extend(_apply_exclusive_deletion_markers(grid, mapped_rows))
|
||||
required_codes = {
|
||||
code for code, config in contract.fields_by_code.items()
|
||||
if config.get('scope') == 'line' and config.get('required')
|
||||
@@ -423,6 +446,12 @@ def _normalize_html_value(raw: str, config: dict[str, Any] | None) -> Any:
|
||||
"""按冻结字段类型、normalizer 和 validator 转换 HTML 单元格;非法值留空不跨列补偿。"""
|
||||
if config is None:
|
||||
return None
|
||||
# [STEP] 表格错列时,典型 SAP 项次会落入 Reservation ID 列;不能只靠数字长度放行。
|
||||
if (
|
||||
str(config.get('field_code') or '') == 'reservation_id'
|
||||
and _is_probable_sap_line_number(raw)
|
||||
):
|
||||
return None
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
candidate: Any = raw
|
||||
if value_type in {'decimal', 'integer'}:
|
||||
@@ -440,6 +469,11 @@ def _normalize_html_value(raw: str, config: dict[str, Any] | None) -> Any:
|
||||
return None
|
||||
|
||||
|
||||
def _is_probable_sap_line_number(value: Any) -> bool:
|
||||
"""识别典型五位 SAP 项次,防止 PDF 表格错列将 00010/00020 误作预约号。"""
|
||||
return bool(re.fullmatch(r'0{3,4}[1-9]\d?', str(value or '').strip()))
|
||||
|
||||
|
||||
def _has_explicit_zero_quantity(
|
||||
row: list[HtmlGridSlot | None], *, columns: list[HtmlColumnMapping],
|
||||
) -> bool:
|
||||
@@ -460,6 +494,40 @@ def _has_explicit_zero_quantity(
|
||||
return value is not None and value == 0
|
||||
|
||||
|
||||
def _apply_exclusive_deletion_markers(
|
||||
grid: HtmlGrid, rows: list[HtmlMappedRow],
|
||||
) -> list[str]:
|
||||
"""将独占删除标记归属到唯一相邻明细;存在零数量竞争行时保留有效行并转复核。"""
|
||||
issues: list[str] = []
|
||||
for index, marker_row in enumerate(rows):
|
||||
if not _is_exclusive_deletion_marker_row(grid, marker_row.row_index):
|
||||
continue
|
||||
previous = rows[index - 1] if index else None
|
||||
if previous is None or previous.role != 'data' or not previous.fields:
|
||||
issues.append('deletion_marker_without_unique_previous_line')
|
||||
continue
|
||||
# A zero-Qty row before a positive adjacent row is stronger deletion evidence than
|
||||
# a displaced marker. Do not silently delete the positive row in that situation.
|
||||
if any(item.role == 'deleted' for item in rows[:index - 1]):
|
||||
issues.append('deletion_marker_target_ambiguous')
|
||||
continue
|
||||
rows[index - 1] = previous.model_copy(update={'role': 'deleted', 'fields': []})
|
||||
return issues
|
||||
|
||||
|
||||
def _is_exclusive_deletion_marker_row(grid: HtmlGrid, row_index: int) -> bool:
|
||||
"""仅接受整行只表达删除含义的标记,避免把描述列中的普通文字误当删除指令。"""
|
||||
texts = [
|
||||
normalize_table_header(slot.text)
|
||||
for slot in grid.rows[row_index]
|
||||
if slot is not None and slot.text.strip()
|
||||
]
|
||||
if not texts:
|
||||
return False
|
||||
markers = {'item deleted', 'deleted item', '项目已删除', '項目已刪除'}
|
||||
return all(text in markers for text in texts)
|
||||
|
||||
|
||||
def _header_candidates(grid: HtmlGrid, *, row_index: int, column_index: int) -> list[str]:
|
||||
"""生成叶表头、上层合并表头和组合路径的标准化候选,保持精确匹配。"""
|
||||
displays = _header_display_path(grid, row_index, column_index)
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/lifecycle.py
|
||||
|
||||
用途:管理 ShippingNoticeDocument 的版面版本、checksum、大小门禁和当前成功快照。
|
||||
依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session。
|
||||
逻辑:相同内容/parser/checksum 幂等复用;失败版本保留审计,只有可用终态更新 Document 当前引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy import and_, func, or_, update
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument
|
||||
|
||||
|
||||
LAYOUT_PARSER_NAME = 'mineru'
|
||||
LAYOUT_BACKEND = 'pipeline'
|
||||
LAYOUT_CONTRACT_VERSION = 'shipping_document_table_snapshot.v1'
|
||||
CURRENT_LAYOUT_STATUSES = frozenset({'ready', 'needs_review'})
|
||||
TERMINAL_LAYOUT_STATUSES = frozenset({'ready', 'needs_review', 'failed', 'unsupported'})
|
||||
|
||||
|
||||
def current_layout_parser_key() -> str:
|
||||
"""生成运维可轮转的 parser 身份;Provider/模型升级必须提升 revision 防止复用旧结果。"""
|
||||
revision = str(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_PARSER_REVISION', 'v3',
|
||||
) or 'v3').strip()
|
||||
return f'{LAYOUT_PARSER_NAME}:{LAYOUT_BACKEND}:{LAYOUT_CONTRACT_VERSION}:{revision}'
|
||||
|
||||
|
||||
def canonical_layout_payload(payload: dict[str, Any]) -> tuple[str, int]:
|
||||
"""返回布局 JSON 的稳定 SHA-256 和 UTF-8 大小,供幂等与容量门禁复用。"""
|
||||
encoded = json.dumps(
|
||||
payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'),
|
||||
).encode('utf-8')
|
||||
return hashlib.sha256(encoded).hexdigest(), len(encoded)
|
||||
|
||||
|
||||
def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any] | None:
|
||||
"""读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。"""
|
||||
version = document.current_layout_version
|
||||
if (
|
||||
version is None
|
||||
or str(version.status or '') not in CURRENT_LAYOUT_STATUSES
|
||||
or not isinstance(version.payload_json, dict)
|
||||
):
|
||||
return None
|
||||
return dict(version.payload_json)
|
||||
|
||||
|
||||
def record_inline_layout_snapshot(
|
||||
document: ShippingNoticeDocument,
|
||||
snapshot: dict[str, Any],
|
||||
*,
|
||||
parser_key: str | None = None,
|
||||
) -> ShippingDocumentLayoutVersion:
|
||||
"""
|
||||
将 Intake 解析阶段已有布局快照转为不可变版本;后续 L1 Job 会复用同一收口逻辑。
|
||||
|
||||
超大 payload 不落正文,只创建 failed 审计版本;相同内容/parser/checksum 重试复用旧终态。
|
||||
"""
|
||||
payload = dict(snapshot)
|
||||
parser_key = str(parser_key or current_layout_parser_key())
|
||||
checksum, payload_size = canonical_layout_payload(payload)
|
||||
source_hash = str(document.content_hash or '').strip().lower()
|
||||
if len(source_hash) != 64:
|
||||
source_hash = hashlib.sha256(
|
||||
f'document:{document.id}:{document.attachment_key}'.encode('utf-8'),
|
||||
).hexdigest()
|
||||
existing = (
|
||||
ShippingDocumentLayoutVersion.query
|
||||
.filter_by(
|
||||
document_id=int(document.id),
|
||||
source_content_hash=source_hash,
|
||||
parser_key=parser_key,
|
||||
payload_checksum=checksum,
|
||||
)
|
||||
.order_by(ShippingDocumentLayoutVersion.version.desc())
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
if existing.status in CURRENT_LAYOUT_STATUSES:
|
||||
document.current_layout_version_id = existing.id
|
||||
return existing
|
||||
|
||||
version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by(
|
||||
document_id=int(document.id),
|
||||
).scalar() or 0) + 1
|
||||
now = datetime.utcnow()
|
||||
provider_status = str(payload.get('status') or 'failed')
|
||||
status = provider_status if provider_status in {
|
||||
'ready', 'needs_review', 'failed', 'unsupported',
|
||||
} else 'failed'
|
||||
max_bytes = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
|
||||
)), 1)
|
||||
issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)})
|
||||
stored_payload: dict[str, Any] | None = payload
|
||||
if payload_size > max_bytes:
|
||||
status = 'failed'
|
||||
stored_payload = None
|
||||
issues.append('shipping_document_layout_snapshot_size_exceeded')
|
||||
version = ShippingDocumentLayoutVersion(
|
||||
document_id=int(document.id),
|
||||
version=version_no,
|
||||
status=status,
|
||||
source_content_hash=source_hash,
|
||||
parser_key=parser_key,
|
||||
parser_name=str(payload.get('provider') or LAYOUT_PARSER_NAME)[:32],
|
||||
parser_version=str(payload.get('provider_version') or '')[:64] or None,
|
||||
backend=str(payload.get('backend') or LAYOUT_BACKEND)[:32],
|
||||
contract_version=str(payload.get('snapshot_version') or LAYOUT_CONTRACT_VERSION)[:64],
|
||||
payload_json=stored_payload,
|
||||
payload_checksum=checksum,
|
||||
payload_size_bytes=payload_size,
|
||||
quality_json=(
|
||||
dict(payload['capability']) if isinstance(payload.get('capability'), dict) else None
|
||||
),
|
||||
issues_json=sorted(set(issues)),
|
||||
attempt_count=1,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
finished_at=now,
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
if status in CURRENT_LAYOUT_STATUSES:
|
||||
document.current_layout_version_id = version.id
|
||||
return version
|
||||
|
||||
|
||||
def schedule_layout_version(
|
||||
document: ShippingNoticeDocument,
|
||||
*,
|
||||
force: bool = False,
|
||||
created_by_id: int | None = None,
|
||||
) -> ShippingDocumentLayoutVersion | None:
|
||||
"""为支持的附件创建唯一 queued 版本和 Job;相同 parser 成功版本默认幂等复用。"""
|
||||
from pathlib import Path
|
||||
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS
|
||||
|
||||
if not bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', False)):
|
||||
return None
|
||||
if document.asset_id is None or Path(str(document.filename or '')).suffix.lower() not in MINERU_SUPPORTED_EXTENSIONS:
|
||||
return None
|
||||
source_hash = str(document.content_hash or '').strip().lower()
|
||||
if len(source_hash) != 64:
|
||||
return None
|
||||
active = ShippingDocumentLayoutVersion.query.filter(
|
||||
ShippingDocumentLayoutVersion.document_id == int(document.id),
|
||||
ShippingDocumentLayoutVersion.status.in_({'queued', 'running'}),
|
||||
).first()
|
||||
if active is not None:
|
||||
return active
|
||||
if not force:
|
||||
reusable = ShippingDocumentLayoutVersion.query.filter_by(
|
||||
document_id=int(document.id), source_content_hash=source_hash,
|
||||
parser_key=current_layout_parser_key(),
|
||||
).filter(ShippingDocumentLayoutVersion.status.in_(tuple(CURRENT_LAYOUT_STATUSES))).order_by(
|
||||
ShippingDocumentLayoutVersion.version.desc(),
|
||||
).first()
|
||||
if reusable is not None:
|
||||
document.current_layout_version_id = reusable.id
|
||||
return reusable
|
||||
version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by(
|
||||
document_id=int(document.id),
|
||||
).scalar() or 0) + 1
|
||||
version = ShippingDocumentLayoutVersion(
|
||||
document_id=int(document.id), version=version_no, status='queued',
|
||||
source_content_hash=source_hash, parser_key=current_layout_parser_key(),
|
||||
parser_name=LAYOUT_PARSER_NAME, backend=LAYOUT_BACKEND,
|
||||
contract_version=LAYOUT_CONTRACT_VERSION, issues_json=[], attempt_count=0,
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_DOCUMENT_LAYOUT,
|
||||
{'layout_version_id': int(version.id)},
|
||||
domain='shipping_notice', business_ref=f'layout:{version.id}',
|
||||
created_by_id=created_by_id, message='等待解析文档版面',
|
||||
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS', 3)),
|
||||
commit=False,
|
||||
)
|
||||
version.job_id = job_id
|
||||
return version
|
||||
|
||||
|
||||
def schedule_document_layouts(
|
||||
documents: list[ShippingNoticeDocument], *, created_by_id: int | None = None,
|
||||
) -> list[ShippingDocumentLayoutVersion]:
|
||||
"""在 Document 持久化事务内为支持附件建立独立布局版本,超量文档保留 skipped 审计。"""
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS
|
||||
|
||||
max_documents = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4,
|
||||
)), 0)
|
||||
eligible = [
|
||||
item for item in documents
|
||||
if item.asset_id is not None
|
||||
and Path(str(item.filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS
|
||||
]
|
||||
result: list[ShippingDocumentLayoutVersion] = []
|
||||
for index, document in enumerate(eligible):
|
||||
if index >= max_documents:
|
||||
existing = ShippingDocumentLayoutVersion.query.filter_by(
|
||||
document_id=int(document.id), source_content_hash=str(document.content_hash or ''),
|
||||
parser_key=current_layout_parser_key(), status='unsupported',
|
||||
).first()
|
||||
if existing is None:
|
||||
version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by(
|
||||
document_id=int(document.id),
|
||||
).scalar() or 0) + 1
|
||||
existing = ShippingDocumentLayoutVersion(
|
||||
document_id=int(document.id), version=version_no, status='unsupported',
|
||||
source_content_hash=str(document.content_hash or ''),
|
||||
parser_key=current_layout_parser_key(),
|
||||
parser_name=LAYOUT_PARSER_NAME, backend=LAYOUT_BACKEND,
|
||||
contract_version=LAYOUT_CONTRACT_VERSION,
|
||||
issues_json=['mineru_intake_document_budget_exceeded'], attempt_count=0,
|
||||
finished_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
result.append(existing)
|
||||
continue
|
||||
version = schedule_layout_version(document, created_by_id=created_by_id)
|
||||
if version is not None:
|
||||
result.append(version)
|
||||
return result
|
||||
|
||||
|
||||
def serialize_layout_version(version: ShippingDocumentLayoutVersion) -> dict[str, Any]:
|
||||
"""返回管理员诊断安全摘要,不暴露 HTML、bbox、正文或 Provider 原始响应。"""
|
||||
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
|
||||
tables = payload.get('tables') if isinstance(payload.get('tables'), list) else []
|
||||
layout_candidate = (
|
||||
payload.get('layout_candidate') if isinstance(payload.get('layout_candidate'), dict) else {}
|
||||
)
|
||||
candidate_pages = (
|
||||
layout_candidate.get('pages') if isinstance(layout_candidate.get('pages'), list) else []
|
||||
)
|
||||
candidate_table_count = sum(
|
||||
len(page.get('tables') or [])
|
||||
for page in candidate_pages
|
||||
if isinstance(page, dict) and isinstance(page.get('tables'), list)
|
||||
)
|
||||
return {
|
||||
'id': version.id, 'document_id': version.document_id, 'version': version.version,
|
||||
'status': version.status, 'parser_name': version.parser_name,
|
||||
'parser_version': version.parser_version, 'backend': version.backend,
|
||||
'contract_version': version.contract_version,
|
||||
'payload_checksum': version.payload_checksum,
|
||||
'payload_size_bytes': version.payload_size_bytes,
|
||||
'table_count': candidate_table_count or len(tables),
|
||||
'issues': list(version.issues_json or []),
|
||||
'attempt_count': version.attempt_count, 'job_id': version.job_id,
|
||||
'is_current': version.document.current_layout_version_id == version.id,
|
||||
'created_at': version.created_at.isoformat() if version.created_at else None,
|
||||
'started_at': version.started_at.isoformat() if version.started_at else None,
|
||||
'finished_at': version.finished_at.isoformat() if version.finished_at else None,
|
||||
}
|
||||
|
||||
|
||||
def list_layout_versions(document_id: int) -> list[dict[str, Any]]:
|
||||
"""列出一个 Document 的布局版本安全摘要。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(document_id))
|
||||
if document is None:
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
raise NotFoundError(
|
||||
'Shipping notice document not found', code='SHIPPING_NOTICE.DOCUMENT_NOT_FOUND',
|
||||
)
|
||||
return [serialize_layout_version(item) for item in ShippingDocumentLayoutVersion.query.filter_by(
|
||||
document_id=int(document.id),
|
||||
).order_by(ShippingDocumentLayoutVersion.version.desc()).all()]
|
||||
|
||||
|
||||
def request_layout_reparse(
|
||||
document_id: int, *, created_by_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""管理员显式创建下一布局版本;活动版本存在时幂等返回同一版本。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(document_id))
|
||||
if document is None:
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
raise NotFoundError(
|
||||
'Shipping notice document not found', code='SHIPPING_NOTICE.DOCUMENT_NOT_FOUND',
|
||||
)
|
||||
version = schedule_layout_version(document, force=True, created_by_id=created_by_id)
|
||||
if version is None:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError(
|
||||
'Document is not eligible for layout parsing',
|
||||
code='SHIPPING_NOTICE.LAYOUT_FILE_TYPE_UNSUPPORTED',
|
||||
)
|
||||
db.session.commit()
|
||||
return serialize_layout_version(version)
|
||||
|
||||
|
||||
def claim_layout_version(
|
||||
version_id: int, *, job_id: int, owned_attempt: int,
|
||||
) -> tuple[ShippingDocumentLayoutVersion, str] | None:
|
||||
"""原子领取 queued/同 Job running 版本并轮转 lease,旧 Worker 立即失效。"""
|
||||
lease = f'{int(job_id)}:{int(owned_attempt)}'
|
||||
now = datetime.utcnow()
|
||||
predicate = or_(
|
||||
ShippingDocumentLayoutVersion.status == 'queued',
|
||||
and_(
|
||||
ShippingDocumentLayoutVersion.status == 'running',
|
||||
ShippingDocumentLayoutVersion.job_id == int(job_id),
|
||||
),
|
||||
)
|
||||
result = db.session.execute(
|
||||
update(ShippingDocumentLayoutVersion)
|
||||
.where(ShippingDocumentLayoutVersion.id == int(version_id), predicate)
|
||||
.values(
|
||||
status='running', job_id=int(job_id), lease_token=lease,
|
||||
attempt_count=int(owned_attempt), started_at=now, updated_at=now,
|
||||
)
|
||||
)
|
||||
if int(result.rowcount or 0) != 1:
|
||||
db.session.rollback()
|
||||
return None
|
||||
db.session.commit()
|
||||
version = db.session.get(ShippingDocumentLayoutVersion, int(version_id))
|
||||
return (version, lease) if version is not None else None
|
||||
|
||||
|
||||
def complete_layout_version(
|
||||
version_id: int, *, lease_token: str, snapshot: dict[str, Any],
|
||||
) -> bool:
|
||||
"""按 lease 条件冻结 payload/checksum;失败版本不覆盖 Document 旧成功引用。"""
|
||||
version = db.session.get(ShippingDocumentLayoutVersion, int(version_id))
|
||||
if version is None or version.status != 'running' or version.lease_token != lease_token:
|
||||
db.session.rollback()
|
||||
return False
|
||||
checksum, payload_size = canonical_layout_payload(snapshot)
|
||||
max_bytes = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
|
||||
)), 1)
|
||||
issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)})
|
||||
provider_status = str(snapshot.get('status') or 'failed')
|
||||
status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed'
|
||||
stored_payload: dict[str, Any] | None = dict(snapshot)
|
||||
if payload_size > max_bytes:
|
||||
status = 'failed'
|
||||
stored_payload = None
|
||||
issues.append('shipping_document_layout_snapshot_size_exceeded')
|
||||
now = datetime.utcnow()
|
||||
version.status = status
|
||||
version.parser_version = str(snapshot.get('provider_version') or '')[:64] or None
|
||||
version.backend = str(snapshot.get('backend') or LAYOUT_BACKEND)[:32]
|
||||
version.payload_json = stored_payload
|
||||
version.payload_checksum = checksum
|
||||
version.payload_size_bytes = payload_size
|
||||
version.quality_json = dict(snapshot['capability']) if isinstance(snapshot.get('capability'), dict) else None
|
||||
version.issues_json = sorted(set(issues))
|
||||
version.lease_token = None
|
||||
version.finished_at = now
|
||||
version.updated_at = now
|
||||
if status in CURRENT_LAYOUT_STATUSES:
|
||||
version.document.current_layout_version_id = version.id
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
|
||||
def sync_layout_after_job_recovery(job: Any) -> None:
|
||||
"""通用 Job 超时回收后同步布局版本,清除旧 lease 或记录最终失败。"""
|
||||
version = ShippingDocumentLayoutVersion.query.filter_by(job_id=int(job.id)).first()
|
||||
if version is None or version.status != 'running':
|
||||
return
|
||||
version.lease_token = None
|
||||
version.updated_at = datetime.utcnow()
|
||||
if str(job.status or '') == 'queued':
|
||||
version.status = 'queued'
|
||||
elif str(job.status or '') in {'failed', 'cancelled'}:
|
||||
version.status = 'failed'
|
||||
version.finished_at = datetime.utcnow()
|
||||
version.issues_json = sorted(set(list(version.issues_json or []) + [
|
||||
'shipping_document_layout_job_exhausted',
|
||||
]))
|
||||
|
||||
|
||||
def sync_layout_after_job_failure(job_id: int) -> None:
|
||||
"""Handler 调用 fail_job 后立即同步版本状态,避免等待超时回收才清 lease。"""
|
||||
from app.models import Job
|
||||
|
||||
job = db.session.get(Job, int(job_id))
|
||||
if job is None:
|
||||
return
|
||||
sync_layout_after_job_recovery(job)
|
||||
db.session.commit()
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
@@ -40,6 +41,7 @@ class MinerUClientConfig:
|
||||
languages: tuple[str, ...] = ('ch',)
|
||||
connect_timeout_seconds: int = 10
|
||||
read_timeout_seconds: int = 300
|
||||
poll_interval_seconds: float = 1.0
|
||||
max_upload_bytes: int = 30 * 1024 * 1024
|
||||
max_response_bytes: int = 20 * 1024 * 1024
|
||||
|
||||
@@ -193,20 +195,7 @@ class MinerUClient:
|
||||
details={'max_bytes': self.config.max_upload_bytes},
|
||||
)
|
||||
|
||||
data = [
|
||||
('backend', self.config.backend),
|
||||
('parse_method', self.config.parse_method),
|
||||
('formula_enable', 'false'),
|
||||
('table_enable', 'true'),
|
||||
('image_analysis', 'false'),
|
||||
('return_md', 'false'),
|
||||
('return_middle_json', 'true'),
|
||||
('return_model_output', 'true'),
|
||||
('return_content_list', 'true'),
|
||||
('return_images', 'false'),
|
||||
('response_format_zip', 'false'),
|
||||
]
|
||||
data.extend(('lang_list', item) for item in self.config.languages)
|
||||
data = _mineru_request_data(self.config)
|
||||
try:
|
||||
response = self.session.post(
|
||||
f'{self.base_url}/file_parse',
|
||||
@@ -252,6 +241,110 @@ class MinerUClient:
|
||||
)
|
||||
return payload
|
||||
|
||||
def parse_file_async(self, *, filename: str, content: bytes) -> dict[str, Any]:
|
||||
"""
|
||||
通过 `/tasks` 提交异步解析并轮询终态结果,避免单条 HTTP 长连接占用 Worker。
|
||||
|
||||
Args:
|
||||
filename: 受支持文件名,仅用于扩展名和 multipart。
|
||||
content: 文件原始字节,受上传上限限制。
|
||||
Returns:
|
||||
与同步 `/file_parse` 相同的 completed 结果对象。
|
||||
Raises:
|
||||
ValidationError: 提交、状态或终态响应不符合协议。
|
||||
ServiceUnavailableError: 网络、5xx 或总等待时间超限。
|
||||
"""
|
||||
extension = Path(str(filename or '')).suffix.lower()
|
||||
if extension not in MINERU_SUPPORTED_EXTENSIONS:
|
||||
raise ValidationError(
|
||||
'MinerU file type is unsupported',
|
||||
code='SHIPPING_NOTICE.LAYOUT_FILE_TYPE_UNSUPPORTED',
|
||||
details={'extension': extension},
|
||||
)
|
||||
if not content:
|
||||
raise ValidationError('MinerU input file is empty', code='SHIPPING_NOTICE.LAYOUT_FILE_EMPTY')
|
||||
if len(content) > self.config.max_upload_bytes:
|
||||
raise ValidationError(
|
||||
'MinerU input file exceeds size limit',
|
||||
code='SHIPPING_NOTICE.LAYOUT_FILE_TOO_LARGE',
|
||||
details={'max_bytes': self.config.max_upload_bytes},
|
||||
)
|
||||
data = _mineru_request_data(self.config)
|
||||
try:
|
||||
response = self.session.post(
|
||||
f'{self.base_url}/tasks',
|
||||
files=[('files', (filename, content, _mime_type(extension)))],
|
||||
data=data,
|
||||
timeout=(self.config.connect_timeout_seconds, self.config.connect_timeout_seconds),
|
||||
)
|
||||
submission = _response_json(response, max_bytes=self.config.max_response_bytes)
|
||||
except requests.exceptions.RequestException as exc:
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU task submission failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
|
||||
) from exc
|
||||
if response.status_code >= 500:
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU task submission failed',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
|
||||
details={'status': response.status_code},
|
||||
)
|
||||
if response.status_code >= 400:
|
||||
raise ValidationError(
|
||||
'MinerU task submission was rejected',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_PARSE_FAILED',
|
||||
details={'status': response.status_code},
|
||||
)
|
||||
task_id = str(submission.get('task_id') or submission.get('id') or '').strip()
|
||||
if not task_id:
|
||||
raise ValidationError(
|
||||
'MinerU task response has no task id',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
deadline = time.monotonic() + max(float(self.config.read_timeout_seconds), 1.0)
|
||||
while time.monotonic() < deadline:
|
||||
status = self._get_async_json(f'/tasks/{task_id}')
|
||||
state = str(status.get('status') or status.get('state') or '').strip().lower()
|
||||
if state in {'completed', 'succeeded', 'success'}:
|
||||
result = self._get_async_json(f'/tasks/{task_id}/result')
|
||||
if str(result.get('status') or '').strip().lower() not in {'completed', 'succeeded', 'success'}:
|
||||
result = {**result, 'status': 'completed', 'task_id': task_id}
|
||||
return result
|
||||
if state in {'failed', 'error', 'cancelled', 'canceled'}:
|
||||
raise ValidationError(
|
||||
'MinerU parse task failed',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_PARSE_FAILED',
|
||||
details={'provider_error_code': _provider_error_code(status.get('error'))},
|
||||
)
|
||||
time.sleep(max(float(self.config.poll_interval_seconds), 0.05))
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU parse task timed out', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
|
||||
)
|
||||
|
||||
def _get_async_json(self, path: str) -> dict[str, Any]:
|
||||
"""读取一个异步任务接口并统一网络、状态码和 JSON 容量错误。"""
|
||||
try:
|
||||
response = self.session.get(
|
||||
f'{self.base_url}{path}',
|
||||
timeout=(self.config.connect_timeout_seconds, self.config.connect_timeout_seconds),
|
||||
)
|
||||
payload = _response_json(response, max_bytes=self.config.max_response_bytes)
|
||||
except requests.exceptions.RequestException as exc:
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU task polling failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
|
||||
) from exc
|
||||
if response.status_code >= 500:
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU task polling failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
|
||||
details={'status': response.status_code},
|
||||
)
|
||||
if response.status_code >= 400:
|
||||
raise ValidationError(
|
||||
'MinerU task polling response is invalid',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
details={'status': response.status_code},
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def parse_mineru_candidate(payload: dict[str, Any]) -> MinerUParseCandidate:
|
||||
"""
|
||||
@@ -404,6 +497,46 @@ def _read_limited_response(response: requests.Response, *, max_bytes: int) -> by
|
||||
return b''.join(chunks)
|
||||
|
||||
|
||||
def _mineru_request_data(config: MinerUClientConfig) -> list[tuple[str, str]]:
|
||||
"""生成同步/异步接口共用的 pipeline multipart 参数。"""
|
||||
data = [
|
||||
('backend', config.backend),
|
||||
('parse_method', config.parse_method),
|
||||
('formula_enable', 'false'),
|
||||
('table_enable', 'true'),
|
||||
('image_analysis', 'false'),
|
||||
('return_md', 'false'),
|
||||
('return_middle_json', 'true'),
|
||||
('return_model_output', 'true'),
|
||||
('return_content_list', 'true'),
|
||||
('return_images', 'false'),
|
||||
('response_format_zip', 'false'),
|
||||
]
|
||||
data.extend(('lang_list', item) for item in config.languages)
|
||||
return data
|
||||
|
||||
|
||||
def _response_json(response: requests.Response, *, max_bytes: int) -> dict[str, Any]:
|
||||
"""读取有限大小 JSON 响应;兼容测试替身和 requests 非流式 GET。"""
|
||||
if hasattr(response, 'iter_content'):
|
||||
raw = _read_limited_response(response, max_bytes=max_bytes)
|
||||
else: # pragma: no cover - requests.Response 始终实现 iter_content
|
||||
raw = bytes(response.content or b'')
|
||||
try:
|
||||
payload = json.loads(raw.decode(response.encoding or 'utf-8'))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise ValidationError(
|
||||
'MinerU response is not valid JSON',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
) from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError(
|
||||
'MinerU response must be an object',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def _decode_json_field(value: Any, *, field: str) -> Any:
|
||||
"""解包 MinerU 将 middle/model/content JSON 作为字符串返回的协议形式。"""
|
||||
parsed = value
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/native_pdf.py
|
||||
|
||||
用途:用项目既有 PDFium 提取原生 PDF 字符坐标、页面渲染,并组装保守的 layout.v1 表格候选。
|
||||
依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐和布局契约。
|
||||
逻辑:MinerU 提供整表与 HTML;PDFium提供独立字符/图像证据;只有严格匹配的 cell 才写入候选,整体仍固定 needs_review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pypdfium2 as pdfium
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import (
|
||||
LayoutBBox,
|
||||
LayoutCell,
|
||||
LayoutDocument,
|
||||
LayoutIssue,
|
||||
LayoutPage,
|
||||
LayoutParserInfo,
|
||||
LayoutQuality,
|
||||
LayoutRow,
|
||||
LayoutTable,
|
||||
LayoutToken,
|
||||
normalize_layout_text,
|
||||
stable_layout_id,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.mineru import MinerUParseCandidate
|
||||
from app.services.shipping_notice.document_layout.opencv_table import (
|
||||
reconstruct_opencv_table_geometry,
|
||||
validate_opencv_cell_text,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import build_ocr_table_evidence
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import (
|
||||
PositionedCharacter,
|
||||
align_html_cells_from_positioned_text,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NativePdfPage:
|
||||
"""保存单页原生字符和渲染图;对象仅在 Worker 内存中存在。"""
|
||||
|
||||
page_no: int
|
||||
width: float
|
||||
height: float
|
||||
rotation: int
|
||||
characters: list[PositionedCharacter]
|
||||
image: np.ndarray
|
||||
|
||||
|
||||
def extract_native_pdf_pages(content: bytes, *, render_scale: float = 2.0) -> list[NativePdfPage]:
|
||||
"""
|
||||
从 PDF bytes 提取左上原点字符坐标和页面图。
|
||||
|
||||
Args:
|
||||
content: 原始 PDF 字节,不写文件和日志。
|
||||
render_scale: OpenCV 网格检测使用的渲染倍率,必须为正数。
|
||||
Returns:
|
||||
连续页列表;扫描 PDF 可返回无字符页面,但仍保留页面尺寸和图像。
|
||||
Raises:
|
||||
ValueError: 内容为空、倍率非法或 PDFium 无法打开文件。
|
||||
"""
|
||||
if not content or render_scale <= 0:
|
||||
raise ValueError('native PDF content and positive render scale are required')
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
pages: list[NativePdfPage] = []
|
||||
for page_index in range(len(pdf)):
|
||||
page = pdf[page_index]
|
||||
width, height = page.get_size()
|
||||
text_page = page.get_textpage()
|
||||
characters: list[PositionedCharacter] = []
|
||||
for char_index in range(text_page.count_chars()):
|
||||
text = text_page.get_text_range(char_index, 1)
|
||||
if not text or not normalize_layout_text(text):
|
||||
continue
|
||||
left, bottom, right, top = text_page.get_charbox(char_index, loose=True)
|
||||
if right <= left or top <= bottom:
|
||||
continue
|
||||
try:
|
||||
characters.append(PositionedCharacter(
|
||||
text=text,
|
||||
bbox=LayoutBBox(
|
||||
x0=left, y0=height - top, x1=right, y1=height - bottom,
|
||||
),
|
||||
source_index=len(characters),
|
||||
))
|
||||
except ValueError:
|
||||
continue
|
||||
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
|
||||
pages.append(NativePdfPage(
|
||||
page_no=page_index + 1,
|
||||
width=float(width),
|
||||
height=float(height),
|
||||
rotation=rotation if rotation in {0, 90, 180, 270} else 0,
|
||||
characters=characters,
|
||||
image=np.asarray(page.render(scale=render_scale).to_numpy()).copy(),
|
||||
))
|
||||
return pages
|
||||
|
||||
|
||||
def build_native_pdf_layout_candidate(
|
||||
*,
|
||||
document_id: int,
|
||||
content_hash: str,
|
||||
content: bytes,
|
||||
mineru: MinerUParseCandidate,
|
||||
) -> LayoutDocument:
|
||||
"""
|
||||
组合 MinerU HTML 与 PDFium 独立证据,生成始终 needs_review 的 layout.v1 候选。
|
||||
|
||||
Args:
|
||||
document_id: 当前 ShippingNoticeDocument 主键。
|
||||
content_hash: 当前附件 SHA-256,用于稳定 ID 和契约校验。
|
||||
content: 原始 PDF 字节。
|
||||
mineru: 同一文件的 MinerU pipeline 候选。
|
||||
Returns:
|
||||
通过完整布局契约校验的候选;没有可证 cell 时保留空表和 blocking issue。
|
||||
"""
|
||||
native_pages = extract_native_pdf_pages(content)
|
||||
mineru_pages = {item.page_no: item for item in mineru.pages}
|
||||
issues: list[LayoutIssue] = [LayoutIssue(
|
||||
code='document_cell_truth_deferred', severity='blocking',
|
||||
)]
|
||||
pages: list[LayoutPage] = []
|
||||
for native in native_pages:
|
||||
page_candidate = mineru_pages.get(native.page_no)
|
||||
tables: list[LayoutTable] = []
|
||||
page_tokens: dict[str, LayoutToken] = {}
|
||||
for table_index, table_candidate in enumerate(page_candidate.tables if page_candidate else []):
|
||||
try:
|
||||
grid = parse_html_grid(table_candidate.html, table_id=table_candidate.candidate_id)
|
||||
cells, method_issues = _candidate_cells(
|
||||
native=native, grid=grid, table_bbox=table_candidate.bbox,
|
||||
)
|
||||
except Exception:
|
||||
issues.append(LayoutIssue(
|
||||
code='native_pdf_table_candidate_invalid', severity='blocking', page_no=native.page_no,
|
||||
table_id=table_candidate.candidate_id,
|
||||
))
|
||||
continue
|
||||
for code in method_issues:
|
||||
issues.append(LayoutIssue(
|
||||
code=code, severity='blocking', page_no=native.page_no,
|
||||
table_id=table_candidate.candidate_id,
|
||||
))
|
||||
if not cells:
|
||||
continue
|
||||
try:
|
||||
layout_table = _layout_table(
|
||||
native=native,
|
||||
grid=grid,
|
||||
table_bbox=table_candidate.bbox,
|
||||
content_hash=content_hash,
|
||||
table_index=table_index,
|
||||
cells=cells,
|
||||
page_tokens=page_tokens,
|
||||
)
|
||||
except Exception:
|
||||
issues.append(LayoutIssue(
|
||||
code='native_pdf_layout_table_invalid', severity='blocking',
|
||||
page_no=native.page_no, table_id=table_candidate.candidate_id,
|
||||
))
|
||||
continue
|
||||
tables.append(layout_table)
|
||||
if page_candidate and page_candidate.tables and not tables:
|
||||
issues.append(LayoutIssue(
|
||||
code='native_pdf_table_cells_unresolved', severity='blocking', page_no=native.page_no,
|
||||
))
|
||||
pages.append(LayoutPage(
|
||||
page_no=native.page_no, width=native.width, height=native.height,
|
||||
rotation=native.rotation,
|
||||
tokens=[page_tokens[token_id] for token_id in sorted(page_tokens)],
|
||||
tables=tables,
|
||||
))
|
||||
if not any(page.tables for page in pages):
|
||||
issues.append(LayoutIssue(code='native_pdf_no_resolved_tables', severity='blocking'))
|
||||
return LayoutDocument(
|
||||
document_id=document_id,
|
||||
content_hash=content_hash,
|
||||
parser=LayoutParserInfo(
|
||||
name='mineru-pipeline+pdfium+rapidocr',
|
||||
version=str(mineru.provider_version or 'unknown'),
|
||||
),
|
||||
pages=pages,
|
||||
quality=LayoutQuality(status='needs_review', confidence=0, issues=issues),
|
||||
)
|
||||
|
||||
|
||||
def _candidate_cells(
|
||||
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox,
|
||||
) -> tuple[dict[str, dict[str, Any]], list[str]]:
|
||||
"""优先唯一文本对齐,失败后仅对严格有框表使用 OpenCV 双门禁。"""
|
||||
alignment = align_html_cells_from_positioned_text(
|
||||
grid, characters=native.characters, table_bbox=table_bbox,
|
||||
page_width=native.width, page_height=native.height,
|
||||
)
|
||||
if alignment.complete:
|
||||
return {
|
||||
item.cell_id: {
|
||||
'bbox': item.bbox,
|
||||
'tokens': [
|
||||
_native_layout_token(native=native, glyph_index=index, content_hash='pending')
|
||||
for index in item.glyph_indices
|
||||
],
|
||||
'source': 'native_text', 'confidence': 1,
|
||||
}
|
||||
for item in alignment.cells
|
||||
}, ['native_pdf_cells_from_unique_text_candidate']
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
native.image, page_width=native.width, page_height=native.height,
|
||||
table_bbox=table_bbox, grid=grid,
|
||||
)
|
||||
validation = validate_opencv_cell_text(
|
||||
geometry, grid=grid,
|
||||
bounded_text_reader=lambda bbox: _text_within(native.characters, bbox),
|
||||
minimum_match_rate=1.0,
|
||||
required_cell_ids={item.cell_id for item in grid.cells if item.text.strip()},
|
||||
)
|
||||
if not validation.accepted:
|
||||
ocr = build_ocr_table_evidence(
|
||||
image=native.image, page_width=native.width, page_height=native.height,
|
||||
table_bbox=table_bbox, grid=grid,
|
||||
)
|
||||
if not ocr.ready:
|
||||
return {}, sorted(set(
|
||||
alignment.issues + geometry.issues + validation.issues + ocr.issues,
|
||||
))
|
||||
ocr_lines = {index: item for index, item in enumerate(ocr.lines)}
|
||||
return {
|
||||
item.cell_id: {
|
||||
'bbox': item.bbox,
|
||||
'tokens': [
|
||||
_ocr_layout_token(
|
||||
native=native, line=ocr_lines[index], line_index=index,
|
||||
)
|
||||
for index in item.line_indices
|
||||
],
|
||||
'source': 'ocr',
|
||||
'confidence': min(
|
||||
(ocr_lines[index].confidence for index in item.line_indices), default=0,
|
||||
),
|
||||
}
|
||||
for item in ocr.cells
|
||||
}, ['ocr_pdf_cells_from_grid_candidate']
|
||||
cells: dict[str, dict[str, Any]] = {}
|
||||
for item in geometry.cells:
|
||||
indices = _glyph_indices_within(native.characters, item.bbox)
|
||||
expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id)
|
||||
if expected.text.strip() and not indices:
|
||||
return {}, ['native_pdf_opencv_cell_tokens_missing']
|
||||
cells[item.cell_id] = {
|
||||
'bbox': item.bbox,
|
||||
'tokens': [
|
||||
_native_layout_token(native=native, glyph_index=index, content_hash='pending')
|
||||
for index in indices
|
||||
],
|
||||
'source': 'native_text', 'confidence': 1,
|
||||
}
|
||||
return cells, ['native_pdf_cells_from_opencv_candidate']
|
||||
|
||||
|
||||
def _native_layout_token(*, native: NativePdfPage, glyph_index: int, content_hash: str) -> LayoutToken:
|
||||
"""把表格区域内单个 PDF glyph 转为稳定、可引用的 LayoutToken。"""
|
||||
glyph = native.characters[glyph_index]
|
||||
return LayoutToken(
|
||||
token_id=stable_layout_id('token', content_hash, native.page_no, glyph_index),
|
||||
text=glyph.text,
|
||||
normalized_text=normalize_layout_text(glyph.text),
|
||||
bbox=glyph.bbox,
|
||||
normalized_bbox=_normalized_bbox(glyph.bbox, native.width, native.height),
|
||||
source='native_text', confidence=1, line_id=None,
|
||||
)
|
||||
|
||||
|
||||
def _ocr_layout_token(*, native: NativePdfPage, line: Any, line_index: int) -> LayoutToken:
|
||||
"""把一条 OCR 行转为临时 LayoutToken;最终稳定 ID 在组表时绑定 Document/cell。"""
|
||||
return LayoutToken(
|
||||
token_id=stable_layout_id('ocr-token', 'pending', native.page_no, line_index),
|
||||
text=line.text,
|
||||
normalized_text=normalize_layout_text(line.text),
|
||||
bbox=line.bbox,
|
||||
normalized_bbox=_normalized_bbox(line.bbox, native.width, native.height),
|
||||
source='ocr', confidence=line.confidence, line_id=None,
|
||||
)
|
||||
|
||||
|
||||
def _layout_table(
|
||||
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox, content_hash: str,
|
||||
table_index: int, cells: dict[str, dict[str, Any]], page_tokens: dict[str, LayoutToken],
|
||||
) -> LayoutTable:
|
||||
"""按 HTML row/column/span 组装具有真实 bbox 和 token 引用的 needs_review 表格。"""
|
||||
rows: list[LayoutRow] = []
|
||||
for row_index in range(grid.row_count):
|
||||
source_cells = [item for item in grid.cells if item.row_index == row_index]
|
||||
if not source_cells:
|
||||
continue
|
||||
role = 'header' if source_cells and all(item.is_header for item in source_cells) else 'data'
|
||||
layout_cells = []
|
||||
for source in sorted(source_cells, key=lambda item: item.column_index):
|
||||
evidence = cells[source.cell_id]
|
||||
tokens = [
|
||||
token.model_copy(update={
|
||||
'token_id': stable_layout_id(
|
||||
'token', content_hash, native.page_no, table_index,
|
||||
source.row_index, source.column_index, token.token_id,
|
||||
),
|
||||
})
|
||||
for token in evidence['tokens']
|
||||
]
|
||||
for token in tokens:
|
||||
page_tokens[token.token_id] = token
|
||||
layout_cells.append(LayoutCell(
|
||||
cell_id=stable_layout_id(
|
||||
'cell', content_hash, native.page_no, table_index,
|
||||
source.row_index, source.column_index,
|
||||
),
|
||||
row_index=source.row_index, column_index=source.column_index,
|
||||
row_span=source.row_span, column_span=source.column_span,
|
||||
text=source.text, normalized_text=normalize_layout_text(source.text),
|
||||
bbox=evidence['bbox'],
|
||||
normalized_bbox=_normalized_bbox(evidence['bbox'], native.width, native.height),
|
||||
token_ids=[token.token_id for token in tokens],
|
||||
source=evidence['source'], confidence=evidence['confidence'], role=role,
|
||||
))
|
||||
rows.append(LayoutRow(
|
||||
row_id=stable_layout_id('row', content_hash, native.page_no, table_index, row_index),
|
||||
row_index=row_index, cells=layout_cells, role=role,
|
||||
))
|
||||
return LayoutTable(
|
||||
table_id=stable_layout_id('table', content_hash, native.page_no, table_index),
|
||||
bbox=table_bbox,
|
||||
normalized_bbox=_normalized_bbox(table_bbox, native.width, native.height),
|
||||
rows=rows,
|
||||
header_row_indices=[row.row_index for row in rows if row.role == 'header'],
|
||||
confidence=0, status='needs_review',
|
||||
)
|
||||
|
||||
|
||||
def _glyph_indices_within(characters: list[PositionedCharacter], bbox: LayoutBBox) -> list[int]:
|
||||
"""返回中心点落在 bbox 内的 glyph 索引,保持 PDF 文本顺序。"""
|
||||
return [
|
||||
index for index, item in enumerate(characters)
|
||||
if bbox.x0 <= (item.bbox.x0 + item.bbox.x1) / 2 <= bbox.x1
|
||||
and bbox.y0 <= (item.bbox.y0 + item.bbox.y1) / 2 <= bbox.y1
|
||||
]
|
||||
|
||||
|
||||
def _text_within(characters: list[PositionedCharacter], bbox: LayoutBBox) -> str:
|
||||
"""读取 bbox 内原生字符,供 OpenCV 几何的独立文本一致性验证。"""
|
||||
return ''.join(characters[index].text for index in _glyph_indices_within(characters, bbox))
|
||||
|
||||
|
||||
def _normalized_bbox(bbox: LayoutBBox, width: float, height: float) -> LayoutBBox:
|
||||
"""将页面单位 bbox 转换为布局契约 0..1 坐标。"""
|
||||
return LayoutBBox(
|
||||
x0=bbox.x0 / width, y0=bbox.y0 / height,
|
||||
x1=bbox.x1 / width, y1=bbox.y1 / height,
|
||||
)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/ocr_pdf.py
|
||||
|
||||
用途:保留 RapidOCR 文本行多边形坐标,并为扫描 PDF 表格提供严格 cell 候选。
|
||||
依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约。
|
||||
逻辑:OCR 只提供独立文本坐标;必须与多参数有框网格及全部非空 cell 文本一致才输出,结果仍需人工真值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox, normalize_layout_text
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
|
||||
from app.services.shipping_notice.document_layout.opencv_table import (
|
||||
reconstruct_opencv_table_geometry,
|
||||
validate_opencv_cell_text,
|
||||
)
|
||||
|
||||
|
||||
class OcrLayoutModel(BaseModel):
|
||||
"""为 OCR 坐标结果启用严格字段校验。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class OcrLine(OcrLayoutModel):
|
||||
"""保存一条 RapidOCR 文本行、页面坐标和置信度。"""
|
||||
|
||||
text: str = Field(min_length=1)
|
||||
bbox: LayoutBBox
|
||||
confidence: float = Field(ge=0, le=1)
|
||||
|
||||
|
||||
class OcrCellEvidence(OcrLayoutModel):
|
||||
"""保存经几何和文本双门禁确认的 OCR cell 候选。"""
|
||||
|
||||
cell_id: str
|
||||
bbox: LayoutBBox
|
||||
line_indices: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
class OcrTableEvidence(OcrLayoutModel):
|
||||
"""汇总扫描表候选;ready=False 时禁止暴露 cell。"""
|
||||
|
||||
ready: bool
|
||||
lines: list[OcrLine] = Field(default_factory=list)
|
||||
cells: list[OcrCellEvidence] = Field(default_factory=list)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _ocr_engine() -> Any:
|
||||
"""惰性创建 RapidOCR 引擎,避免未使用 OCR 时加载模型。"""
|
||||
from rapidocr_onnxruntime import RapidOCR
|
||||
|
||||
return RapidOCR()
|
||||
|
||||
|
||||
def extract_ocr_lines(
|
||||
image: Any, *, page_width: float, page_height: float, minimum_confidence: float = 0.8,
|
||||
) -> list[OcrLine]:
|
||||
"""
|
||||
将 RapidOCR 图像像素多边形映射为 PDF 页面坐标。
|
||||
|
||||
Args:
|
||||
image: PDFium 渲染的页面 ndarray。
|
||||
page_width/page_height: PDF 页面单位尺寸。
|
||||
minimum_confidence: OCR 行最低可信度;低于阈值完全丢弃。
|
||||
Returns:
|
||||
保持 OCR 返回顺序的文本行坐标。
|
||||
"""
|
||||
if not 0 < minimum_confidence <= 1:
|
||||
raise ValueError('OCR minimum confidence must be within (0, 1]')
|
||||
height, width = image.shape[:2]
|
||||
if width <= 0 or height <= 0 or page_width <= 0 or page_height <= 0:
|
||||
raise ValueError('OCR page dimensions must be positive')
|
||||
result, _elapsed = _ocr_engine()(image)
|
||||
lines: list[OcrLine] = []
|
||||
for item in result or []:
|
||||
if len(item) < 3:
|
||||
continue
|
||||
polygon, raw_text, raw_confidence = item[0], item[1], item[2]
|
||||
text = str(raw_text or '').strip()
|
||||
confidence = float(raw_confidence or 0)
|
||||
if not text or not normalize_layout_text(text) or confidence < minimum_confidence:
|
||||
continue
|
||||
try:
|
||||
xs = [float(point[0]) for point in polygon]
|
||||
ys = [float(point[1]) for point in polygon]
|
||||
bbox = LayoutBBox(
|
||||
x0=min(xs) * page_width / width,
|
||||
y0=min(ys) * page_height / height,
|
||||
x1=max(xs) * page_width / width,
|
||||
y1=max(ys) * page_height / height,
|
||||
)
|
||||
if bbox.x1 > page_width or bbox.y1 > page_height:
|
||||
continue
|
||||
lines.append(OcrLine(text=text, bbox=bbox, confidence=confidence))
|
||||
except (TypeError, ValueError, IndexError):
|
||||
continue
|
||||
return lines
|
||||
|
||||
|
||||
def build_ocr_table_evidence(
|
||||
*, image: Any, page_width: float, page_height: float,
|
||||
table_bbox: LayoutBBox, grid: HtmlGrid,
|
||||
) -> OcrTableEvidence:
|
||||
"""对扫描表执行 OCR 行坐标、OpenCV 网格和全部非空 cell 文本三重门禁。"""
|
||||
try:
|
||||
lines = extract_ocr_lines(image, page_width=page_width, page_height=page_height)
|
||||
except Exception:
|
||||
return OcrTableEvidence(ready=False, issues=['ocr_engine_unavailable'])
|
||||
if not lines:
|
||||
return OcrTableEvidence(ready=False, issues=['ocr_text_missing'])
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
image, page_width=page_width, page_height=page_height,
|
||||
table_bbox=table_bbox, grid=grid,
|
||||
)
|
||||
validation = validate_opencv_cell_text(
|
||||
geometry, grid=grid,
|
||||
bounded_text_reader=lambda bbox: _text_within(lines, bbox),
|
||||
minimum_match_rate=1,
|
||||
required_cell_ids={item.cell_id for item in grid.cells if item.text.strip()},
|
||||
)
|
||||
if not validation.accepted:
|
||||
return OcrTableEvidence(
|
||||
ready=False, issues=sorted(set(geometry.issues + validation.issues)),
|
||||
)
|
||||
cells = []
|
||||
for item in geometry.cells:
|
||||
indices = _line_indices_within(lines, item.bbox)
|
||||
expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id)
|
||||
if expected.text.strip() and not indices:
|
||||
return OcrTableEvidence(ready=False, issues=['ocr_cell_tokens_missing'])
|
||||
cells.append(OcrCellEvidence(cell_id=item.cell_id, bbox=item.bbox, line_indices=indices))
|
||||
return OcrTableEvidence(ready=True, lines=lines, cells=cells, issues=[])
|
||||
|
||||
|
||||
def _line_indices_within(lines: list[OcrLine], bbox: LayoutBBox) -> list[int]:
|
||||
"""返回中心点位于 cell 内的 OCR 行索引。"""
|
||||
return [
|
||||
index for index, item in enumerate(lines)
|
||||
if bbox.x0 <= (item.bbox.x0 + item.bbox.x1) / 2 <= bbox.x1
|
||||
and bbox.y0 <= (item.bbox.y0 + item.bbox.y1) / 2 <= bbox.y1
|
||||
]
|
||||
|
||||
|
||||
def _text_within(lines: list[OcrLine], bbox: LayoutBBox) -> str:
|
||||
"""按 OCR 顺序读取 cell 内文本行,供独立一致性校验。"""
|
||||
return ' '.join(lines[index].text for index in _line_indices_within(lines, bbox))
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from decimal import Decimal
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
@@ -80,6 +81,9 @@ class OrderDocumentProfile(OrderProfileModel):
|
||||
columns = [item.column_index for item in self.column_rules]
|
||||
if len(columns) != len(set(columns)):
|
||||
raise ValueError('order profile source columns must be unique')
|
||||
targets = [code for item in self.column_rules for code in item.target_field_codes]
|
||||
if len(targets) != len(set(targets)):
|
||||
raise ValueError('order profile target fields must be unique across columns')
|
||||
if self.data_start_row_index <= self.header_row_index:
|
||||
raise ValueError('order profile data rows must start after the header')
|
||||
if self.row_structure == 'unsupported_row_structure' and self.column_rules:
|
||||
@@ -228,7 +232,7 @@ def _parse_profile_row(
|
||||
if value is None:
|
||||
issues.append(f'order_profile_field_invalid:{code}')
|
||||
continue
|
||||
fields[code] = value.isoformat() if hasattr(value, 'isoformat') else value
|
||||
fields[code] = _profile_json_value(value)
|
||||
if profile.drop_zero_qty and explicit_qty == 0:
|
||||
return OrderProfileRowResult(row_index=row_index, status='deleted')
|
||||
required_build = {'part_number', 'qty'}
|
||||
@@ -278,3 +282,10 @@ def _normalize_profile_value(raw: Any, config: dict[str, Any] | None) -> Any:
|
||||
return value if value is not None and validate_order_field_value(value, config) else None
|
||||
except (ArithmeticError, TypeError, ValueError, ValidationError):
|
||||
return None
|
||||
|
||||
|
||||
def _profile_json_value(value: Any) -> Any:
|
||||
"""把字段规则返回值转换为数据库 JSON 可序列化标量。"""
|
||||
if isinstance(value, Decimal):
|
||||
return int(value) if value == value.to_integral_value() else float(value)
|
||||
return value.isoformat() if hasattr(value, 'isoformat') else value
|
||||
@@ -0,0 +1,238 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/runtime.py
|
||||
|
||||
用途:在独立布局 Job 中调用 MinerU,并生成可持久化的紧凑文本、表格及原生 PDF 候选快照。
|
||||
依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf。
|
||||
逻辑:保存受字符预算限制的分页文本块、整表 HTML 和保守 layout.v1 候选;Provider 错误安全降级,不保存原始响应。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.shipping_notice.document_layout.mineru import (
|
||||
MINERU_SUPPORTED_EXTENSIONS,
|
||||
MinerUClient,
|
||||
MinerUClientConfig,
|
||||
parse_mineru_candidate,
|
||||
)
|
||||
|
||||
|
||||
LAYOUT_SNAPSHOT_VERSION = 'shipping_document_table_snapshot.v1'
|
||||
|
||||
|
||||
def _enabled() -> bool:
|
||||
"""读取显式 MinerU 开关;未配置时不得在上传链静默增加外部调用。"""
|
||||
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', False))
|
||||
|
||||
|
||||
def mineru_layout_capture_enabled(filename: str) -> bool:
|
||||
"""判断文件是否需要读取二进制并调用 MinerU,供上传链避免默认关闭时重复对象存储 I/O。"""
|
||||
return _enabled() and Path(str(filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS
|
||||
|
||||
|
||||
def build_mineru_table_snapshot(
|
||||
*,
|
||||
filename: str,
|
||||
content: bytes,
|
||||
read_timeout_seconds: int | None = None,
|
||||
document_id: int | None = None,
|
||||
content_hash: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
为一个受支持附件生成紧凑 MinerU 文本与表格快照。
|
||||
|
||||
核心逻辑:保留分页非表格文本块和表格 HTML,分别执行字符预算;不持久化
|
||||
task_id、Provider 原始响应、模型中间输出或逐字符坐标。
|
||||
|
||||
Args:
|
||||
filename: 原附件名,仅用于扩展名和 MinerU multipart,不进入返回错误详情。
|
||||
content: 原始文件字节;不写数据库和日志。
|
||||
document_id/content_hash: PDF 的版本化 Document 身份;两者齐全时生成 layout.v1 候选。
|
||||
Returns:
|
||||
关闭/不支持时返回 None;成功或 Provider 降级均返回受控的版本化状态对象。
|
||||
"""
|
||||
extension = Path(str(filename or '')).suffix.lower()
|
||||
if not mineru_layout_capture_enabled(filename) or not content:
|
||||
return None
|
||||
base_url = str(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL') or '').strip()
|
||||
if not base_url:
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'mineru',
|
||||
'backend': 'pipeline',
|
||||
'status': 'config_missing',
|
||||
'tables': [],
|
||||
'issues': ['mineru_base_url_missing'],
|
||||
}
|
||||
config = MinerUClientConfig(
|
||||
base_url=base_url,
|
||||
backend='pipeline',
|
||||
connect_timeout_seconds=int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS', 10,
|
||||
)),
|
||||
read_timeout_seconds=int(read_timeout_seconds or min(
|
||||
int(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS', 300)),
|
||||
max(int(current_app.config.get('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', 300)) - 30, 1),
|
||||
)),
|
||||
)
|
||||
try:
|
||||
candidate = parse_mineru_candidate(
|
||||
MinerUClient(config).parse_file_async(filename=filename, content=content),
|
||||
)
|
||||
except AppError as exc:
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'mineru',
|
||||
'backend': 'pipeline',
|
||||
'status': 'failed',
|
||||
'tables': [],
|
||||
'issues': [str(exc.code)],
|
||||
}
|
||||
except (TypeError, ValueError):
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'mineru',
|
||||
'backend': 'pipeline',
|
||||
'status': 'failed',
|
||||
'tables': [],
|
||||
'issues': ['SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE'],
|
||||
}
|
||||
max_html_chars = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS', 1_000_000,
|
||||
)), 1)
|
||||
max_text_chars = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS', 200_000,
|
||||
) or 200_000), 1)
|
||||
tables: list[dict[str, Any]] = []
|
||||
text_blocks: list[dict[str, Any]] = []
|
||||
total_html_chars = 0
|
||||
total_text_chars = 0
|
||||
issues = list(candidate.capability.issues)
|
||||
for page in candidate.pages:
|
||||
for block in sorted(
|
||||
page.text_blocks,
|
||||
key=lambda item: (
|
||||
item.normalized_bbox.y0, item.normalized_bbox.x0,
|
||||
item.normalized_bbox.y1, item.normalized_bbox.x1,
|
||||
),
|
||||
):
|
||||
text = ' '.join(str(block.text or '').split()).strip()
|
||||
if not text:
|
||||
continue
|
||||
if total_text_chars + len(text) > max_text_chars:
|
||||
issues.append('mineru_text_budget_exceeded')
|
||||
continue
|
||||
total_text_chars += len(text)
|
||||
text_blocks.append({
|
||||
'page_no': block.page_no,
|
||||
'normalized_bbox': block.normalized_bbox.model_dump(mode='json'),
|
||||
'text': text,
|
||||
'content_type': block.content_type,
|
||||
})
|
||||
for table in page.tables:
|
||||
html = str(table.html or '')
|
||||
if total_html_chars + len(html) > max_html_chars:
|
||||
issues.append('mineru_table_html_budget_exceeded')
|
||||
continue
|
||||
total_html_chars += len(html)
|
||||
tables.append({
|
||||
'table_id': table.candidate_id,
|
||||
'page_no': table.page_no,
|
||||
'bbox': table.bbox.model_dump(mode='json'),
|
||||
'normalized_bbox': table.normalized_bbox.model_dump(mode='json'),
|
||||
'html': html,
|
||||
'row_count': table.row_count,
|
||||
'cell_count': table.cell_count,
|
||||
'has_rowspan': table.has_rowspan,
|
||||
'has_colspan': table.has_colspan,
|
||||
})
|
||||
snapshot = {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'mineru',
|
||||
'provider_version': candidate.provider_version,
|
||||
'backend': candidate.backend or 'pipeline',
|
||||
'status': 'ready',
|
||||
'text_blocks': text_blocks,
|
||||
'tables': tables,
|
||||
'capability': candidate.capability.model_dump(mode='json'),
|
||||
'issues': sorted(set(issues)),
|
||||
}
|
||||
if extension == '.pdf' and document_id and content_hash:
|
||||
try:
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
build_native_pdf_layout_candidate,
|
||||
)
|
||||
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=int(document_id), content_hash=str(content_hash),
|
||||
content=content, mineru=candidate,
|
||||
)
|
||||
snapshot['layout_candidate'] = layout.model_dump(mode='json')
|
||||
except Exception:
|
||||
snapshot['issues'] = sorted(set(
|
||||
list(snapshot['issues']) + ['native_pdf_layout_candidate_invalid'],
|
||||
))
|
||||
return snapshot
|
||||
|
||||
|
||||
def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | None = None) -> None:
|
||||
"""就地为 NoticeIntakeResult 的根文件或 EML 附件补充布局快照,失败不阻断文本解析。"""
|
||||
meta = result.meta if isinstance(getattr(result, 'meta', None), dict) else {}
|
||||
attachments = meta.get('attachments') if isinstance(meta.get('attachments'), list) else []
|
||||
if attachments:
|
||||
app = current_app._get_current_object()
|
||||
eligible = [
|
||||
item for item in attachments
|
||||
if isinstance(item, dict)
|
||||
and isinstance(item.get('_payload_bytes'), bytes)
|
||||
and mineru_layout_capture_enabled(str(item.get('filename') or ''))
|
||||
]
|
||||
max_documents = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4,
|
||||
)), 0)
|
||||
concurrency = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY', 2,
|
||||
)), 1)
|
||||
selected = eligible[:max_documents]
|
||||
for item in eligible[max_documents:]:
|
||||
item['layout_snapshot'] = {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'mineru', 'backend': 'pipeline', 'status': 'skipped_budget',
|
||||
'tables': [], 'issues': ['mineru_intake_document_budget_exceeded'],
|
||||
}
|
||||
|
||||
batch_count = max((len(selected) + concurrency - 1) // concurrency, 1)
|
||||
configured_timeout = int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS', 300,
|
||||
))
|
||||
total_timeout = int(current_app.config.get('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', 300))
|
||||
per_request_timeout = max(min(configured_timeout, (max(total_timeout - 30, 1) // batch_count)), 1)
|
||||
|
||||
def parse_attachment(item: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""在线程独立应用上下文中解析一个附件,不访问 ORM Session。"""
|
||||
with app.app_context():
|
||||
return build_mineru_table_snapshot(
|
||||
filename=str(item.get('filename') or ''),
|
||||
content=item['_payload_bytes'],
|
||||
read_timeout_seconds=per_request_timeout,
|
||||
)
|
||||
|
||||
if selected:
|
||||
with ThreadPoolExecutor(max_workers=min(concurrency, len(selected))) as pool:
|
||||
snapshots = list(pool.map(parse_attachment, selected))
|
||||
for item, snapshot in zip(selected, snapshots, strict=True):
|
||||
if snapshot is not None:
|
||||
item['layout_snapshot'] = snapshot
|
||||
return
|
||||
if isinstance(root_asset_bytes, bytes):
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename=str(getattr(result, 'filename', '') or ''), content=root_asset_bytes,
|
||||
)
|
||||
if snapshot is not None:
|
||||
meta['layout_snapshot'] = snapshot
|
||||
@@ -0,0 +1,112 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/schema_mapping.py
|
||||
|
||||
用途:将 shipping_document_layout.v1 的真实 cell/token 证据映射到 Run 冻结订单 Schema。
|
||||
依赖:布局契约、HTML 网格统一映射器、TableHeaderContract。
|
||||
逻辑:只消费契约已验证行列和显式 continuation;不猜跨页、不提升质量状态、不接受无 cell 证据字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutDocument, LayoutTable, validate_layout_document
|
||||
from app.services.shipping_notice.document_layout.html_table import (
|
||||
HtmlGrid,
|
||||
HtmlGridCell,
|
||||
HtmlGridSlot,
|
||||
map_html_grid_to_schema,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import TableHeaderContract
|
||||
|
||||
|
||||
def map_layout_document_to_schema(
|
||||
layout: LayoutDocument | dict[str, Any], *, contract: TableHeaderContract,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
映射完整布局文档,并输出保留 cell/token 证据的安全候选。
|
||||
|
||||
Args:
|
||||
layout: 必须通过 shipping_document_layout.v1 完整校验。
|
||||
contract: 当前 Run 冻结订单 Schema 表头契约。
|
||||
Returns:
|
||||
每张表的映射、质量和显式跨页父表;needs_review 永不伪装 accepted。
|
||||
"""
|
||||
document = validate_layout_document(layout)
|
||||
result: list[dict[str, Any]] = []
|
||||
for page in document.pages:
|
||||
for table in page.tables:
|
||||
grid = layout_table_to_grid(table)
|
||||
mapped = map_html_grid_to_schema(
|
||||
grid, page_no=page.page_no, table_id=table.table_id, contract=contract,
|
||||
)
|
||||
token_ids_by_cell = {
|
||||
cell.cell_id: list(cell.token_ids)
|
||||
for row in table.rows for cell in row.cells
|
||||
}
|
||||
result.append({
|
||||
'page_no': page.page_no,
|
||||
'table_id': table.table_id,
|
||||
'continuation_of': table.continuation_of,
|
||||
'layout_status': table.status,
|
||||
'mapping_status': 'candidate' if table.status != 'accepted' else 'accepted',
|
||||
'header_row_index': mapped.header_row_index,
|
||||
'issues': sorted(set(
|
||||
list(mapped.issues)
|
||||
+ ([] if table.status == 'accepted' else ['layout_table_not_accepted'])
|
||||
)),
|
||||
'columns': [item.model_dump(mode='json') for item in mapped.columns],
|
||||
'rows': [{
|
||||
**row.model_dump(mode='json'),
|
||||
'fields': [{
|
||||
**field.model_dump(mode='json'),
|
||||
'token_ids': token_ids_by_cell.get(field.cell_id, []),
|
||||
'evidence_ref': (
|
||||
f'layout:{document.document_id}:p{page.page_no}:'
|
||||
f'{table.table_id}:{field.cell_id}'
|
||||
),
|
||||
} for field in row.fields],
|
||||
} for row in mapped.rows],
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def layout_table_to_grid(table: LayoutTable) -> HtmlGrid:
|
||||
"""把 layout.v1 Table 转换为矩形 Grid,同时保留真实 cell_id、span 和角色。"""
|
||||
occupied: dict[tuple[int, int], HtmlGridSlot] = {}
|
||||
cells: list[HtmlGridCell] = []
|
||||
max_row = 0
|
||||
max_column = 0
|
||||
for row in table.rows:
|
||||
for cell in row.cells:
|
||||
is_header = cell.role == 'header' or row.role == 'header'
|
||||
cells.append(HtmlGridCell(
|
||||
cell_id=cell.cell_id,
|
||||
row_index=cell.row_index,
|
||||
column_index=cell.column_index,
|
||||
row_span=cell.row_span,
|
||||
column_span=cell.column_span,
|
||||
text=cell.text,
|
||||
normalized_text=cell.normalized_text,
|
||||
is_header=is_header,
|
||||
))
|
||||
for row_index in range(cell.row_index, cell.row_index + cell.row_span):
|
||||
for column_index in range(cell.column_index, cell.column_index + cell.column_span):
|
||||
occupied[(row_index, column_index)] = HtmlGridSlot(
|
||||
row_index=row_index, column_index=column_index,
|
||||
cell_id=cell.cell_id, text=cell.text,
|
||||
normalized_text=cell.normalized_text, is_header=is_header,
|
||||
origin_row_index=cell.row_index,
|
||||
origin_column_index=cell.column_index,
|
||||
)
|
||||
max_row = max(max_row, row_index + 1)
|
||||
max_column = max(max_column, column_index + 1)
|
||||
return HtmlGrid(
|
||||
row_count=max_row,
|
||||
column_count=max_column,
|
||||
rows=[
|
||||
[occupied.get((row_index, column_index)) for column_index in range(max_column)]
|
||||
for row_index in range(max_row)
|
||||
],
|
||||
cells=cells,
|
||||
)
|
||||
@@ -0,0 +1,212 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/text_cell_alignment.py
|
||||
|
||||
用途:用原生 PDF 字符坐标为 MinerU HTML cell 生成严格、可追溯的几何候选。
|
||||
依赖:document_layout contracts/html_table、Pydantic。
|
||||
逻辑:只接受表格区域内唯一且不重叠的规范化文本匹配;重复、空白或冲突 cell 不猜框。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError as PydanticValidationError, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
|
||||
|
||||
|
||||
class TextCellAlignmentModel(BaseModel):
|
||||
"""为字符和 cell 候选启用严格字段校验,防止评测辅助结果静默漂移。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class PositionedCharacter(TextCellAlignmentModel):
|
||||
"""保存 PDF 原生文本层的单个可见字符及页面坐标。"""
|
||||
|
||||
text: str = Field(min_length=1, max_length=8)
|
||||
bbox: LayoutBBox
|
||||
source_index: int | None = Field(default=None, ge=0)
|
||||
|
||||
|
||||
class TextAlignedCell(TextCellAlignmentModel):
|
||||
"""保存唯一文本匹配得到的 HTML cell 候选框;仍需人工视觉确认。"""
|
||||
|
||||
cell_id: str
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
glyph_indices: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
class TextCellAlignmentResult(TextCellAlignmentModel):
|
||||
"""汇总严格文本对齐覆盖率和不准入原因,不复制文档原文。"""
|
||||
|
||||
complete: bool
|
||||
expected_cell_count: int = Field(ge=0)
|
||||
matched_cell_count: int = Field(ge=0)
|
||||
cells: list[TextAlignedCell] = Field(default_factory=list)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_completeness(self) -> 'TextCellAlignmentResult':
|
||||
"""完整结果必须覆盖所有原始 cell;不完整结果不得伪报 complete。"""
|
||||
expected = self.expected_cell_count > 0 and self.matched_cell_count == self.expected_cell_count
|
||||
if self.complete != expected:
|
||||
raise ValueError('text cell alignment completeness is inconsistent')
|
||||
if self.matched_cell_count != len(self.cells):
|
||||
raise ValueError('text cell alignment count is inconsistent')
|
||||
return self
|
||||
|
||||
|
||||
def align_html_cells_from_positioned_text(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
) -> TextCellAlignmentResult:
|
||||
"""
|
||||
在整表区域内按唯一规范化文本匹配 HTML 原始 cell,并合并字符 bbox。
|
||||
|
||||
Args:
|
||||
grid: 已展开但仍保留原始 cell 身份的 HTML 网格。
|
||||
characters: PDF 原生文本层字符及左上原点页面坐标。
|
||||
table_bbox: MinerU 整表页面 bbox,仅在该范围内搜索。
|
||||
page_width/page_height: 页面尺寸,用于生成 0..1 标准化坐标。
|
||||
Returns:
|
||||
可供人工叠框 Review 的候选;任何歧义都保留 issue,绝不进入生产证据。
|
||||
"""
|
||||
if page_width <= 0 or page_height <= 0:
|
||||
raise ValueError('text cell alignment page dimensions must be positive')
|
||||
if table_bbox.x1 > page_width or table_bbox.y1 > page_height:
|
||||
raise ValueError('text cell alignment table bbox must be within the page')
|
||||
glyphs: list[PositionedCharacter] = []
|
||||
invalid_character_bbox = False
|
||||
for item in characters:
|
||||
try:
|
||||
glyph = item if isinstance(item, PositionedCharacter) else PositionedCharacter.model_validate(item)
|
||||
except PydanticValidationError:
|
||||
invalid_character_bbox = True
|
||||
continue
|
||||
if glyph.bbox.x1 > page_width or glyph.bbox.y1 > page_height:
|
||||
invalid_character_bbox = True
|
||||
continue
|
||||
glyphs.append(glyph)
|
||||
glyphs = [item for item in glyphs if _bbox_center_within(table_bbox, item.bbox)]
|
||||
normalized_stream, stream_to_glyph = _normalized_character_stream(glyphs)
|
||||
used_glyphs: set[int] = set()
|
||||
matched: list[TextAlignedCell] = []
|
||||
issues: set[str] = set()
|
||||
if invalid_character_bbox:
|
||||
issues.add('text_cell_alignment_invalid_character_bbox')
|
||||
|
||||
for cell in grid.cells:
|
||||
expected = _normalize_text(cell.text)
|
||||
if not expected:
|
||||
issues.add('text_cell_alignment_empty_cell')
|
||||
continue
|
||||
starts = [match.start() for match in re.finditer(re.escape(expected), normalized_stream)]
|
||||
if len(starts) != 1:
|
||||
issues.add(
|
||||
'text_cell_alignment_text_not_found'
|
||||
if not starts else 'text_cell_alignment_text_not_unique'
|
||||
)
|
||||
continue
|
||||
indices = set(stream_to_glyph[starts[0]:starts[0] + len(expected)])
|
||||
if not indices or indices & used_glyphs:
|
||||
issues.add('text_cell_alignment_glyph_overlap')
|
||||
continue
|
||||
matched_glyphs = [glyphs[index] for index in sorted(indices)]
|
||||
if not _glyphs_form_contiguous_text(matched_glyphs):
|
||||
issues.add('text_cell_alignment_geometry_discontinuous')
|
||||
continue
|
||||
bbox = _union_bbox([item.bbox for item in matched_glyphs])
|
||||
used_glyphs.update(indices)
|
||||
matched.append(TextAlignedCell(
|
||||
cell_id=cell.cell_id,
|
||||
row_index=cell.row_index,
|
||||
column_index=cell.column_index,
|
||||
bbox=bbox,
|
||||
normalized_bbox=LayoutBBox(
|
||||
x0=bbox.x0 / page_width,
|
||||
y0=bbox.y0 / page_height,
|
||||
x1=bbox.x1 / page_width,
|
||||
y1=bbox.y1 / page_height,
|
||||
),
|
||||
glyph_indices=sorted(
|
||||
glyphs[index].source_index if glyphs[index].source_index is not None else index
|
||||
for index in indices
|
||||
),
|
||||
))
|
||||
|
||||
return TextCellAlignmentResult(
|
||||
complete=bool(grid.cells) and len(matched) == len(grid.cells),
|
||||
expected_cell_count=len(grid.cells),
|
||||
matched_cell_count=len(matched),
|
||||
cells=matched,
|
||||
issues=sorted(issues),
|
||||
)
|
||||
|
||||
|
||||
def _normalized_character_stream(
|
||||
characters: list[PositionedCharacter],
|
||||
) -> tuple[str, list[int]]:
|
||||
"""生成规范化字符流,并保留每个输出字符到原 glyph 的反向索引。"""
|
||||
stream: list[str] = []
|
||||
mapping: list[int] = []
|
||||
for index, item in enumerate(characters):
|
||||
normalized = _normalize_text(item.text)
|
||||
stream.extend(normalized)
|
||||
mapping.extend([index] * len(normalized))
|
||||
return ''.join(stream), mapping
|
||||
|
||||
|
||||
def _normalize_text(value: Any) -> str:
|
||||
"""以 NFKC/casefold 保留字母数字和中日韩字符,忽略版面空白及标点。"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).casefold()
|
||||
return re.sub(r'[^0-9a-z\u4e00-\u9fff]+', '', text)
|
||||
|
||||
|
||||
def _bbox_center_within(parent: LayoutBBox, child: LayoutBBox) -> bool:
|
||||
"""使用字符中心点筛选整表区域,允许字体 bbox 轻微越过表格边界。"""
|
||||
center_x = (child.x0 + child.x1) / 2
|
||||
center_y = (child.y0 + child.y1) / 2
|
||||
return parent.x0 <= center_x <= parent.x1 and parent.y0 <= center_y <= parent.y1
|
||||
|
||||
|
||||
def _union_bbox(boxes: list[LayoutBBox]) -> LayoutBBox:
|
||||
"""合并唯一匹配字符范围;调用方保证列表非空。"""
|
||||
return LayoutBBox(
|
||||
x0=min(item.x0 for item in boxes),
|
||||
y0=min(item.y0 for item in boxes),
|
||||
x1=max(item.x1 for item in boxes),
|
||||
y1=max(item.y1 for item in boxes),
|
||||
)
|
||||
|
||||
|
||||
def _glyphs_form_contiguous_text(characters: list[PositionedCharacter]) -> bool:
|
||||
"""要求匹配字符处于同一视觉行且水平间距连续,禁止跨 cell/跨行拼接。"""
|
||||
if not characters:
|
||||
return False
|
||||
heights = [item.bbox.y1 - item.bbox.y0 for item in characters]
|
||||
median_height = sorted(heights)[len(heights) // 2]
|
||||
allowed_vertical_drift = max(2.0, median_height * 0.75)
|
||||
center_y = sum((item.bbox.y0 + item.bbox.y1) / 2 for item in characters) / len(characters)
|
||||
if any(abs((item.bbox.y0 + item.bbox.y1) / 2 - center_y) > allowed_vertical_drift for item in characters):
|
||||
return False
|
||||
ordered = sorted(characters, key=lambda item: item.bbox.x0)
|
||||
if characters != ordered:
|
||||
return False
|
||||
widths = [item.bbox.x1 - item.bbox.x0 for item in characters]
|
||||
median_width = sorted(widths)[len(widths) // 2]
|
||||
allowed_gap = max(4.0, median_width * 3.0)
|
||||
return all(
|
||||
right.bbox.x0 - left.bbox.x1 <= allowed_gap
|
||||
for left, right in zip(characters, characters[1:])
|
||||
)
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/eml_parse.py
|
||||
|
||||
用途:将 .eml 解析为结构化结果(邮件元数据、清洗正文、真实附件及各自文本)。
|
||||
依赖:标准库 email/html;Flask current_app(可选);notice_upload.extract_notice_text(叶附件抽取)。
|
||||
依赖:标准库 email/html、BeautifulSoup;Flask current_app(可选);notice_upload.extract_notice_text(叶附件抽取)。
|
||||
逻辑:由 notice_upload.extract_notice_text 在 file_type=eml 时调用;忽略内嵌图片/签名图;
|
||||
嵌套 message/rfc822 与附件型 multipart(disposition/filename)登记为独立附件;
|
||||
外层 body 不穿透 rfc822 / 附件型 multipart,避免订单文本误入正文或重复;
|
||||
@@ -24,11 +24,15 @@ from email.utils import parsedate_to_datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from bs4 import BeautifulSoup, Comment
|
||||
|
||||
# 签名/Logo 文件名启发式(仅对 image/* 生效)
|
||||
_SIGNATURE_LOGO_NAME_RE = re.compile(
|
||||
r"(?:^|[_.\-])(logo|signature|sig|banner|icon|spacer|pixel|footer|header)(?:[_.\-]|$)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_HTML_TABLE_TAGS = frozenset({'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td'})
|
||||
_HTML_DROP_TAGS = frozenset({'script', 'style', 'img', 'svg', 'object', 'embed', 'iframe', 'template'})
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -330,6 +334,52 @@ def _extract_body_text(msg: Message) -> str:
|
||||
return plain or html
|
||||
|
||||
|
||||
def _extract_body_html_tables(msg: Message) -> list[str]:
|
||||
"""
|
||||
提取根邮件正文中的 HTML 表格并做最小白名单清洗。
|
||||
|
||||
核心逻辑:即使 multipart/alternative 同时存在 plain,也读取对应 HTML 的 table;
|
||||
仅保留表格结构、cell 文本及 rowspan/colspan,禁止脚本、样式、链接和图片进入布局快照。
|
||||
|
||||
Args:
|
||||
msg: 当前 EML 根消息;不穿透 rfc822 或附件型 multipart。
|
||||
Returns:
|
||||
最多 20 张、合计不超过 200000 字符的安全 HTML table 片段。
|
||||
"""
|
||||
result: list[str] = []
|
||||
total_chars = 0
|
||||
for part in _iter_local_body_candidates(msg):
|
||||
if str(part.get_content_type() or '').lower() != 'text/html':
|
||||
continue
|
||||
raw = _decode_part_text(part, _read_part_payload(part))
|
||||
soup = BeautifulSoup(raw or '', 'html.parser')
|
||||
for table in soup.find_all('table'):
|
||||
if table.find_parent('table') is not None:
|
||||
continue
|
||||
fragment = BeautifulSoup(str(table), 'html.parser')
|
||||
for comment in fragment.find_all(string=lambda value: isinstance(value, Comment)):
|
||||
comment.extract()
|
||||
for tag in list(fragment.find_all(True)):
|
||||
if tag.name in _HTML_DROP_TAGS:
|
||||
tag.decompose()
|
||||
continue
|
||||
if tag.name not in _HTML_TABLE_TAGS:
|
||||
tag.unwrap()
|
||||
continue
|
||||
allowed = {'rowspan', 'colspan'} if tag.name in {'th', 'td'} else set()
|
||||
tag.attrs = {
|
||||
key: value for key, value in tag.attrs.items()
|
||||
if str(key).lower() in allowed
|
||||
}
|
||||
cleaned = str(fragment.find('table') or '').strip()
|
||||
if not cleaned or total_chars + len(cleaned) > 200_000 or len(result) >= 20:
|
||||
continue
|
||||
result.append(cleaned)
|
||||
total_chars += len(cleaned)
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def _is_collectible_text_leaf(msg: Message) -> bool:
|
||||
"""判定部件是否可作为附件容器内的可落库文本叶子(非 filename 附件)。"""
|
||||
ctype = str(msg.get_content_type() or "").lower()
|
||||
@@ -1126,6 +1176,7 @@ def parse_eml_bytes(
|
||||
date_val = _format_date(msg)
|
||||
message_id = _normalize_message_id(_header_str(msg, "Message-ID") or _header_str(msg, "Message-Id"))
|
||||
body_text = _extract_body_text(msg)
|
||||
body_html_tables = _extract_body_html_tables(msg)
|
||||
|
||||
state = _ParseState(limits=limits, extract_text=extract_text)
|
||||
_walk_message(msg, state, depth=depth)
|
||||
@@ -1143,6 +1194,7 @@ def parse_eml_bytes(
|
||||
"to": to_addr,
|
||||
"date": date_val,
|
||||
"body_text": combined_body,
|
||||
"body_html_tables": body_html_tables,
|
||||
}
|
||||
flat = _compose_flat_text(
|
||||
subject=subject,
|
||||
|
||||
@@ -150,10 +150,10 @@ def _heuristic_extract(
|
||||
for m in re.finditer(r"([A-Za-z0-9\-_]{3,})\s*[xX×*]\s*(\d+(?:\.\d+)?)", text):
|
||||
lines.append({"part_number": m.group(1), "qty": float(m.group(2))})
|
||||
|
||||
# 尝试纯数字 Reservation ID + SKU + Qty 的自由文本模式(如 1000140351 10-40594-001 2)
|
||||
# 尝试 5 位或 10 位 Reservation ID + SKU + Qty 的自由文本模式。
|
||||
if not lines:
|
||||
for m in re.finditer(
|
||||
r"(?P<resv>\d{8,12})\s+([A-Za-z0-9\-_]{3,})\s+(\d+(?:\.\d+)?)",
|
||||
r"(?P<resv>(?:\d{5}|\d{10}))\s+([A-Za-z0-9\-_]{3,})\s+(\d+(?:\.\d+)?)",
|
||||
text,
|
||||
):
|
||||
lines.append(
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_service.py
|
||||
|
||||
用途:管理订单文档模板 Profile 的草稿、发布、退役和 Run 冻结快照。
|
||||
依赖:ShippingOrderDocumentProfile、订单 Schema 版本、document_layout.order_profile 纯契约。
|
||||
逻辑:草稿保存时把目标 field_code 转成稳定 field_id;发布时重新校验绑定 Schema 并原子替换当前版本。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
OrderDocumentProfile,
|
||||
OrderProfileColumnRule,
|
||||
order_profile_structure_fingerprint,
|
||||
)
|
||||
|
||||
|
||||
PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
|
||||
|
||||
def _schema_fields(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]:
|
||||
"""返回绑定 Schema 中已启用的订单明细字段,并拒绝重复 field_code。"""
|
||||
definition = version.definition_json if isinstance(version.definition_json, dict) else {}
|
||||
result: dict[str, dict[str, Any]] = {}
|
||||
for raw in definition.get('fields') or []:
|
||||
if not isinstance(raw, dict) or not raw.get('enabled', True) or raw.get('scope') != 'line':
|
||||
continue
|
||||
code = str(raw.get('field_code') or '').strip()
|
||||
field_id = str(raw.get('field_id') or '').strip()
|
||||
if not code or not field_id or code in result:
|
||||
raise ValidationError(
|
||||
'Order profile Schema fields are invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
result[code] = dict(raw)
|
||||
return result
|
||||
|
||||
|
||||
def _require_schema_version(raw_id: Any) -> ShippingOrderSchemaVersion:
|
||||
"""读取不可变 published/retired Schema;草稿不可作为 Profile 运行契约。"""
|
||||
try:
|
||||
version_id = int(raw_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'schema_version_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
) from exc
|
||||
version = db.session.get(ShippingOrderSchemaVersion, version_id)
|
||||
if version is None or version.status not in {'published', 'retired'} or not version.checksum:
|
||||
raise ValidationError(
|
||||
'Order profile requires an immutable Schema version',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID',
|
||||
)
|
||||
return version
|
||||
|
||||
|
||||
def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersion) -> dict[str, Any]:
|
||||
"""校验纯 Profile 契约并把每个目标字段冻结为 field_id + field_code。"""
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError(
|
||||
'Order profile definition must be an object',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
fields = _schema_fields(schema_version)
|
||||
normalized_rules: list[dict[str, Any]] = []
|
||||
for raw_rule in raw.get('column_rules') or []:
|
||||
if not isinstance(raw_rule, dict):
|
||||
raise ValidationError(
|
||||
'Order profile column rule is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
codes = raw_rule.get('target_field_codes')
|
||||
if not isinstance(codes, list) or any(str(code or '').strip() not in fields for code in codes):
|
||||
raise ValidationError(
|
||||
'Order profile target field is unavailable in its Schema version',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
)
|
||||
rule = OrderProfileColumnRule(
|
||||
column_index=raw_rule.get('column_index'),
|
||||
extractor_key=raw_rule.get('extractor_key'),
|
||||
target_field_codes=[str(code).strip() for code in codes],
|
||||
)
|
||||
normalized_rules.append({
|
||||
**rule.model_dump(),
|
||||
'target_fields': [
|
||||
{'field_id': str(fields[code]['field_id']), 'field_code': code}
|
||||
for code in rule.target_field_codes
|
||||
],
|
||||
})
|
||||
try:
|
||||
contract = OrderDocumentProfile(
|
||||
profile_code='VALIDATION_PROFILE',
|
||||
version=1,
|
||||
structure_fingerprint=raw.get('structure_fingerprint'),
|
||||
header_row_index=raw.get('header_row_index'),
|
||||
data_start_row_index=raw.get('data_start_row_index'),
|
||||
row_structure=raw.get('row_structure', 'preserved'),
|
||||
column_rules=[OrderProfileColumnRule(**{
|
||||
key: value for key, value in item.items() if key != 'target_fields'
|
||||
}) for item in normalized_rules],
|
||||
drop_zero_qty=raw.get('drop_zero_qty', True),
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Order profile definition is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
) from exc
|
||||
return {
|
||||
'contract_version': contract.contract_version,
|
||||
'structure_fingerprint': contract.structure_fingerprint,
|
||||
'header_row_index': contract.header_row_index,
|
||||
'data_start_row_index': contract.data_start_row_index,
|
||||
'row_structure': contract.row_structure,
|
||||
'column_rules': normalized_rules,
|
||||
'drop_zero_qty': contract.drop_zero_qty,
|
||||
}
|
||||
|
||||
|
||||
def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderDocumentProfile:
|
||||
"""把数据库冻结定义还原为纯执行契约,额外存储的 field_id 不进入解析器。"""
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
return OrderDocumentProfile(
|
||||
profile_code=profile.profile_code,
|
||||
version=profile.version,
|
||||
structure_fingerprint=definition.get('structure_fingerprint'),
|
||||
header_row_index=definition.get('header_row_index'),
|
||||
data_start_row_index=definition.get('data_start_row_index'),
|
||||
row_structure=definition.get('row_structure', 'preserved'),
|
||||
column_rules=[OrderProfileColumnRule(**{
|
||||
key: value for key, value in rule.items() if key != 'target_fields'
|
||||
}) for rule in definition.get('column_rules') or [] if isinstance(rule, dict)],
|
||||
drop_zero_qty=definition.get('drop_zero_qty', True),
|
||||
)
|
||||
|
||||
|
||||
def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""返回不含文档正文的 Profile 管理 DTO。"""
|
||||
schema = profile.schema_version
|
||||
return {
|
||||
'id': profile.id,
|
||||
'profile_code': profile.profile_code,
|
||||
'display_name': profile.display_name,
|
||||
'version': profile.version,
|
||||
'status': profile.status,
|
||||
'schema_version_id': profile.schema_version_id,
|
||||
'schema_version': schema.version if schema is not None else None,
|
||||
'schema_checksum': schema.checksum if schema is not None else None,
|
||||
'structure_fingerprint': profile.structure_fingerprint,
|
||||
'definition': dict(profile.definition_json or {}),
|
||||
'checksum': profile.checksum,
|
||||
'lock_version': profile.lock_version,
|
||||
'change_note': profile.change_note,
|
||||
'source_profile_id': profile.source_profile_id,
|
||||
'published_at': profile.published_at.isoformat() if profile.published_at else None,
|
||||
'retired_at': profile.retired_at.isoformat() if profile.retired_at else None,
|
||||
}
|
||||
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""按模板编码和版本倒序列出全部 Profile。"""
|
||||
return [payload(item) for item in ShippingOrderDocumentProfile.query.order_by(
|
||||
ShippingOrderDocumentProfile.profile_code.asc(),
|
||||
ShippingOrderDocumentProfile.version.desc(),
|
||||
).all()]
|
||||
|
||||
|
||||
def _document_layout(document: ShippingNoticeDocument) -> dict[str, Any]:
|
||||
"""读取可用于建 Profile 的 ready MinerU 表格快照,不接受失败/超预算候选。"""
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
|
||||
layout = current_layout_snapshot(document) or {}
|
||||
tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
|
||||
if layout.get('status') != 'ready' or not tables:
|
||||
raise ValidationError(
|
||||
'Document has no ready MinerU tables',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
return layout
|
||||
|
||||
|
||||
def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
|
||||
"""列出最近含 ready MinerU 表格的订单附件;不返回正文、HTML 或原始布局。"""
|
||||
safe_limit = max(1, min(int(limit), 100))
|
||||
rows = ShippingNoticeDocument.query.filter(
|
||||
ShippingNoticeDocument.document_type == 'attachment',
|
||||
ShippingNoticeDocument.current_layout_version_id.is_not(None),
|
||||
).order_by(ShippingNoticeDocument.created_at.desc()).limit(safe_limit * 4).all()
|
||||
result: list[dict[str, Any]] = []
|
||||
for document in rows:
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
|
||||
layout = current_layout_snapshot(document) or {}
|
||||
tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
|
||||
if layout.get('status') != 'ready' or not tables:
|
||||
continue
|
||||
result.append({
|
||||
'document_id': document.id,
|
||||
'intake_id': document.intake_id,
|
||||
'filename': document.filename,
|
||||
'content_hash': document.content_hash,
|
||||
'provider': layout.get('provider'),
|
||||
'provider_version': layout.get('provider_version'),
|
||||
'table_count': len(tables),
|
||||
'created_at': document.created_at.isoformat() if document.created_at else None,
|
||||
})
|
||||
if len(result) >= safe_limit:
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def get_sample_tables(document_id: int) -> dict[str, Any]:
|
||||
"""返回样本文档的表格网格预览;预览只含 cell 文本,不返回 bbox、正文或原始 HTML。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(document_id))
|
||||
if document is None:
|
||||
raise NotFoundError(
|
||||
'Order profile sample document not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND',
|
||||
)
|
||||
layout = _document_layout(document)
|
||||
tables: list[dict[str, Any]] = []
|
||||
for raw in layout.get('tables') or []:
|
||||
if not isinstance(raw, dict) or not str(raw.get('html') or '').strip():
|
||||
continue
|
||||
table_id = str(raw.get('table_id') or '')
|
||||
grid = parse_html_grid(str(raw['html']), table_id=table_id)
|
||||
tables.append({
|
||||
'table_id': table_id,
|
||||
'page_no': int(raw.get('page_no') or 1),
|
||||
'row_count': grid.row_count,
|
||||
'column_count': grid.column_count,
|
||||
'rows': [
|
||||
[slot.text if slot is not None else '' for slot in row]
|
||||
for row in grid.rows
|
||||
],
|
||||
})
|
||||
return {
|
||||
'document': {
|
||||
'document_id': document.id,
|
||||
'intake_id': document.intake_id,
|
||||
'filename': document.filename,
|
||||
'content_hash': document.content_hash,
|
||||
},
|
||||
'tables': tables,
|
||||
}
|
||||
|
||||
|
||||
def create_draft_from_sample(
|
||||
data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按持久化样本表格和管理员结构化选择生成 Profile 草稿。
|
||||
|
||||
浏览器只提交 document/table、表头行、数据起始行和受控列规则;结构指纹由后端真实 HTML 计算。
|
||||
"""
|
||||
try:
|
||||
document_id = int(data.get('document_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'document_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
) from exc
|
||||
document = db.session.get(ShippingNoticeDocument, document_id)
|
||||
if document is None:
|
||||
raise NotFoundError(
|
||||
'Order profile sample document not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND',
|
||||
)
|
||||
layout = _document_layout(document)
|
||||
table_id = str(data.get('table_id') or '').strip()
|
||||
raw_table = next((
|
||||
item for item in layout.get('tables') or []
|
||||
if isinstance(item, dict) and str(item.get('table_id') or '') == table_id
|
||||
), None)
|
||||
if raw_table is None:
|
||||
raise ValidationError(
|
||||
'Selected sample table is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
try:
|
||||
header_row_index = int(data.get('header_row_index'))
|
||||
data_start_row_index = int(data.get('data_start_row_index'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Sample row selection is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
) from exc
|
||||
grid = parse_html_grid(str(raw_table.get('html') or ''), table_id=table_id)
|
||||
if (
|
||||
header_row_index < 0 or header_row_index >= grid.row_count
|
||||
or data_start_row_index <= header_row_index or data_start_row_index >= grid.row_count
|
||||
):
|
||||
raise ValidationError(
|
||||
'Sample row selection is out of range',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
definition = {
|
||||
'structure_fingerprint': order_profile_structure_fingerprint(
|
||||
grid, header_row_index=header_row_index,
|
||||
),
|
||||
'header_row_index': header_row_index,
|
||||
'data_start_row_index': data_start_row_index,
|
||||
'row_structure': str(data.get('row_structure') or 'preserved'),
|
||||
'column_rules': data.get('column_rules'),
|
||||
'drop_zero_qty': data.get('drop_zero_qty', True),
|
||||
}
|
||||
return save_draft({
|
||||
'profile_code': data.get('profile_code'),
|
||||
'display_name': data.get('display_name'),
|
||||
'schema_version_id': data.get('schema_version_id'),
|
||||
'definition': definition,
|
||||
'change_note': data.get('change_note'),
|
||||
'expected_lock_version': data.get('expected_lock_version'),
|
||||
}, actor_id=actor_id, profile_id=profile_id)
|
||||
|
||||
|
||||
def save_draft(
|
||||
data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""创建或整体替换草稿;更新要求乐观锁一致,发布版本不可修改。"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if profile is not None and profile.status != 'draft':
|
||||
raise ConflictError(
|
||||
'Published order document profile is immutable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE',
|
||||
)
|
||||
code = str(data.get('profile_code') or (profile.profile_code if profile else '')).strip().upper()
|
||||
if not PROFILE_CODE_PATTERN.fullmatch(code):
|
||||
raise ValidationError('profile_code is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
if profile is not None and code != profile.profile_code:
|
||||
raise ConflictError(
|
||||
'Draft profile_code is immutable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE',
|
||||
)
|
||||
if profile is None and ShippingOrderDocumentProfile.query.filter_by(
|
||||
profile_code=code, status='draft',
|
||||
).count():
|
||||
raise ConflictError(
|
||||
'An order document profile draft already exists',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS',
|
||||
)
|
||||
schema_version = _require_schema_version(
|
||||
data.get('schema_version_id', profile.schema_version_id if profile else None),
|
||||
)
|
||||
if profile is not None:
|
||||
expected = data.get('expected_lock_version')
|
||||
if not isinstance(expected, int):
|
||||
raise ValidationError(
|
||||
'expected_lock_version is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED',
|
||||
)
|
||||
if expected != profile.lock_version:
|
||||
raise ConflictError(
|
||||
'Order document profile draft was changed by another user',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT',
|
||||
details={'expected_lock_version': expected, 'current_lock_version': profile.lock_version},
|
||||
)
|
||||
if schema_version.id != profile.schema_version_id:
|
||||
raise ConflictError(
|
||||
'Draft Schema binding is immutable; create a new version',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE',
|
||||
)
|
||||
definition = _normalize_definition(data.get('definition'), schema_version=schema_version)
|
||||
if profile is None:
|
||||
version = int(db.session.query(func.max(ShippingOrderDocumentProfile.version)).filter_by(
|
||||
profile_code=code,
|
||||
).scalar() or 0) + 1
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code=code,
|
||||
version=version,
|
||||
schema_version_id=schema_version.id,
|
||||
created_by_id=actor_id,
|
||||
lock_version=1,
|
||||
)
|
||||
db.session.add(profile)
|
||||
else:
|
||||
profile.lock_version += 1
|
||||
profile.display_name = str(data.get('display_name') or profile.display_name or code).strip()
|
||||
profile.structure_fingerprint = definition['structure_fingerprint']
|
||||
profile.definition_json = definition
|
||||
profile.change_note = str(data.get('change_note') or '').strip() or None
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
|
||||
|
||||
def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""从不可变版本复制新草稿;同编码只允许一个草稿。"""
|
||||
source = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if source.status not in {'published', 'retired'}:
|
||||
raise ConflictError(
|
||||
'Only immutable profile can be cloned', code='SHIPPING.ORDER_DOCUMENT_PROFILE_CLONE_INVALID',
|
||||
)
|
||||
if ShippingOrderDocumentProfile.query.filter_by(profile_code=source.profile_code, status='draft').count():
|
||||
raise ConflictError(
|
||||
'An order document profile draft already exists',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS',
|
||||
)
|
||||
version = int(db.session.query(func.max(ShippingOrderDocumentProfile.version)).filter_by(
|
||||
profile_code=source.profile_code,
|
||||
).scalar() or 0) + 1
|
||||
clone = ShippingOrderDocumentProfile(
|
||||
profile_code=source.profile_code,
|
||||
display_name=source.display_name,
|
||||
version=version,
|
||||
status='draft',
|
||||
schema_version_id=source.schema_version_id,
|
||||
structure_fingerprint=source.structure_fingerprint,
|
||||
definition_json=dict(source.definition_json or {}),
|
||||
source_profile_id=source.id,
|
||||
created_by_id=actor_id,
|
||||
lock_version=1,
|
||||
)
|
||||
db.session.add(clone)
|
||||
db.session.commit()
|
||||
return payload(clone)
|
||||
|
||||
|
||||
def publish(
|
||||
profile_id: int, *, actor_id: int | None, expected_lock_version: Any,
|
||||
) -> dict[str, Any]:
|
||||
"""发布草稿并原子退役同编码旧版本;checksum 包含 Schema 身份与完整定义。"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError(
|
||||
'Only draft order document profile can be published',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
if not isinstance(expected_lock_version, int):
|
||||
raise ValidationError(
|
||||
'expected_lock_version is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED',
|
||||
)
|
||||
if expected_lock_version != profile.lock_version:
|
||||
raise ConflictError(
|
||||
'Order document profile draft was changed by another user',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT',
|
||||
)
|
||||
schema_version = _require_schema_version(profile.schema_version_id)
|
||||
normalized = _normalize_definition(profile.definition_json, schema_version=schema_version)
|
||||
profile.definition_json = normalized
|
||||
profile.structure_fingerprint = normalized['structure_fingerprint']
|
||||
_definition_contract(profile)
|
||||
encoded = json.dumps({
|
||||
'profile_code': profile.profile_code,
|
||||
'version': profile.version,
|
||||
'schema_version_id': schema_version.id,
|
||||
'schema_checksum': schema_version.checksum,
|
||||
'definition': normalized,
|
||||
}, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
now = datetime.utcnow()
|
||||
previous = ShippingOrderDocumentProfile.query.filter_by(
|
||||
profile_code=profile.profile_code, status='published',
|
||||
).first()
|
||||
if previous is not None:
|
||||
previous.status = 'retired'
|
||||
previous.retired_at = now
|
||||
db.session.flush()
|
||||
profile.checksum = hashlib.sha256(encoded).hexdigest()
|
||||
profile.status = 'published'
|
||||
profile.published_by_id = actor_id
|
||||
profile.published_at = now
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
|
||||
|
||||
def retire(profile_id: int) -> dict[str, Any]:
|
||||
"""手工退役当前发布版本;历史 Run 仍使用自身冻结快照。"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'published':
|
||||
raise ConflictError(
|
||||
'Only published order document profile can be retired',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RETIRE_INVALID',
|
||||
)
|
||||
profile.status = 'retired'
|
||||
profile.retired_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
|
||||
|
||||
def delete_draft(profile_id: int) -> None:
|
||||
"""删除未发布草稿;不可变版本永久保留审计。"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError(
|
||||
'Only draft order document profile can be deleted',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED',
|
||||
)
|
||||
db.session.delete(profile)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def published_snapshots_for_schema(schema_version_id: int) -> list[dict[str, Any]]:
|
||||
"""生成 Run 可直接冻结的 published Profile 快照,不返回 ORM 或当前引用。"""
|
||||
rows = ShippingOrderDocumentProfile.query.filter_by(
|
||||
schema_version_id=int(schema_version_id), status='published',
|
||||
).order_by(ShippingOrderDocumentProfile.profile_code.asc()).all()
|
||||
return [{
|
||||
'profile_id': item.id,
|
||||
'profile_code': item.profile_code,
|
||||
'version': item.version,
|
||||
'checksum': item.checksum,
|
||||
'schema_version_id': item.schema_version_id,
|
||||
'structure_fingerprint': item.structure_fingerprint,
|
||||
'definition': dict(item.definition_json or {}),
|
||||
} for item in rows]
|
||||
@@ -43,6 +43,7 @@ from app.services.shipping_notice.duplicate_detection import (
|
||||
from app.services.shipping_notice.document_candidate_persist import generate_candidate_no
|
||||
from app.services.shipping_notice.order_schema.runtime import persist_dynamic_order
|
||||
from app.services.shipping_notice.context_fields.runtime import canonical_mail_context
|
||||
from app.services.shipping_notice.order_extraction_workflow import frozen_document_text_for_dify
|
||||
|
||||
|
||||
def _load_intakes(
|
||||
@@ -184,6 +185,8 @@ def persist_order_extraction_result(
|
||||
schema_version_id: int,
|
||||
extraction_source: str = 'dify_workflow',
|
||||
frozen_context_by_intake: dict[int, dict[str, Any]] | None = None,
|
||||
frozen_layout_candidates_by_document: dict[int, list[dict[str, Any]]] | None = None,
|
||||
frozen_evidence_text_by_document: dict[int, str] | None = None,
|
||||
auto_create_enabled: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -200,6 +203,8 @@ def persist_order_extraction_result(
|
||||
schema_version_id: Run 冻结的 published Schema 版本。
|
||||
extraction_source: 固定为后台 Workflow 来源,不接受用户输入。
|
||||
frozen_context_by_intake: Run 按 Intake 冻结的确定性上下文;后台 Run 必须提供。
|
||||
frozen_layout_candidates_by_document: Run 按 Document 冻结的 L4 字段候选;只接受 accepted cell 证据。
|
||||
frozen_evidence_text_by_document: Run 实际发送给 Dify 的冻结文本;用于同源 quote 核验。
|
||||
auto_create_enabled: 冻结发布门禁;关闭时只落 Candidate,不自动创建/打开 Task。
|
||||
Returns:
|
||||
自动创建/打开的任务、待处理订单及缺失流程字段摘要。
|
||||
@@ -252,11 +257,16 @@ def persist_order_extraction_result(
|
||||
document_has_pending: dict[int, bool] = {int(row.id): False for row in documents}
|
||||
document_non_shipping_indexes: dict[int, list[int]] = {int(row.id): [] for row in documents}
|
||||
|
||||
# [STEP 1] 本轮选择状态完全由最新 LLM 结果决定,避免旧的 selected Candidate 混入自动建批集合。
|
||||
db.session.query(ShippingNoticeCandidate).filter(
|
||||
# [STEP 1] 新 Run 先撤销旧版本候选的可消费资格;旧记录仍保留用于审计与重识别失败回退。
|
||||
current_candidates = db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.intake_id.in_([int(row.id) for row in intakes]),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
).update({'selected': False}, synchronize_session=False)
|
||||
ShippingNoticeCandidate.is_current_version.is_(True),
|
||||
)
|
||||
if run_id is not None:
|
||||
current_candidates = current_candidates.filter(ShippingNoticeCandidate.order_extraction_run_id != int(run_id))
|
||||
current_candidates.update({'selected': False, 'is_current_version': False}, synchronize_session=False)
|
||||
current_candidates.update({'selected': False}, synchronize_session=False)
|
||||
|
||||
for index, raw_order in enumerate(orders):
|
||||
if not isinstance(raw_order, dict):
|
||||
@@ -310,9 +320,27 @@ def persist_order_extraction_result(
|
||||
actor_id=int(session.user_id),
|
||||
schema_version_id=schema_version_id,
|
||||
frozen_mail_context=(frozen_context_by_intake or {}).get(int(intake.id)),
|
||||
layout_candidates_by_document={
|
||||
int(item.id): list((frozen_layout_candidates_by_document or {}).get(int(item.id)) or [])
|
||||
for item in owned_docs
|
||||
},
|
||||
frozen_evidence_text_by_document=frozen_evidence_text_by_document,
|
||||
)
|
||||
if run_id is not None:
|
||||
dynamic['extraction'].run_id = int(run_id)
|
||||
layout_evidence_issues = [
|
||||
{
|
||||
'field': ','.join(str(code) for code in item.get('field_codes') or []) or 'document_layout',
|
||||
'severity': 'blocking',
|
||||
'reason': str(item.get('reason') or 'layout_evidence_unavailable'),
|
||||
'document_id': item.get('document_id'),
|
||||
}
|
||||
for item in (
|
||||
(dynamic['extraction'].validation_result_json or {}).get('deterministic_table_issues') or []
|
||||
)
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
blocking_conflicts.extend(layout_evidence_issues)
|
||||
summary = {**dynamic['header'], 'lines': dynamic['lines']}
|
||||
# Bill-to 是业务归属客户原文;简称只保存在 customer_matches 主数据快照中。
|
||||
if summary.get('bill_to_customer'):
|
||||
@@ -330,6 +358,21 @@ def persist_order_extraction_result(
|
||||
'field': ','.join(dynamic['blocked_fields']), 'severity': 'blocking',
|
||||
'reason': 'dynamic_schema_required_or_evidence_gate',
|
||||
}])
|
||||
field_confidence: dict[str, float] = {}
|
||||
for decision in dynamic['decisions']:
|
||||
field_code = str(decision.get('field_code') or '')
|
||||
if not field_code:
|
||||
continue
|
||||
confidence = float(decision.get('confidence') or 0.0)
|
||||
existing_confidence = field_confidence.get(field_code)
|
||||
field_confidence[field_code] = (
|
||||
confidence if existing_confidence is None else min(existing_confidence, confidence)
|
||||
)
|
||||
low_confidence_fields = sorted({
|
||||
field_code
|
||||
for field_code, minimum_confidence in dynamic['auto_create_key_field_thresholds'].items()
|
||||
if field_confidence.get(field_code, 0.0) < minimum_confidence
|
||||
})
|
||||
assessment = assess_candidate_business_summary(summary)
|
||||
normalized = assessment['normalized_summary']
|
||||
reasons: list[str] = []
|
||||
@@ -341,6 +384,8 @@ def persist_order_extraction_result(
|
||||
reasons.append('low_classification_confidence')
|
||||
if dynamic['blocked_fields']:
|
||||
reasons.append('dynamic_schema_gate')
|
||||
if low_confidence_fields:
|
||||
reasons.append('low_key_field_confidence')
|
||||
if blocking_conflicts:
|
||||
reasons.append('blocking_conflict')
|
||||
|
||||
@@ -348,7 +393,11 @@ def persist_order_extraction_result(
|
||||
active_keys_by_intake[int(intake.id)].add(candidate_key)
|
||||
candidate = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter_by(intake_id=int(intake.id), candidate_key=candidate_key)
|
||||
.filter_by(
|
||||
intake_id=int(intake.id),
|
||||
candidate_key=candidate_key,
|
||||
order_extraction_run_id=int(run_id) if run_id is not None else None,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if candidate is not None and candidate.consumed_task_id is not None:
|
||||
@@ -360,15 +409,17 @@ def persist_order_extraction_result(
|
||||
intake_id=int(intake.id),
|
||||
primary_document_id=int(document.id),
|
||||
candidate_key=candidate_key,
|
||||
order_extraction_run_id=int(run_id) if run_id is not None else None,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
candidate.primary_document_id = int(document.id)
|
||||
candidate.source_order_index = index
|
||||
candidate.order_extraction_id = int(dynamic['extraction'].id)
|
||||
candidate.order_extraction_run_id = int(run_id) if run_id is not None else None
|
||||
candidate.is_current_version = True
|
||||
candidate.extraction_source = extraction_source
|
||||
candidate.classification_confidence = classification_confidence
|
||||
candidate.field_confidence_json = {}
|
||||
candidate.field_confidence_json = field_confidence
|
||||
candidate.missing_fields_json = list(assessment['missing_required_fields']) + list(assessment['missing_process_fields'])
|
||||
candidate.evidence_json = list(dynamic['observations'])
|
||||
candidate.po_number = str(normalized.get('po_number') or '').strip() or None
|
||||
@@ -391,7 +442,7 @@ def persist_order_extraction_result(
|
||||
'request_id': request_id,
|
||||
'classification': classification,
|
||||
'classification_confidence': classification_confidence,
|
||||
'field_confidence': {},
|
||||
'field_confidence': field_confidence,
|
||||
'field_adjudication': {
|
||||
'schema_version_id': int(dynamic['extraction'].schema_version_id),
|
||||
'extraction_id': int(dynamic['extraction'].id),
|
||||
@@ -404,6 +455,8 @@ def persist_order_extraction_result(
|
||||
'missing_process_fields': assessment['missing_process_fields'],
|
||||
'process_issues': assessment['process_issues'],
|
||||
'auto_create_reasons': reasons,
|
||||
'low_confidence_fields': low_confidence_fields,
|
||||
'key_field_confidence_thresholds': dynamic['auto_create_key_field_thresholds'],
|
||||
'verified_reservation_evidence': [
|
||||
{
|
||||
'line_index': int(item.get('line_position') or 0),
|
||||
@@ -489,13 +542,14 @@ def persist_order_extraction_result(
|
||||
document.order_extraction_error_code = None
|
||||
document.order_extraction_error_message = None
|
||||
|
||||
# [STEP 3] 清理同一抽取版本中消失、且尚未消费的旧 Candidate。
|
||||
# [STEP 3] 只清理同一 Run 回放中消失的候选;不同 Run 的旧版本不得删除。
|
||||
for intake in intakes:
|
||||
active_keys = active_keys_by_intake[int(intake.id)]
|
||||
stale = db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
ShippingNoticeCandidate.extraction_source == extraction_source,
|
||||
ShippingNoticeCandidate.order_extraction_run_id == (int(run_id) if run_id is not None else None),
|
||||
)
|
||||
if active_keys:
|
||||
stale = stale.filter(ShippingNoticeCandidate.candidate_key.notin_(tuple(active_keys)))
|
||||
@@ -632,6 +686,20 @@ def submit_order_extraction_run_result(
|
||||
for item in snapshot_intakes
|
||||
if isinstance(item, dict) and str(item.get('intake_id') or '').isdigit()
|
||||
}
|
||||
frozen_layout_candidates_by_document = {
|
||||
int(document['document_id']): list(document.get('layout_schema_candidates') or [])
|
||||
for intake in snapshot_intakes if isinstance(intake, dict)
|
||||
for document in intake.get('documents') or []
|
||||
if isinstance(document, dict) and str(document.get('document_id') or '').isdigit()
|
||||
}
|
||||
frozen_evidence_text_by_document = {
|
||||
int(document['document_id']): (
|
||||
frozen_document_text_for_dify(document) or str(document.get('extracted_text') or '')
|
||||
)
|
||||
for intake in snapshot_intakes if isinstance(intake, dict)
|
||||
for document in intake.get('documents') or []
|
||||
if isinstance(document, dict) and str(document.get('document_id') or '').isdigit()
|
||||
}
|
||||
intake_nos = [str(item.get('intake_no') or '').strip().upper() for item in snapshot_intakes]
|
||||
intake_nos = [item for item in intake_nos if item]
|
||||
intakes = db.session.query(ShippingNoticeIntake).filter(
|
||||
@@ -772,5 +840,9 @@ def submit_order_extraction_run_result(
|
||||
schema_version_id=int(run.schema_version_id),
|
||||
extraction_source='dify_workflow',
|
||||
frozen_context_by_intake=frozen_context_by_intake,
|
||||
auto_create_enabled=bool((run.provider_config_json or {}).get('auto_create_enabled', False)),
|
||||
frozen_layout_candidates_by_document=frozen_layout_candidates_by_document,
|
||||
frozen_evidence_text_by_document=frozen_evidence_text_by_document,
|
||||
auto_create_enabled=bool(
|
||||
((run.input_snapshot_json or {}).get('auto_creation_policy') or {}).get('enabled', False)
|
||||
),
|
||||
)
|
||||
@@ -11,6 +11,8 @@ from __future__ import annotations
|
||||
import copy
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.reservation_id import is_valid_reservation_id
|
||||
|
||||
|
||||
def _field_values(fields: Any, field_code: str, codes: dict[str, str]) -> set[str]:
|
||||
"""读取某稳定字段的非空 Observation 值,供身份和冲突比较。"""
|
||||
@@ -34,6 +36,60 @@ def _line_identity(line: dict[str, Any], codes: dict[str, str]) -> tuple[str, st
|
||||
return None
|
||||
|
||||
|
||||
def _single_valid_reservation(line: dict[str, Any], codes: dict[str, str]) -> str | None:
|
||||
"""返回唯一合法的 Reservation;缺失、冲突或错位值都不能作为跨文档关联依据。"""
|
||||
values = {
|
||||
value for value in _field_values(line.get('fields'), 'reservation_id', codes)
|
||||
if is_valid_reservation_id(value)
|
||||
}
|
||||
return next(iter(values)) if len(values) == 1 else None
|
||||
|
||||
|
||||
def _completion_anchor_values(line: dict[str, Any], codes: dict[str, str]) -> dict[str, str]:
|
||||
"""读取可用于 PDF/邮件行补全的强锚点;只接受单一原子值。"""
|
||||
anchors: dict[str, str] = {}
|
||||
for field_code in ('part_number', 'line_no'):
|
||||
values = _field_values(line.get('fields'), field_code, codes)
|
||||
if len(values) == 1:
|
||||
anchors[field_code] = next(iter(values))
|
||||
return anchors
|
||||
|
||||
|
||||
def _find_unique_reservation_completion_line(
|
||||
lines: list[dict[str, Any]], incoming: dict[str, Any], codes: dict[str, str],
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
在同 PO 的既有行中找到可安全补齐 Reservation 的唯一行。
|
||||
|
||||
只有一侧有唯一合法 Reservation、另一侧完全缺失 Reservation,且可用料号或项次唯一匹配时返回。
|
||||
多行重复料号、锚点冲突和不完整邮件片段一律不自动关联,交由后续人工复核。
|
||||
"""
|
||||
incoming_reservation = _single_valid_reservation(incoming, codes)
|
||||
incoming_anchors = _completion_anchor_values(incoming, codes)
|
||||
if not incoming_anchors:
|
||||
return None
|
||||
|
||||
# Unit 以并发完成顺序聚合:既支持邮件先返回 Reservation、PDF 后返回订单行,
|
||||
# 也支持 PDF 先返回订单行、邮件后返回 Reservation。
|
||||
requires_candidate_reservation = incoming_reservation is None
|
||||
|
||||
candidate_sets: list[set[int]] = []
|
||||
for field_code, value in incoming_anchors.items():
|
||||
matches = {
|
||||
index for index, candidate in enumerate(lines)
|
||||
if (_single_valid_reservation(candidate, codes) is not None) == requires_candidate_reservation
|
||||
and _completion_anchor_values(candidate, codes).get(field_code) == value
|
||||
}
|
||||
# 两侧同时带有多个锚点时必须全部一致;只靠其中一个匹配会把同料号不同项次错并。
|
||||
if not matches:
|
||||
return None
|
||||
candidate_sets.append(matches)
|
||||
if not candidate_sets:
|
||||
return None
|
||||
candidates = set.intersection(*candidate_sets)
|
||||
return lines[next(iter(candidates))] if len(candidates) == 1 else None
|
||||
|
||||
|
||||
def _order_identity(order: dict[str, Any], codes: dict[str, str]) -> tuple[set[str], set[tuple[str, str]]]:
|
||||
"""返回可用于保守合并的 PO 集合和强行身份集合。"""
|
||||
po_numbers = _field_values(order.get('header_fields'), 'po_number', codes)
|
||||
@@ -68,8 +124,10 @@ def _merge_fields(target: list[dict[str, Any]], incoming: Any) -> None:
|
||||
seen.add(key)
|
||||
|
||||
|
||||
def _merge_order(target: dict[str, Any], incoming: dict[str, Any], codes: dict[str, str]) -> None:
|
||||
"""合并 Header 与同身份 Line;新 Line 按来源顺序追加。"""
|
||||
def _merge_order(
|
||||
target: dict[str, Any], incoming: dict[str, Any], codes: dict[str, str], *, matched_by_po: bool,
|
||||
) -> None:
|
||||
"""合并 Header 与同身份 Line;同 PO 下仅允许唯一强锚点补齐缺失 Reservation。"""
|
||||
_merge_fields(target.setdefault('header_fields', []), incoming.get('header_fields'))
|
||||
target_lines = target.setdefault('lines', [])
|
||||
target_by_identity = {
|
||||
@@ -81,10 +139,17 @@ def _merge_order(target: dict[str, Any], incoming: dict[str, Any], codes: dict[s
|
||||
continue
|
||||
identity = _line_identity(raw_line, codes)
|
||||
if identity is None or identity not in target_by_identity:
|
||||
cloned = copy.deepcopy(raw_line)
|
||||
target_lines.append(cloned)
|
||||
if identity is not None:
|
||||
target_by_identity[identity] = cloned
|
||||
completion_target = (
|
||||
_find_unique_reservation_completion_line(target_lines, raw_line, codes)
|
||||
if matched_by_po else None
|
||||
)
|
||||
if completion_target is not None:
|
||||
_merge_fields(completion_target.setdefault('fields', []), raw_line.get('fields'))
|
||||
else:
|
||||
cloned = copy.deepcopy(raw_line)
|
||||
target_lines.append(cloned)
|
||||
if identity is not None:
|
||||
target_by_identity[identity] = cloned
|
||||
else:
|
||||
_merge_fields(target_by_identity[identity].setdefault('fields', []), raw_line.get('fields'))
|
||||
target.setdefault('source_document_ids', []).append(incoming.get('primary_document_id'))
|
||||
@@ -106,12 +171,13 @@ def merge_unit_orders(*, orders: list[dict[str, Any]], schema_definition: dict[s
|
||||
if str(candidate.get('source_intake_no') or '').strip().upper() != intake_no:
|
||||
continue
|
||||
candidate_pos, candidate_lines = _order_identity(candidate, codes)
|
||||
if (len(po_numbers) == 1 and po_numbers == candidate_pos) or bool(line_keys & candidate_lines):
|
||||
matched_by_po = len(po_numbers) == 1 and po_numbers == candidate_pos
|
||||
if matched_by_po or bool(line_keys & candidate_lines):
|
||||
match = candidate
|
||||
break
|
||||
if match is None:
|
||||
order['source_document_ids'] = [order.get('primary_document_id')]
|
||||
merged.append(order)
|
||||
else:
|
||||
_merge_order(match, order, codes)
|
||||
_merge_order(match, order, codes, matched_by_po=matched_by_po)
|
||||
return merged
|
||||
@@ -0,0 +1,271 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_extraction_quality_service.py
|
||||
|
||||
用途:管理 L7 影子验收批次、双人标签、质量指标和双角色批准门禁。
|
||||
依赖:订单抽取 Run/Schema/质量模型、统一 AppError。
|
||||
逻辑:只保存匿名计数和错误标志;双人完全一致的 Run 才计入指标,批准批次供 Runtime Binding 自动建单门禁引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
Agent,
|
||||
ShippingOrderExtractionQualityBatch,
|
||||
ShippingOrderExtractionQualityLabel,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
|
||||
|
||||
THRESHOLDS = {
|
||||
'version': 'l7.v1', 'minimum_samples': 100,
|
||||
'minimum_precision': 0.995, 'minimum_recall': 0.98,
|
||||
'maximum_wrong_merge_rate': 0.005, 'maximum_wrong_split_rate': 0.005,
|
||||
'maximum_wrong_auto_create_count': 0,
|
||||
}
|
||||
|
||||
|
||||
def _batch_no() -> str:
|
||||
"""生成不含业务内容的影子验收批次编号。"""
|
||||
return f"SOQ-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def _label_signature(label: ShippingOrderExtractionQualityLabel) -> tuple[Any, ...]:
|
||||
"""生成双人一致性签名;只包含匿名计数和错误标志。"""
|
||||
return (
|
||||
int(label.core_expected_count), int(label.core_extracted_count), int(label.core_correct_count),
|
||||
bool(label.wrong_merge), bool(label.wrong_split), bool(label.wrong_auto_create),
|
||||
)
|
||||
|
||||
|
||||
def quality_metrics(batch: ShippingOrderExtractionQualityBatch) -> dict[str, Any]:
|
||||
"""汇总双人一致标签并计算固定 L7 指标,分歧/单人标签不计有效样本。"""
|
||||
grouped: dict[int, list[ShippingOrderExtractionQualityLabel]] = {}
|
||||
for label in batch.labels:
|
||||
grouped.setdefault(int(label.run_id), []).append(label)
|
||||
agreed = []
|
||||
disagreed = 0
|
||||
pending = 0
|
||||
for labels in grouped.values():
|
||||
if len(labels) < 2:
|
||||
pending += 1
|
||||
continue
|
||||
if len({_label_signature(item) for item in labels}) != 1:
|
||||
disagreed += 1
|
||||
continue
|
||||
agreed.append(labels[0])
|
||||
expected = sum(int(item.core_expected_count) for item in agreed)
|
||||
extracted = sum(int(item.core_extracted_count) for item in agreed)
|
||||
correct = sum(int(item.core_correct_count) for item in agreed)
|
||||
precision = correct / extracted if extracted else 0.0
|
||||
recall = correct / expected if expected else 0.0
|
||||
sample_count = len(agreed)
|
||||
wrong_merge_count = sum(1 for item in agreed if item.wrong_merge)
|
||||
wrong_split_count = sum(1 for item in agreed if item.wrong_split)
|
||||
wrong_auto_create_count = sum(1 for item in agreed if item.wrong_auto_create)
|
||||
reasons = []
|
||||
if sample_count < THRESHOLDS['minimum_samples']:
|
||||
reasons.append('insufficient_samples')
|
||||
if precision < THRESHOLDS['minimum_precision']:
|
||||
reasons.append('precision_below_threshold')
|
||||
if recall < THRESHOLDS['minimum_recall']:
|
||||
reasons.append('recall_below_threshold')
|
||||
if sample_count and wrong_merge_count / sample_count > THRESHOLDS['maximum_wrong_merge_rate']:
|
||||
reasons.append('wrong_merge_rate_above_threshold')
|
||||
if sample_count and wrong_split_count / sample_count > THRESHOLDS['maximum_wrong_split_rate']:
|
||||
reasons.append('wrong_split_rate_above_threshold')
|
||||
if wrong_auto_create_count > THRESHOLDS['maximum_wrong_auto_create_count']:
|
||||
reasons.append('wrong_auto_create_detected')
|
||||
return {
|
||||
'thresholds': dict(THRESHOLDS), 'agreed_sample_count': sample_count,
|
||||
'pending_review_count': pending, 'disagreed_review_count': disagreed,
|
||||
'core_expected_count': expected, 'core_extracted_count': extracted,
|
||||
'core_correct_count': correct, 'precision': round(precision, 6), 'recall': round(recall, 6),
|
||||
'wrong_merge_count': wrong_merge_count, 'wrong_split_count': wrong_split_count,
|
||||
'wrong_auto_create_count': wrong_auto_create_count,
|
||||
'wrong_merge_rate': round(wrong_merge_count / sample_count, 6) if sample_count else 0.0,
|
||||
'wrong_split_rate': round(wrong_split_count / sample_count, 6) if sample_count else 0.0,
|
||||
'eligible': not reasons, 'blocking_reasons': reasons,
|
||||
}
|
||||
|
||||
|
||||
def serialize_quality_batch(batch: ShippingOrderExtractionQualityBatch) -> dict[str, Any]:
|
||||
"""返回脱敏批次、指标和批准人 ID,不返回 Run 内容或字段值。"""
|
||||
metrics = quality_metrics(batch)
|
||||
return {
|
||||
'id': batch.id, 'batch_no': batch.batch_no, 'owner_agent_id': batch.owner_agent_id,
|
||||
'schema_version_id': batch.schema_version_id,
|
||||
'threshold_version': batch.threshold_version, 'status': batch.status,
|
||||
'business_approved_by_id': batch.business_approved_by_id,
|
||||
'technical_approved_by_id': batch.technical_approved_by_id,
|
||||
'approved_at': batch.approved_at.isoformat() + 'Z' if batch.approved_at else None,
|
||||
'metrics': metrics,
|
||||
}
|
||||
|
||||
|
||||
def create_quality_batch(*, owner_agent_id: int, schema_version_id: int, actor_id: int) -> ShippingOrderExtractionQualityBatch:
|
||||
"""创建 collecting 批次;Owner 和 Schema 必须存在,阈值固定为当前规则。"""
|
||||
schema_version = db.session.get(ShippingOrderSchemaVersion, schema_version_id)
|
||||
if db.session.get(Agent, owner_agent_id) is None or schema_version is None:
|
||||
raise NotFoundError('Owner Agent or Schema version not found')
|
||||
if schema_version.status != 'published':
|
||||
raise ValidationError('Quality batch requires the currently published Schema version')
|
||||
batch = ShippingOrderExtractionQualityBatch(
|
||||
batch_no=_batch_no(), owner_agent_id=owner_agent_id, schema_version_id=schema_version_id,
|
||||
threshold_version=THRESHOLDS['version'], created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(batch)
|
||||
db.session.commit()
|
||||
return batch
|
||||
|
||||
|
||||
def list_approved_quality_batches(*, owner_agent_id: int) -> list[dict[str, Any]]:
|
||||
"""列出指定 Owner 当前仍达标的批准批次,供 Runtime Binding 管理端显式选择。"""
|
||||
if db.session.get(Agent, owner_agent_id) is None:
|
||||
raise NotFoundError('Owner Agent not found')
|
||||
from app.services.shipping_notice.order_schema.runtime import published_version
|
||||
|
||||
current_schema_id = published_version().id
|
||||
batches = (
|
||||
ShippingOrderExtractionQualityBatch.query
|
||||
.filter_by(
|
||||
owner_agent_id=owner_agent_id, schema_version_id=current_schema_id, status='approved',
|
||||
)
|
||||
.order_by(ShippingOrderExtractionQualityBatch.approved_at.desc())
|
||||
.all()
|
||||
)
|
||||
return [
|
||||
serialize_quality_batch(batch) for batch in batches
|
||||
if batch.threshold_version == THRESHOLDS['version']
|
||||
and quality_metrics(batch)['eligible']
|
||||
]
|
||||
|
||||
|
||||
def save_quality_label(*, batch_id: int, run_no: str, actor_id: int, payload: Any) -> ShippingOrderExtractionQualityBatch:
|
||||
"""新增或覆盖当前管理员标签;任一批准开始后即冻结标签,Run 必须符合批次边界。"""
|
||||
batch = db.session.get(ShippingOrderExtractionQualityBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Quality batch not found')
|
||||
actor = db.session.get(User, actor_id)
|
||||
if actor is None or actor.role != 'admin':
|
||||
raise ValidationError('Quality reviewer must be an administrator')
|
||||
if (
|
||||
batch.status in {'approved', 'rejected'}
|
||||
or batch.business_approved_by_id is not None
|
||||
or batch.technical_approved_by_id is not None
|
||||
):
|
||||
raise ConflictError('Quality batch is immutable', code='SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_IMMUTABLE')
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=str(run_no or '').strip()).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Order extraction run not found')
|
||||
if (
|
||||
int(run.owner_agent_id) != int(batch.owner_agent_id)
|
||||
or int(run.schema_version_id) != int(batch.schema_version_id)
|
||||
or run.status not in {'completed', 'needs_review'}
|
||||
# 自动建单 Run 属于生产执行,不能反向作为影子质量验收样本。
|
||||
or bool((run.provider_config_json or {}).get('auto_create_enabled'))
|
||||
):
|
||||
raise ValidationError(
|
||||
'Run is not eligible for this quality batch',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_RUN_INVALID',
|
||||
)
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError('Label payload must be an object')
|
||||
try:
|
||||
expected = int(payload.get('core_expected_count'))
|
||||
extracted = int(payload.get('core_extracted_count'))
|
||||
correct = int(payload.get('core_correct_count'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Quality counts must be integers') from exc
|
||||
if min(expected, extracted, correct) < 0 or correct > min(expected, extracted):
|
||||
raise ValidationError('Quality counts are inconsistent')
|
||||
flags = {key: payload.get(key, False) for key in ('wrong_merge', 'wrong_split', 'wrong_auto_create')}
|
||||
if any(not isinstance(value, bool) for value in flags.values()):
|
||||
raise ValidationError('Quality error flags must be boolean')
|
||||
label = ShippingOrderExtractionQualityLabel.query.filter_by(
|
||||
batch_id=batch.id, run_id=run.id, reviewer_id=actor_id,
|
||||
).first()
|
||||
if label is None:
|
||||
label = ShippingOrderExtractionQualityLabel(batch_id=batch.id, run_id=run.id, reviewer_id=actor_id)
|
||||
db.session.add(label)
|
||||
label.core_expected_count = expected
|
||||
label.core_extracted_count = extracted
|
||||
label.core_correct_count = correct
|
||||
label.wrong_merge = flags['wrong_merge']
|
||||
label.wrong_split = flags['wrong_split']
|
||||
label.wrong_auto_create = flags['wrong_auto_create']
|
||||
db.session.flush()
|
||||
batch.status = 'ready' if quality_metrics(batch)['eligible'] else 'collecting'
|
||||
db.session.commit()
|
||||
return batch
|
||||
|
||||
|
||||
def approve_quality_batch(*, batch_id: int, role: str, actor_id: int) -> ShippingOrderExtractionQualityBatch:
|
||||
"""按 business/technical 角色批准;两角色必须不同管理员且指标仍达标。"""
|
||||
batch = db.session.get(ShippingOrderExtractionQualityBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Quality batch not found')
|
||||
if batch.status == 'rejected':
|
||||
raise ConflictError('Quality batch was rejected')
|
||||
actor = db.session.get(User, actor_id)
|
||||
if actor is None or actor.role != 'admin':
|
||||
raise ValidationError('Quality approver must be an administrator')
|
||||
if not quality_metrics(batch)['eligible']:
|
||||
raise ConflictError(
|
||||
'Quality thresholds are not satisfied',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_NOT_READY',
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
if role == 'business':
|
||||
if batch.business_approved_by_id is not None:
|
||||
if batch.business_approved_by_id == actor_id:
|
||||
return batch
|
||||
raise ConflictError('Business approval is immutable')
|
||||
if batch.technical_approved_by_id == actor_id:
|
||||
raise ValidationError('Business and technical approvers must be different')
|
||||
batch.business_approved_by_id = actor_id
|
||||
batch.business_approved_at = now
|
||||
elif role == 'technical':
|
||||
if batch.technical_approved_by_id is not None:
|
||||
if batch.technical_approved_by_id == actor_id:
|
||||
return batch
|
||||
raise ConflictError('Technical approval is immutable')
|
||||
if batch.business_approved_by_id == actor_id:
|
||||
raise ValidationError('Business and technical approvers must be different')
|
||||
batch.technical_approved_by_id = actor_id
|
||||
batch.technical_approved_at = now
|
||||
else:
|
||||
raise ValidationError('Approval role must be business or technical')
|
||||
if batch.business_approved_by_id and batch.technical_approved_by_id:
|
||||
batch.status = 'approved'
|
||||
batch.approved_at = now
|
||||
else:
|
||||
batch.status = 'ready'
|
||||
db.session.commit()
|
||||
return batch
|
||||
|
||||
|
||||
def require_approved_quality_batch(
|
||||
*, batch_id: int | None, owner_agent_id: int, schema_version_id: int,
|
||||
) -> ShippingOrderExtractionQualityBatch:
|
||||
"""校验引用的是同 Owner/Schema、当前阈值且双人批准的批次。"""
|
||||
batch = db.session.get(ShippingOrderExtractionQualityBatch, int(batch_id or 0))
|
||||
if (
|
||||
batch is None or batch.status != 'approved'
|
||||
or int(batch.owner_agent_id) != int(owner_agent_id)
|
||||
or int(batch.schema_version_id) != int(schema_version_id)
|
||||
or batch.threshold_version != THRESHOLDS['version']
|
||||
or not quality_metrics(batch)['eligible']
|
||||
):
|
||||
raise ConflictError(
|
||||
'Approved order extraction quality batch is required',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_GATE_BLOCKED',
|
||||
)
|
||||
return batch
|
||||
@@ -29,6 +29,7 @@ from app.models import (
|
||||
Job,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRunIntake,
|
||||
ShippingOrderSchemaVersion,
|
||||
@@ -201,7 +202,11 @@ def _build_snapshot(
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
schema_version: ShippingOrderSchemaVersion,
|
||||
) -> dict[str, Any]:
|
||||
"""冻结 Worker 所需的完整输入;保存文档正文,后续执行不再回读可变 Document。"""
|
||||
"""冻结 Worker 所需的正文、布局和 Schema 映射;后续执行不再回读可变 Document。"""
|
||||
from app.services.shipping_notice.order_document_profile_service import (
|
||||
published_snapshots_for_schema,
|
||||
)
|
||||
|
||||
intake_ids = [intake.id for intake in intakes]
|
||||
documents = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
@@ -216,8 +221,31 @@ def _build_snapshot(
|
||||
for asset in db.session.query(FileAsset).filter(FileAsset.id.in_(asset_ids)).all()
|
||||
} if asset_ids else {}
|
||||
documents_by_intake: dict[int, list[dict[str, Any]]] = {intake.id: [] for intake in intakes}
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
table_contract = compile_table_header_contract(dict(schema_version.definition_json or {}))
|
||||
|
||||
for document in documents:
|
||||
asset = assets.get(document.asset_id) if document.asset_id is not None else None
|
||||
layout_snapshot = current_layout_snapshot(document)
|
||||
layout_candidate = (
|
||||
layout_snapshot.get('layout_candidate')
|
||||
if isinstance(layout_snapshot, dict) and isinstance(layout_snapshot.get('layout_candidate'), dict)
|
||||
else None
|
||||
)
|
||||
layout_schema_candidates: list[dict[str, Any]] = []
|
||||
if layout_candidate is not None:
|
||||
try:
|
||||
layout_schema_candidates = map_layout_document_to_schema(
|
||||
layout_candidate, contract=table_contract,
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
layout_schema_candidates = [{
|
||||
'mapping_status': 'failed',
|
||||
'issues': ['layout_schema_mapping_invalid'],
|
||||
}]
|
||||
documents_by_intake[document.intake_id].append({
|
||||
'document_id': document.id,
|
||||
'document_type': document.document_type,
|
||||
@@ -230,6 +258,8 @@ def _build_snapshot(
|
||||
'parse_status': document.parse_status,
|
||||
'extracted_text': document.extracted_text or '',
|
||||
'parse_warnings': document.parse_warnings_json or [],
|
||||
'layout_snapshot': layout_snapshot,
|
||||
'layout_schema_candidates': layout_schema_candidates,
|
||||
})
|
||||
incomplete = [
|
||||
intake.intake_no
|
||||
@@ -246,7 +276,7 @@ def _build_snapshot(
|
||||
details={'intake_nos': incomplete},
|
||||
)
|
||||
return {
|
||||
'snapshot_version': 1,
|
||||
'snapshot_version': 3,
|
||||
'user_id': user_id,
|
||||
'owner_agent_id': owner_agent_id,
|
||||
'conversation_id': conversation_id,
|
||||
@@ -257,6 +287,7 @@ def _build_snapshot(
|
||||
'extraction_contract': dify_contract(schema_version),
|
||||
'definition': schema_version.definition_json,
|
||||
},
|
||||
'order_document_profiles': published_snapshots_for_schema(schema_version.id),
|
||||
'intakes': [
|
||||
{
|
||||
'intake_id': intake.id,
|
||||
@@ -315,6 +346,9 @@ def create_order_extraction_run(
|
||||
agent_id: int,
|
||||
conversation_id: str,
|
||||
intake_nos: list[str],
|
||||
reparse_of_run: ShippingOrderExtractionRun | None = None,
|
||||
reparse_reason: str | None = None,
|
||||
reparse_comment: str | None = None,
|
||||
) -> tuple[ShippingOrderExtractionRun, bool]:
|
||||
"""
|
||||
创建订单抽取 Run;相同服务器快照幂等复用,不同输入抢占同一 Intake 时返回冲突。
|
||||
@@ -324,18 +358,47 @@ def create_order_extraction_run(
|
||||
agent_id: 用户入口货代 Agent 主键,不是后台 Provider ID。
|
||||
conversation_id: HXOPS ChatSession.session_id;首次后台 Run 可为空,由服务端创建并绑定 Intake。
|
||||
intake_nos: 1-50 个已解析且未消费的 Intake 编号。
|
||||
reparse_of_run: 可选的终态来源 Run;提供时创建新的版本化识别 Run。
|
||||
reparse_reason/reparse_comment: 用户选择的重识别原因及可选备注,仅用于审计。
|
||||
Returns:
|
||||
`(run, reused)`;Run 与通用 Job 在同一事务创建。
|
||||
"""
|
||||
owner_agent = _require_owner_agent(user=user, agent_id=agent_id)
|
||||
if reparse_of_run is not None and (
|
||||
int(reparse_of_run.user_id) != int(user.id)
|
||||
or str(reparse_of_run.status or '') not in {'completed', 'needs_review', 'failed', 'cancelled'}
|
||||
):
|
||||
raise ConflictError(
|
||||
'Only a terminal run owned by the current user can be reparsed',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE',
|
||||
)
|
||||
intakes = _load_intakes(user_id=user.id, intake_nos=intake_nos)
|
||||
from app.services.agent_runtime_binding_service import resolve_runtime_binding
|
||||
from app.services.agent_runtime_binding_service import resolve_executor_governance, resolve_runtime_binding
|
||||
|
||||
binding = resolve_runtime_binding(
|
||||
owner_agent_id=owner_agent.id,
|
||||
capability_code='shipping.order_extraction',
|
||||
)
|
||||
schema_version = published_version()
|
||||
quality_batch_id = binding.quality_batch_id
|
||||
if bool((binding.config_json or {}).get('auto_create_enabled')):
|
||||
from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch
|
||||
|
||||
require_approved_quality_batch(
|
||||
batch_id=quality_batch_id,
|
||||
owner_agent_id=owner_agent.id,
|
||||
schema_version_id=int(schema_version.id),
|
||||
)
|
||||
# 绑定决定本业务如何执行;执行器决定所有调用方共享的容量与熔断保护,两者一起冻结到 Run。
|
||||
binding_config = {
|
||||
**dict(binding.config_json or {}),
|
||||
# 单元执行参数属于实现细节,使用统一保守默认值而不在应用管理形成配置分支。
|
||||
'unit_concurrency': 2,
|
||||
'unit_max_attempts': 2,
|
||||
'unit_retry_backoff_ms': 500,
|
||||
'max_model_units': 20,
|
||||
**resolve_executor_governance(binding.provider_agent),
|
||||
}
|
||||
session = _resolve_conversation(
|
||||
user_id=user.id,
|
||||
agent_id=owner_agent.id,
|
||||
@@ -350,6 +413,9 @@ def create_order_extraction_run(
|
||||
intakes=intakes,
|
||||
schema_version=schema_version,
|
||||
)
|
||||
# 自动建单总开关与字段模板一起冻结,后续管理员变更不影响已创建 Run。
|
||||
from app.services.shipping_notice.order_schema.service import get_auto_creation_policy
|
||||
snapshot['auto_creation_policy'] = get_auto_creation_policy()
|
||||
snapshot_hash = _sha256(snapshot)
|
||||
idempotency_key = _sha256({
|
||||
'user_id': user.id,
|
||||
@@ -359,7 +425,9 @@ def create_order_extraction_run(
|
||||
'input_snapshot_hash': snapshot_hash,
|
||||
'runtime_binding_id': binding.id,
|
||||
'provider_agent_id': binding.provider_agent_id,
|
||||
'provider_config': binding.config_json or {},
|
||||
'provider_config': binding_config,
|
||||
'quality_batch_id': quality_batch_id,
|
||||
'reparse_of_run_id': reparse_of_run.id if reparse_of_run is not None else None,
|
||||
})
|
||||
existing = _run_by_idempotency_key(idempotency_key)
|
||||
if existing is not None:
|
||||
@@ -389,7 +457,8 @@ def create_order_extraction_run(
|
||||
owner_agent_id=owner_agent.id,
|
||||
runtime_binding_id=binding.id,
|
||||
provider_agent_id=binding.provider_agent_id,
|
||||
provider_config_json=dict(binding.config_json or {}),
|
||||
quality_batch_id=quality_batch_id,
|
||||
provider_config_json=binding_config,
|
||||
provider_snapshot_json={
|
||||
'provider_agent_id': binding.provider_agent_id,
|
||||
'runtime_provider': binding.provider_agent.runtime_provider,
|
||||
@@ -398,6 +467,9 @@ def create_order_extraction_run(
|
||||
'dify_app_id': binding.provider_agent.dify_app_id,
|
||||
'api_base_url': binding.provider_agent.api_base_url,
|
||||
},
|
||||
reparse_of_run_id=reparse_of_run.id if reparse_of_run is not None else None,
|
||||
reparse_reason=str(reparse_reason or '').strip()[:64] or None,
|
||||
reparse_comment=str(reparse_comment or '').strip()[:2000] or None,
|
||||
conversation_id=conversation_id,
|
||||
schema_version_id=schema_version.id,
|
||||
input_snapshot_hash=snapshot_hash,
|
||||
@@ -463,6 +535,77 @@ def create_order_extraction_run(
|
||||
return run, False
|
||||
|
||||
|
||||
def reparse_order_extraction_run(
|
||||
*, user_id: int, run_no: str, reason: str, comment: str | None = None,
|
||||
) -> tuple[ShippingOrderExtractionRun, bool]:
|
||||
"""
|
||||
基于原始未消费 Intake 创建新的订单识别版本,并冻结当前发布的规则快照。
|
||||
|
||||
核心逻辑:锁定来源 Run 并复用同一活跃后继 Run;新 Run 不复用 Provider 成功缓存,
|
||||
因此 Schema、Binding、Profile 与布局快照均从当前发布态重新冻结。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户 ID;只能重识别自己的终态 Run。
|
||||
run_no: 来源 Run 编号。
|
||||
reason: 必填的受控业务原因;用于审计和后续差异解释。
|
||||
comment: 可选补充说明,不写入 Provider 输入。
|
||||
|
||||
Returns:
|
||||
`(run, reused)`;重复请求返回同一活跃后继 Run。
|
||||
"""
|
||||
source = (
|
||||
db.session.query(ShippingOrderExtractionRun)
|
||||
.filter_by(user_id=user_id, run_no=str(run_no or '').strip())
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if source is None:
|
||||
raise NotFoundError('Shipping order extraction run not found', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND')
|
||||
if str(source.status or '') not in {'completed', 'needs_review', 'failed', 'cancelled'}:
|
||||
raise ConflictError(
|
||||
'Only terminal order extraction runs can be reparsed',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE', details={'status': source.status},
|
||||
)
|
||||
normalized_reason = str(reason or '').strip().lower()
|
||||
if normalized_reason not in {'rule_updated', 'field_mapping_error', 'document_quality', 'other'}:
|
||||
raise ValidationError('Invalid reparse reason', code='SHIPPING_NOTICE.ORDER_EXTRACTION_REPARSE_REASON_INVALID')
|
||||
successors = (
|
||||
ShippingOrderExtractionRun.query.filter_by(reparse_of_run_id=source.id)
|
||||
.order_by(ShippingOrderExtractionRun.created_at.desc()).all()
|
||||
)
|
||||
active = next((item for item in successors if item.status in {'queued', 'running', 'result_persisted'}), None)
|
||||
if active is not None:
|
||||
return active, True
|
||||
intake_nos = [
|
||||
str(item.get('intake_no') or '').strip().upper()
|
||||
for item in (source.input_snapshot_json or {}).get('intakes', [])
|
||||
if isinstance(item, dict) and str(item.get('intake_no') or '').strip()
|
||||
]
|
||||
if not intake_nos:
|
||||
raise ConflictError('The source run has no reusable intake snapshot', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE')
|
||||
owner_agent = db.session.get(Agent, int(source.owner_agent_id))
|
||||
user = db.session.get(User, int(user_id))
|
||||
if owner_agent is None or user is None:
|
||||
raise ConflictError('The source run cannot be reparsed', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE')
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=owner_agent.id, conversation_id=source.conversation_id, intake_nos=intake_nos,
|
||||
reparse_of_run=source, reparse_reason=normalized_reason, reparse_comment=comment,
|
||||
)
|
||||
if not reused:
|
||||
# [STEP 1] 新版尚未完成时先撤销旧候选的建单资格,防止用户在两个版本之间误建单。
|
||||
source_candidates = db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.order_extraction_run_id == source.id,
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
).all()
|
||||
for candidate in source_candidates:
|
||||
candidate.selected_before_superseded = bool(candidate.selected)
|
||||
candidate.selected = False
|
||||
candidate.is_current_version = False
|
||||
source.superseded_by_run_id = run.id
|
||||
source.superseded_at = datetime.utcnow()
|
||||
return run, reused
|
||||
|
||||
|
||||
def get_order_extraction_run(*, user_id: int, run_no: str) -> ShippingOrderExtractionRun:
|
||||
"""按用户与 Run 编号查询;跨用户访问统一表现为不存在。"""
|
||||
run = ShippingOrderExtractionRun.query.filter_by(user_id=user_id, run_no=run_no).first()
|
||||
@@ -516,6 +659,13 @@ def retry_order_extraction_run(*, user_id: int, run_no: str) -> tuple[ShippingOr
|
||||
)
|
||||
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
config = run.provider_config_json if isinstance(run.provider_config_json, dict) else {}
|
||||
if config.get('retired_protocol') is True:
|
||||
raise ConflictError(
|
||||
'The failed run uses a retired order extraction protocol. Create a new extraction instead.',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_PROTOCOL_RETIRED',
|
||||
details={'run_no': run.run_no},
|
||||
)
|
||||
snapshot_intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
if not snapshot_intakes or any(
|
||||
not isinstance(item, dict) or not isinstance(item.get('deterministic_context'), dict)
|
||||
@@ -579,6 +729,33 @@ def list_order_extraction_runs(
|
||||
return query.order_by(ShippingOrderExtractionRun.created_at.desc()).limit(min(max(limit, 1), 100)).all()
|
||||
|
||||
|
||||
def _reparse_difference_summary(run: ShippingOrderExtractionRun) -> dict[str, Any] | None:
|
||||
"""返回新版与来源 Run 的脱敏规则差异计数,禁止比较或暴露邮件正文和 Provider 输出。"""
|
||||
source = run.reparse_source
|
||||
if source is None:
|
||||
return None
|
||||
current = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
previous = source.input_snapshot_json if isinstance(source.input_snapshot_json, dict) else {}
|
||||
current_schema = current.get('schema') if isinstance(current.get('schema'), dict) else {}
|
||||
previous_schema = previous.get('schema') if isinstance(previous.get('schema'), dict) else {}
|
||||
current_profiles = current.get('order_document_profiles') if isinstance(current.get('order_document_profiles'), list) else []
|
||||
previous_profiles = previous.get('order_document_profiles') if isinstance(previous.get('order_document_profiles'), list) else []
|
||||
profile_checksums = lambda values: sorted(
|
||||
str(item.get('checksum') or '') for item in values if isinstance(item, dict)
|
||||
)
|
||||
def layout_versions(snapshot: dict[str, Any]) -> list[str]:
|
||||
return sorted(
|
||||
str((document.get('layout_snapshot') or {}).get('version') or '')
|
||||
for intake in snapshot.get('intakes') or [] if isinstance(intake, dict)
|
||||
for document in intake.get('documents') or [] if isinstance(document, dict)
|
||||
)
|
||||
return {
|
||||
'schema_changed': str(current_schema.get('checksum') or '') != str(previous_schema.get('checksum') or ''),
|
||||
'profile_changed': profile_checksums(current_profiles) != profile_checksums(previous_profiles),
|
||||
'layout_changed': layout_versions(current) != layout_versions(previous),
|
||||
}
|
||||
|
||||
|
||||
def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
"""输出用户态 Run 与通用进度投影;不返回正文、Provider、Job 或节点诊断字段。"""
|
||||
intake_snapshot = run.input_snapshot_json.get('intakes', []) if isinstance(run.input_snapshot_json, dict) else []
|
||||
@@ -601,6 +778,13 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str,
|
||||
'schema_version': schema_snapshot.get('version'),
|
||||
'schema_checksum': schema_snapshot.get('checksum'),
|
||||
'attempt_count': int(run.attempt_count or 0),
|
||||
'reparse': {
|
||||
'source_run_no': run.reparse_source.run_no if run.reparse_source is not None else None,
|
||||
'superseding_run_no': run.superseding_run.run_no if run.superseding_run is not None else None,
|
||||
'reason': run.reparse_reason,
|
||||
'superseded_at': run.superseded_at.isoformat() + 'Z' if run.superseded_at else None,
|
||||
'difference_summary': _reparse_difference_summary(run),
|
||||
},
|
||||
'progress': {
|
||||
'version': int(run.progress_version or 0),
|
||||
'current_stage_code': run.current_stage_code or ('queued' if run.status == 'queued' else None),
|
||||
@@ -611,10 +795,9 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str,
|
||||
'last_activity_at': run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None,
|
||||
},
|
||||
'result': run.result_json,
|
||||
'error': (
|
||||
{'code': run.error_code, 'message': run.error_message}
|
||||
if run.error_code or run.error_message else None
|
||||
),
|
||||
# Worker/provider error text can contain upstream details. Workspace cards only need a
|
||||
# stable code to select a safe, actionable user hint; full diagnostics stay admin-only.
|
||||
'error': {'code': run.error_code} if run.error_code else None,
|
||||
'created_at': run.created_at.isoformat() + 'Z' if run.created_at else None,
|
||||
'updated_at': run.updated_at.isoformat() + 'Z' if run.updated_at else None,
|
||||
'started_at': run.started_at.isoformat() + 'Z' if run.started_at else None,
|
||||
@@ -631,7 +814,9 @@ def serialize_order_extraction_message_state(run: ShippingOrderExtractionRun) ->
|
||||
return {
|
||||
'status': 'failed' if failed else 'partially_completed' if partial else 'completed' if completed else 'extracting',
|
||||
'phase': 'failed' if failed else 'result_persisted' if run.status == 'result_persisted' else 'llm_extraction',
|
||||
'message': str(run.error_message or '') if failed else '',
|
||||
# The chat log is user-visible on history replay. It must follow the same redaction
|
||||
# boundary as the workspace Run API and never persist upstream error text.
|
||||
'message': '',
|
||||
'created_count': int(result.get('created_count') or 0),
|
||||
'opened_existing_count': int(result.get('opened_existing_count') or 0),
|
||||
'pending_count': int(result.get('pending_count') or 0),
|
||||
@@ -866,8 +1051,8 @@ def list_order_extraction_diagnostic_runs(
|
||||
|
||||
|
||||
def get_order_extraction_diagnostic_run(*, admin_user_id: int, request_id: str | None, run_no: str) -> dict[str, Any]:
|
||||
"""读取一个 Run 的脱敏诊断详情、Job 尝试与节点生命周期,并审计管理员访问。"""
|
||||
from app.models import Job, ShippingOrderExtractionProgressEvent, ShippingOrderExtractionUnit
|
||||
"""读取 Run 的脱敏诊断、单元状态和证据门禁原因;不返回值、引文或版面内部 ID。"""
|
||||
from app.models import Job, ShippingOrderExtraction, ShippingOrderExtractionProgressEvent, ShippingOrderExtractionUnit
|
||||
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=run_no).first()
|
||||
if run is None:
|
||||
@@ -885,6 +1070,25 @@ def get_order_extraction_diagnostic_run(*, admin_user_id: int, request_id: str |
|
||||
.order_by(ShippingOrderExtractionUnit.position.asc()).all()
|
||||
if run.extraction_plan else []
|
||||
)
|
||||
extractions = ShippingOrderExtraction.query.filter_by(run_id=run.id).order_by(
|
||||
ShippingOrderExtraction.id.asc(),
|
||||
).all()
|
||||
evidence_issue_counts: dict[str, int] = {}
|
||||
traceable_observation_count = 0
|
||||
accepted_observation_count = 0
|
||||
for extraction in extractions:
|
||||
validation = extraction.validation_result_json if isinstance(extraction.validation_result_json, dict) else {}
|
||||
for issue in validation.get('deterministic_table_issues') or []:
|
||||
if not isinstance(issue, dict):
|
||||
continue
|
||||
reason = str(issue.get('reason') or 'unknown_layout_evidence_issue')[:128]
|
||||
evidence_issue_counts[reason] = evidence_issue_counts.get(reason, 0) + 1
|
||||
for observation in extraction.observations:
|
||||
if not observation.evidence_verified:
|
||||
continue
|
||||
accepted_observation_count += 1
|
||||
if observation.evidence_ref:
|
||||
traceable_observation_count += 1
|
||||
payload = {
|
||||
'run': _serialize_order_extraction_diagnostic_run(run),
|
||||
'job_attempts': [{
|
||||
@@ -918,6 +1122,15 @@ def get_order_extraction_diagnostic_run(*, admin_user_id: int, request_id: str |
|
||||
'duration_ms': _diagnostic_elapsed_ms(unit.started_at, unit.finished_at),
|
||||
'error_code': unit.error_code,
|
||||
} for unit in units],
|
||||
'evidence_gate': {
|
||||
'accepted_observation_count': accepted_observation_count,
|
||||
'traceable_observation_count': traceable_observation_count,
|
||||
'traceable_rate': (
|
||||
round(traceable_observation_count / accepted_observation_count, 4)
|
||||
if accepted_observation_count else 1.0
|
||||
),
|
||||
'issue_counts': evidence_issue_counts,
|
||||
},
|
||||
}
|
||||
_write_order_extraction_diagnostic_audit(
|
||||
admin_user_id=admin_user_id,
|
||||
@@ -1004,6 +1217,7 @@ def transition_order_extraction_run(
|
||||
intake.order_extraction_status = 'failed'
|
||||
intake.order_extraction_error_code = run.error_code
|
||||
intake.order_extraction_error_message = run.error_message
|
||||
_restore_candidates_after_failed_reparse(run)
|
||||
elif target_status == 'cancelled':
|
||||
run.finished_at = now
|
||||
for intake in intake_rows:
|
||||
@@ -1022,6 +1236,26 @@ def transition_order_extraction_run(
|
||||
return run
|
||||
|
||||
|
||||
def _restore_candidates_after_failed_reparse(run: ShippingOrderExtractionRun) -> None:
|
||||
"""新版重识别失败时恢复来源版本候选,避免业务被失败 Run 永久锁死。"""
|
||||
source_id = run.reparse_of_run_id
|
||||
if source_id is None:
|
||||
return
|
||||
source = db.session.get(ShippingOrderExtractionRun, int(source_id))
|
||||
if source is None or source.superseded_by_run_id != run.id:
|
||||
return
|
||||
candidates = db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.order_extraction_run_id == source.id,
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
).all()
|
||||
for candidate in candidates:
|
||||
candidate.is_current_version = True
|
||||
candidate.selected = bool(candidate.selected_before_superseded)
|
||||
candidate.selected_before_superseded = None
|
||||
source.superseded_by_run_id = None
|
||||
source.superseded_at = None
|
||||
|
||||
|
||||
def mark_order_extraction_persistence_started(run: ShippingOrderExtractionRun) -> None:
|
||||
"""在主业务事务内投影HXOPS落库阶段,避免与冻结输入校验产生跨Session写竞争。"""
|
||||
if run.status in {'completed', 'needs_review', 'failed', 'cancelled'}:
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/services/shipping_notice/order_extraction_workflow.py
|
||||
|
||||
用途:把订单抽取 Run 冻结快照编译为 Dify Workflow inputs,并校验结构化 outputs。
|
||||
依赖:DifyService、context_fields.dify_exposure、ShippingOrderExtractionRun、统一错误类型。
|
||||
逻辑:Provider 只接收字符串化抽取契约、文档及受控只读上下文;输出必须是成功 Workflow 中的 orders 数组。
|
||||
依赖:DifyService、MinerU 紧凑快照、context_fields.dify_exposure、统一错误类型。
|
||||
逻辑:PDF 优先使用 MinerU 分页文本和表格网格,Provider 只接收剥离布局内部载荷后的文档及受控上下文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,7 +16,12 @@ import requests
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.services.dify import DifyService
|
||||
from app.services.shipping_notice.context_fields.dify_exposure import compile_readonly_context
|
||||
from app.services.shipping_notice.notice_line_table import inspect_notice_table_text
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
OrderDocumentProfile,
|
||||
OrderProfileColumnRule,
|
||||
parse_html_table_with_order_profile,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
@@ -37,7 +42,7 @@ def _unit_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]]
|
||||
|
||||
def build_order_extraction_workflow_inputs(run: Any, *, unit: Any) -> dict[str, str]:
|
||||
"""
|
||||
从 Run 不可变快照构建版本化 Dify 执行清单。
|
||||
从 Run 不可变快照构建唯一的 Dify 执行清单。
|
||||
|
||||
核心逻辑:将 Run 标识、完整性哈希、LLM 抽取契约、冻结文档和受控只读提示
|
||||
收敛为唯一 Start 输入,防止 Workflow 变量随契约演进而漂移。
|
||||
@@ -48,37 +53,315 @@ def build_order_extraction_workflow_inputs(run: Any, *, unit: Any) -> dict[str,
|
||||
Returns:
|
||||
dict[str, str]: 仅含 execution_manifest JSON 字符串的 Dify inputs。
|
||||
"""
|
||||
return _build_unique_workflow_inputs(run, unit=unit)
|
||||
|
||||
|
||||
def _compact_layout_schema_candidates(document: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
把 L4 字段候选压缩为 unit.v3 模型上下文。
|
||||
|
||||
核心逻辑:仅保留页、表、行列、稳定 field_id、值、短引文、质量状态和问题码;
|
||||
严禁把 bbox、token、HTML、cell 内部标识或 field_code 发送给模型。
|
||||
|
||||
Args:
|
||||
document: Run 中冻结的单个 Document 快照。
|
||||
|
||||
Returns:
|
||||
list[dict[str, Any]]: 可供 LLM 补充的紧凑结构化表格候选。
|
||||
"""
|
||||
result: list[dict[str, Any]] = []
|
||||
for candidate in document.get('layout_schema_candidates') or []:
|
||||
if not isinstance(candidate, dict):
|
||||
continue
|
||||
rows: list[dict[str, Any]] = []
|
||||
for row in candidate.get('rows') or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
rows.append({
|
||||
'row_index': int(row.get('row_index') or 0),
|
||||
'role': str(row.get('role') or 'data'),
|
||||
'fields': [{
|
||||
'column_index': int(field.get('column_index') or 0),
|
||||
'field_id': str(field.get('field_id') or ''),
|
||||
'value': field.get('value'),
|
||||
'quote': str(field.get('quote') or field.get('value') or '')[:1000],
|
||||
} for field in row.get('fields') or [] if isinstance(field, dict) and field.get('field_id')],
|
||||
'issues': sorted({str(item) for item in row.get('issues') or [] if str(item)}),
|
||||
})
|
||||
result.append({
|
||||
'candidate_id': f"p{int(candidate.get('page_no') or 1)}:{str(candidate.get('table_id') or '')}",
|
||||
'page_no': int(candidate.get('page_no') or 1),
|
||||
'table_id': str(candidate.get('table_id') or ''),
|
||||
'continuation_of': candidate.get('continuation_of'),
|
||||
'status': str(candidate.get('mapping_status') or 'candidate'),
|
||||
'field_policy': 'locked' if candidate.get('mapping_status') == 'accepted' else 'suggested',
|
||||
'rows': rows,
|
||||
'issues': sorted({str(item) for item in candidate.get('issues') or [] if str(item)}),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def frozen_document_text_for_dify(document: dict[str, Any]) -> str:
|
||||
"""
|
||||
将冻结 MinerU 文本块和 HTML 表格转换为 LLM 可读的分页纯文本。
|
||||
|
||||
核心逻辑:按页和页面坐标恢复阅读顺序;表格展开为 TSV 以保留行列关系。
|
||||
HTML、bbox、cell_id 和 Provider 原始响应不得出现在返回文本中。
|
||||
|
||||
Args:
|
||||
document: Run 中冻结的 PDF Document 快照。
|
||||
|
||||
Returns:
|
||||
str: 可替换旧 PDF `extracted_text` 的紧凑文本;快照不可用时返回空字符串。
|
||||
"""
|
||||
if str(document.get('filename') or '').lower().rsplit('.', 1)[-1] != 'pdf':
|
||||
return ''
|
||||
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
|
||||
if layout.get('status') != 'ready':
|
||||
return ''
|
||||
entries: list[tuple[int, float, float, int, str]] = []
|
||||
for block in layout.get('text_blocks') or []:
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
text = ' '.join(str(block.get('text') or '').split()).strip()
|
||||
bbox = block.get('normalized_bbox') if isinstance(block.get('normalized_bbox'), dict) else {}
|
||||
if text:
|
||||
entries.append((
|
||||
int(block.get('page_no') or 1), float(bbox.get('y0') or 0),
|
||||
float(bbox.get('x0') or 0), 0, text,
|
||||
))
|
||||
for table_index, table in enumerate(layout.get('tables') or [], 1):
|
||||
if not isinstance(table, dict) or not str(table.get('html') or '').strip():
|
||||
continue
|
||||
try:
|
||||
grid = parse_html_grid(str(table['html']), table_id=str(table.get('table_id') or table_index))
|
||||
except ValidationError:
|
||||
continue
|
||||
rows = []
|
||||
for row in grid.rows:
|
||||
values = [
|
||||
' '.join(slot.text.split()).strip() if slot is not None else ''
|
||||
for slot in row
|
||||
]
|
||||
rows.append('\t'.join(values).rstrip())
|
||||
table_text = f"[TABLE {table_index}]\n" + '\n'.join(item for item in rows if item.strip())
|
||||
bbox = table.get('normalized_bbox') if isinstance(table.get('normalized_bbox'), dict) else {}
|
||||
entries.append((
|
||||
int(table.get('page_no') or 1), float(bbox.get('y0') or 0),
|
||||
float(bbox.get('x0') or 0), 1, table_text,
|
||||
))
|
||||
if not entries:
|
||||
return ''
|
||||
pages: list[str] = []
|
||||
current_page: int | None = None
|
||||
for page_no, _y, _x, _kind, text in sorted(entries):
|
||||
if page_no != current_page:
|
||||
pages.append(f'[PAGE {page_no}]')
|
||||
current_page = page_no
|
||||
pages.append(text)
|
||||
return '\n'.join(pages).strip()
|
||||
|
||||
|
||||
def _build_unique_workflow_inputs(run: Any, *, unit: Any) -> dict[str, str]:
|
||||
"""
|
||||
构建唯一清单,给 LLM 发送紧凑表格候选而非版面原始数据。
|
||||
|
||||
核心逻辑:PDF 优先使用 MinerU 分页文本与 TSV 表格,失败时保留旧文本;Document
|
||||
删除所有布局载荷,字段候选独立放入 structured_table_candidates。
|
||||
|
||||
Args:
|
||||
run: 已冻结输入快照的抽取 Run。
|
||||
unit: 当前抽取计划单元。
|
||||
|
||||
Returns:
|
||||
dict[str, str]: 仅含 execution_manifest 的 Dify Start 输入。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
schema = (
|
||||
schema_snapshot.get('extraction_contract')
|
||||
if isinstance(schema_snapshot.get('extraction_contract'), dict)
|
||||
else {}
|
||||
)
|
||||
schema = schema_snapshot.get('extraction_contract') if isinstance(schema_snapshot.get('extraction_contract'), dict) else {}
|
||||
intake, document = _unit_snapshot(run, unit)
|
||||
readonly_snapshot = {**snapshot, 'intakes': [intake]}
|
||||
document_for_dify = dict(document)
|
||||
candidates = _compact_layout_schema_candidates(document_for_dify)
|
||||
mineru_text = frozen_document_text_for_dify(document_for_dify)
|
||||
if mineru_text:
|
||||
document_for_dify['extracted_text'] = mineru_text
|
||||
document_for_dify['text_source'] = 'mineru'
|
||||
else:
|
||||
document_for_dify['text_source'] = 'legacy'
|
||||
for key in ('layout_snapshot', 'layout_schema_candidates', 'layout_candidate', 'deterministic_table_candidates'):
|
||||
document_for_dify.pop(key, None)
|
||||
manifest = {
|
||||
'contract_version': 'shipping_order_extraction.unit.v2',
|
||||
'run': {'run_no': str(run.run_no)},
|
||||
'unit': {
|
||||
'unit_id': int(unit.id),
|
||||
'unit_type': str(unit.unit_type),
|
||||
'intake_id': int(unit.intake_id),
|
||||
'intake_no': str(intake.get('intake_no') or ''),
|
||||
'document_id': int(unit.document_id),
|
||||
'document_type': str(unit.document_type),
|
||||
'unit_id': int(unit.id), 'unit_type': str(unit.unit_type),
|
||||
'intake_id': int(unit.intake_id), 'intake_no': str(intake.get('intake_no') or ''),
|
||||
'document_id': int(unit.document_id), 'document_type': str(unit.document_type),
|
||||
},
|
||||
'integrity': {'input_snapshot_hash': str(run.input_snapshot_hash)},
|
||||
'extraction_contract': schema,
|
||||
'documents': [{
|
||||
'intake_id': int(unit.intake_id),
|
||||
'intake_no': str(intake.get('intake_no') or ''),
|
||||
'document': dict(document),
|
||||
}],
|
||||
'document': document_for_dify,
|
||||
'structured_table_candidates': candidates,
|
||||
'readonly_hints': compile_readonly_context(readonly_snapshot),
|
||||
}
|
||||
return {'execution_manifest': json.dumps(manifest, ensure_ascii=False, separators=(',', ':'))}
|
||||
|
||||
|
||||
def _frozen_order_profile(raw: dict[str, Any]) -> OrderDocumentProfile:
|
||||
"""从 Run 快照恢复 Profile 纯契约;不查询当前数据库版本。"""
|
||||
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
|
||||
return OrderDocumentProfile(
|
||||
profile_code=str(raw.get('profile_code') or ''),
|
||||
version=int(raw.get('version') or 0),
|
||||
structure_fingerprint=str(definition.get('structure_fingerprint') or ''),
|
||||
header_row_index=definition.get('header_row_index'),
|
||||
data_start_row_index=definition.get('data_start_row_index'),
|
||||
row_structure=definition.get('row_structure', 'preserved'),
|
||||
column_rules=[OrderProfileColumnRule(**{
|
||||
key: value for key, value in rule.items() if key != 'target_fields'
|
||||
}) for rule in definition.get('column_rules') or [] if isinstance(rule, dict)],
|
||||
drop_zero_qty=definition.get('drop_zero_qty', True),
|
||||
)
|
||||
|
||||
|
||||
def _profile_snapshot_targets_valid(raw: dict[str, Any], *, contract: Any) -> bool:
|
||||
"""确认 Profile 冻结的 field_id/code 与 Run Schema 完全一致,禁止仅凭可变名称执行。"""
|
||||
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
|
||||
for rule in definition.get('column_rules') or []:
|
||||
if not isinstance(rule, dict):
|
||||
return False
|
||||
codes = [str(item or '') for item in rule.get('target_field_codes') or []]
|
||||
targets = rule.get('target_fields') if isinstance(rule.get('target_fields'), list) else []
|
||||
if len(codes) != len(targets):
|
||||
return False
|
||||
for code, target in zip(codes, targets, strict=True):
|
||||
config = contract.fields_by_code.get(code)
|
||||
if (
|
||||
not isinstance(target, dict) or config is None
|
||||
or str(target.get('field_code') or '') != code
|
||||
or str(target.get('field_id') or '') != str(config.get('field_id') or '')
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _dify_profile_candidates(tables: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""剥离内部 field_code,只向 Dify 暴露稳定 field_id、值和短逐字证据。"""
|
||||
result: list[dict[str, Any]] = []
|
||||
for table in tables:
|
||||
result.append({
|
||||
'profile_code': table.get('profile_code'),
|
||||
'profile_version': table.get('profile_version'),
|
||||
'profile_checksum': table.get('profile_checksum'),
|
||||
'table_id': table.get('table_id'),
|
||||
'page_no': table.get('page_no'),
|
||||
'rows': [{
|
||||
'row_index': row.get('row_index'),
|
||||
'status': row.get('status'),
|
||||
'fields': [{
|
||||
'field_id': field.get('field_id'),
|
||||
'value': field.get('value'),
|
||||
'quote': field.get('quote'),
|
||||
} for field in row.get('fields') or [] if isinstance(field, dict)],
|
||||
'issues': list(row.get('issues') or []),
|
||||
} for row in table.get('rows') or [] if isinstance(row, dict)],
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
"""
|
||||
用 Run 冻结 Profile 解析 MinerU HTML,并生成不含坐标/HTML的紧凑字段候选。
|
||||
|
||||
同一表命中多个 Profile 或命中 unsupported Profile 时设 blocking,调用方不得自动选择。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
|
||||
contract = compile_table_header_contract(definition)
|
||||
profiles = [
|
||||
item for item in snapshot.get('order_document_profiles') or []
|
||||
if isinstance(item, dict)
|
||||
and int(item.get('schema_version_id') or 0) == int(run.schema_version_id)
|
||||
]
|
||||
_intake, document = _unit_snapshot(run, unit)
|
||||
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
|
||||
if layout.get('status') != 'ready' or not profiles:
|
||||
return {'matched': False, 'blocking': False, 'tables': [], 'issues': []}
|
||||
result_tables: list[dict[str, Any]] = []
|
||||
issues: list[str] = []
|
||||
matched_any = False
|
||||
for raw_table in layout.get('tables') or []:
|
||||
if not isinstance(raw_table, dict) or not str(raw_table.get('html') or '').strip():
|
||||
continue
|
||||
table_id = str(raw_table.get('table_id') or '')
|
||||
matches: list[tuple[dict[str, Any], Any]] = []
|
||||
for raw_profile in profiles:
|
||||
if not _profile_snapshot_targets_valid(raw_profile, contract=contract):
|
||||
issues.append('order_profile_snapshot_field_mismatch')
|
||||
continue
|
||||
try:
|
||||
parsed = parse_html_table_with_order_profile(
|
||||
str(raw_table['html']),
|
||||
table_id=table_id,
|
||||
profile=_frozen_order_profile(raw_profile),
|
||||
contract=contract,
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
issues.append('order_profile_snapshot_invalid')
|
||||
continue
|
||||
if parsed.matched:
|
||||
matches.append((raw_profile, parsed))
|
||||
if not matches:
|
||||
continue
|
||||
matched_any = True
|
||||
if len(matches) != 1:
|
||||
issues.append('order_profile_multiple_matches')
|
||||
continue
|
||||
raw_profile, parsed = matches[0]
|
||||
if parsed.issues:
|
||||
issues.extend(parsed.issues)
|
||||
continue
|
||||
grid = parse_html_grid(str(raw_table['html']), table_id=table_id)
|
||||
compact_rows: list[dict[str, Any]] = []
|
||||
for row in parsed.rows:
|
||||
if row.status == 'deleted':
|
||||
compact_rows.append({'row_index': row.row_index, 'status': 'deleted', 'fields': []})
|
||||
continue
|
||||
quote = ' | '.join(
|
||||
slot.text.strip() for slot in grid.rows[row.row_index]
|
||||
if slot is not None and slot.text.strip()
|
||||
)[:1000]
|
||||
fields: list[dict[str, Any]] = []
|
||||
for code, value in row.fields.items():
|
||||
config = contract.fields_by_code.get(code)
|
||||
if config is None:
|
||||
continue
|
||||
fields.append({
|
||||
'field_id': str(config.get('field_id') or ''),
|
||||
'field_code': code,
|
||||
'value': value,
|
||||
'quote': quote,
|
||||
})
|
||||
compact_rows.append({
|
||||
'row_index': row.row_index,
|
||||
'status': row.status,
|
||||
'fields': fields,
|
||||
'issues': row.issues,
|
||||
})
|
||||
result_tables.append({
|
||||
'profile_code': str(raw_profile.get('profile_code') or ''),
|
||||
'profile_version': int(raw_profile.get('version') or 0),
|
||||
'profile_checksum': str(raw_profile.get('checksum') or ''),
|
||||
'table_id': table_id,
|
||||
'page_no': int(raw_table.get('page_no') or 1),
|
||||
'rows': compact_rows,
|
||||
})
|
||||
return {
|
||||
'execution_manifest': json.dumps(manifest, ensure_ascii=False, separators=(',', ':')),
|
||||
'matched': matched_any,
|
||||
'blocking': bool(issues),
|
||||
'tables': result_tables,
|
||||
'issues': sorted(set(issues)),
|
||||
}
|
||||
|
||||
|
||||
@@ -140,8 +423,8 @@ def parse_order_extraction_workflow_result(result: dict[str, Any]) -> list[dict[
|
||||
|
||||
|
||||
def validate_unit_orders(run: Any, *, unit: Any, orders: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""强制单元结果只能引用当前 Intake/Document,阻止跨附件伪造关联或证据。"""
|
||||
intake, _document = _unit_snapshot(run, unit)
|
||||
"""强制单元来源边界及 accepted 字段锁,阻止跨附件引用或覆盖确定性值。"""
|
||||
intake, document = _unit_snapshot(run, unit)
|
||||
intake_no = str(intake.get('intake_no') or '').strip().upper()
|
||||
for order in orders:
|
||||
if str(order.get('source_intake_no') or '').strip().upper() != intake_no:
|
||||
@@ -168,11 +451,59 @@ def validate_unit_orders(run: Any, *, unit: Any, orders: list[dict[str, Any]]) -
|
||||
'Unit observation references another document',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
_validate_locked_layout_fields(document, orders=orders)
|
||||
return orders
|
||||
|
||||
|
||||
def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dict[str, Any]]) -> None:
|
||||
"""
|
||||
校验模型完整保留 accepted 版面字段,不允许删改后端确定性映射。
|
||||
|
||||
Args:
|
||||
document: 当前 Unit 的冻结 Document,可能含 accepted 或 needs_review 候选。
|
||||
orders: Dify 返回的单 Unit 订单。
|
||||
|
||||
Raises:
|
||||
ValidationError: accepted 候选值缺失或被替换;needs_review 候选不参与锁定。
|
||||
"""
|
||||
locked: dict[str, set[str]] = {}
|
||||
for candidate in document.get('layout_schema_candidates') or []:
|
||||
if not isinstance(candidate, dict) or candidate.get('mapping_status') != 'accepted':
|
||||
continue
|
||||
for row in candidate.get('rows') or []:
|
||||
if not isinstance(row, dict) or row.get('role') == 'deleted':
|
||||
continue
|
||||
for field in row.get('fields') or []:
|
||||
if not isinstance(field, dict) or not field.get('field_id'):
|
||||
continue
|
||||
locked.setdefault(str(field['field_id']), set()).add(
|
||||
json.dumps(field.get('value'), ensure_ascii=False, sort_keys=True),
|
||||
)
|
||||
if not locked:
|
||||
return
|
||||
returned: dict[str, set[str]] = {}
|
||||
for order in orders:
|
||||
groups = [order.get('header_fields') or []]
|
||||
groups.extend(line.get('fields') or [] for line in order.get('lines') or [] if isinstance(line, dict))
|
||||
for fields in groups:
|
||||
for field in fields if isinstance(fields, list) else []:
|
||||
if not isinstance(field, dict) or str(field.get('field_id') or '') not in locked:
|
||||
continue
|
||||
field_id = str(field['field_id'])
|
||||
for observation in field.get('observations') or []:
|
||||
if isinstance(observation, dict):
|
||||
returned.setdefault(field_id, set()).add(
|
||||
json.dumps(observation.get('value'), ensure_ascii=False, sort_keys=True),
|
||||
)
|
||||
if any(returned.get(field_id, set()) != values for field_id, values in locked.items()):
|
||||
raise ValidationError(
|
||||
'Workflow changed or omitted an accepted layout field',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
|
||||
|
||||
def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None:
|
||||
"""完整确定性表格单元直接生成动态订单;无法覆盖必填字段时返回 None 交给模型。"""
|
||||
"""仅 accepted layout 完整表可零 Provider;其他结构或纯文本一律交给模型补充。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
schema = (
|
||||
@@ -182,83 +513,92 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An
|
||||
)
|
||||
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
|
||||
intake, document = _unit_snapshot(run, unit)
|
||||
inspected = inspect_notice_table_text(
|
||||
str(document.get('extracted_text') or ''),
|
||||
contract=compile_table_header_contract(definition),
|
||||
layout_order = _build_accepted_layout_order(
|
||||
unit=unit, intake=intake, document=document, schema=schema, definition=definition,
|
||||
)
|
||||
rows = inspected.get('lines') if isinstance(inspected.get('lines'), list) else []
|
||||
if not rows or inspected.get('ambiguous_fields'):
|
||||
if layout_order is not None:
|
||||
return [layout_order]
|
||||
return None
|
||||
|
||||
|
||||
def _build_accepted_layout_order(
|
||||
*, unit: Any, intake: dict[str, Any], document: dict[str, Any],
|
||||
schema: dict[str, Any], definition: dict[str, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
把唯一且完整的 accepted L4 表格转换为零 Provider 订单。
|
||||
|
||||
Args:
|
||||
unit: 当前抽取单元,用于固定 document_id。
|
||||
intake: 当前冻结 Intake,用于固定 source_intake_no。
|
||||
document: 含 layout_schema_candidates 的冻结 Document。
|
||||
schema: Dify 抽取契约元信息。
|
||||
definition: Run 冻结 Schema 完整定义,用于 required/scope 门禁。
|
||||
|
||||
Returns:
|
||||
完整确定性订单;候选非唯一、含问题或缺必填字段时返回 None。
|
||||
"""
|
||||
candidates = [
|
||||
item for item in document.get('layout_schema_candidates') or []
|
||||
if isinstance(item, dict) and item.get('mapping_status') == 'accepted'
|
||||
]
|
||||
if len(candidates) != 1 or candidates[0].get('issues'):
|
||||
return None
|
||||
fields = [
|
||||
item for item in definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True)
|
||||
and item.get('collection_mode', 'llm_extraction') == 'llm_extraction'
|
||||
]
|
||||
by_code = {str(item.get('field_code') or ''): item for item in fields}
|
||||
text = str(document.get('extracted_text') or '')
|
||||
|
||||
def quote_for(row: dict[str, Any]) -> str:
|
||||
part_number = str(row.get('part_number') or '')
|
||||
return next((line.strip() for line in text.splitlines() if part_number and part_number in line), part_number)
|
||||
|
||||
by_id = {str(item.get('field_id') or ''): item for item in fields}
|
||||
line_groups: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
quote = quote_for(row)
|
||||
raw_fields = []
|
||||
for code, value in row.items():
|
||||
config = by_code.get(str(code))
|
||||
if config is None or config.get('scope') != 'line' or value in (None, ''):
|
||||
continue
|
||||
raw_fields.append({
|
||||
'field_id': str(config['field_id']),
|
||||
'observations': [{
|
||||
'value': value,
|
||||
'document_id': int(unit.document_id),
|
||||
'quote': quote,
|
||||
'confidence': 1.0,
|
||||
}],
|
||||
})
|
||||
line_groups.append({'fields': raw_fields})
|
||||
|
||||
header_fields = []
|
||||
for code, config in by_code.items():
|
||||
if config.get('scope') != 'header':
|
||||
header_values: dict[str, list[dict[str, Any]]] = {}
|
||||
for row in candidates[0].get('rows') or []:
|
||||
if not isinstance(row, dict) or row.get('role') in {'deleted', 'empty', 'summary', 'repeated_header'}:
|
||||
continue
|
||||
values = {str(row.get(code)) for row in rows if row.get(code) not in (None, '')}
|
||||
if len(values) == 1:
|
||||
value = next(iter(values))
|
||||
header_fields.append({
|
||||
'field_id': str(config['field_id']),
|
||||
'observations': [{
|
||||
'value': value,
|
||||
'document_id': int(unit.document_id),
|
||||
'quote': quote_for(rows[0]),
|
||||
'confidence': 1.0,
|
||||
}],
|
||||
})
|
||||
|
||||
line_fields: list[dict[str, Any]] = []
|
||||
for raw in row.get('fields') or []:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
field_id = str(raw.get('field_id') or '')
|
||||
config = by_id.get(field_id)
|
||||
if config is None or raw.get('value') in (None, ''):
|
||||
continue
|
||||
observation = {
|
||||
'value': raw.get('value'), 'document_id': int(unit.document_id),
|
||||
'quote': str(raw.get('quote') or raw.get('value') or '')[:1000], 'confidence': 1.0,
|
||||
}
|
||||
if config.get('scope') == 'header':
|
||||
header_values.setdefault(field_id, []).append(observation)
|
||||
else:
|
||||
line_fields.append({'field_id': field_id, 'observations': [observation]})
|
||||
if line_fields:
|
||||
line_groups.append({'fields': line_fields})
|
||||
header_fields = []
|
||||
for field_id, observations in header_values.items():
|
||||
unique = {json.dumps(item['value'], ensure_ascii=False, sort_keys=True) for item in observations}
|
||||
if len(unique) != 1:
|
||||
return None
|
||||
header_fields.append({'field_id': field_id, 'observations': [observations[0]]})
|
||||
if not line_groups:
|
||||
return None
|
||||
present_header = {item['field_id'] for item in header_fields}
|
||||
for config in fields:
|
||||
if not config.get('required'):
|
||||
continue
|
||||
field_id = str(config['field_id'])
|
||||
field_id = str(config.get('field_id') or '')
|
||||
if config.get('scope') == 'header' and field_id not in present_header:
|
||||
return None
|
||||
if config.get('scope') == 'line' and any(
|
||||
field_id not in {item['field_id'] for item in group['fields']} for group in line_groups
|
||||
):
|
||||
return None
|
||||
return [{
|
||||
'schema_version_id': schema.get('schema_version_id'),
|
||||
'schema_checksum': schema.get('checksum'),
|
||||
'classification': 'shipping_request',
|
||||
'classification_confidence': 1.0,
|
||||
return {
|
||||
'schema_version_id': schema.get('schema_version_id'), 'schema_checksum': schema.get('checksum'),
|
||||
'classification': 'shipping_request', 'classification_confidence': 1.0,
|
||||
'source_intake_no': str(intake.get('intake_no') or ''),
|
||||
'primary_document_id': int(unit.document_id),
|
||||
'header_fields': header_fields,
|
||||
'lines': line_groups,
|
||||
'conflicts': [],
|
||||
}]
|
||||
'header_fields': header_fields, 'lines': line_groups, 'conflicts': [],
|
||||
}
|
||||
|
||||
|
||||
def execute_order_extraction_workflow(*, run: Any, unit: Any, provider: Any, timeout_seconds: int, event_observer=None) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
|
||||
@@ -8,6 +8,7 @@ backend/app/services/shipping_notice/order_schema/runtime.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
@@ -162,9 +163,11 @@ def _quote_supports_value(value: Any, config: dict[str, Any], quote: str) -> boo
|
||||
return bool(normalized_value) and normalized_value in normalized_quote
|
||||
|
||||
|
||||
def _verified_observations(raw: dict[str, Any], config: dict[str, Any],
|
||||
documents: dict[int, ShippingNoticeDocument]) -> list[dict[str, Any]]:
|
||||
"""验证动态 Observation 的字段值、Document 归属、逐字 quote 与类型化值支持关系。"""
|
||||
def _verified_observations(
|
||||
raw: dict[str, Any], config: dict[str, Any], documents: dict[int, ShippingNoticeDocument],
|
||||
frozen_evidence_text_by_document: dict[int, str] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""验证动态 Observation;优先使用该 Run 实际发送给 Dify 的冻结文本,旧正文仅作回退。"""
|
||||
items = raw.get('observations') if isinstance(raw.get('observations'), list) else []
|
||||
verified: list[dict[str, Any]] = []
|
||||
for item in items:
|
||||
@@ -175,7 +178,9 @@ def _verified_observations(raw: dict[str, Any], config: dict[str, Any],
|
||||
quote = str(item.get('quote') or '').strip()
|
||||
if document is None or value is None or not _validate(value, config):
|
||||
continue
|
||||
if not quote or quote not in str(document.extracted_text or ''):
|
||||
frozen_text = str((frozen_evidence_text_by_document or {}).get(int(document.id)) or '')
|
||||
source_texts = [frozen_text, str(document.extracted_text or '')]
|
||||
if not quote or not any(quote in text for text in source_texts if text):
|
||||
continue
|
||||
if not _quote_supports_value(value, config, quote):
|
||||
continue
|
||||
@@ -189,6 +194,11 @@ def _verified_observations(raw: dict[str, Any], config: dict[str, Any],
|
||||
'quote': quote,
|
||||
'confidence': confidence,
|
||||
'source_type': _source_type(document),
|
||||
'evidence_ref': (
|
||||
f'document:{int(document.id)}:quote:'
|
||||
f'{hashlib.sha256(quote.encode("utf-8")).hexdigest()[:24]}'
|
||||
),
|
||||
'evidence_metadata': {'kind': 'text_quote'},
|
||||
})
|
||||
return verified
|
||||
|
||||
@@ -223,9 +233,11 @@ def _choose_value(observations: list[dict[str, Any]], config: dict[str, Any]) ->
|
||||
|
||||
def _persist_field(*, extraction: ShippingOrderExtraction, line_id: int | None, raw: dict[str, Any],
|
||||
config: dict[str, Any], documents: dict[int, ShippingNoticeDocument],
|
||||
backend_candidates: list[dict[str, Any]]) -> tuple[Any, str, list[dict[str, Any]], dict[str, Any]]:
|
||||
backend_candidates: list[dict[str, Any]],
|
||||
frozen_evidence_text_by_document: dict[int, str] | None = None,
|
||||
) -> tuple[Any, str, list[dict[str, Any]], dict[str, Any]]:
|
||||
"""持久化字段全部 Observation、最终 Decision 和可查询类型化 Value。"""
|
||||
candidates = _verified_observations(raw, config, documents)
|
||||
candidates = _verified_observations(raw, config, documents, frozen_evidence_text_by_document)
|
||||
candidates.extend(backend_candidates)
|
||||
observation_rows: list[ShippingOrderFieldObservation] = []
|
||||
for item in candidates:
|
||||
@@ -234,6 +246,8 @@ def _persist_field(*, extraction: ShippingOrderExtraction, line_id: int | None,
|
||||
source_document_id=int(item['document'].id), source_type=item['source_type'],
|
||||
extractor=item.get('extractor') or 'dify_dynamic_schema', raw_value_json=_json_value(item['value']),
|
||||
normalized_value_json=_json_value(item['value']), evidence_quote=item['quote'],
|
||||
evidence_ref=item.get('evidence_ref'),
|
||||
evidence_metadata_json=item.get('evidence_metadata'),
|
||||
confidence=Decimal(str(item['confidence'])), evidence_verified=True,
|
||||
)
|
||||
db.session.add(row)
|
||||
@@ -263,57 +277,138 @@ def _persist_field(*, extraction: ShippingOrderExtraction, line_id: int | None,
|
||||
'id': int(item.id), 'field_id': config['field_id'], 'line_id': line_id,
|
||||
'source_type': item.source_type, 'document_id': item.source_document_id,
|
||||
'value': item.normalized_value_json, 'evidence_verified': bool(item.evidence_verified),
|
||||
'confidence': float(item.confidence),
|
||||
'evidence_ref': item.evidence_ref,
|
||||
'evidence_kind': (
|
||||
item.evidence_metadata_json.get('kind')
|
||||
if isinstance(item.evidence_metadata_json, dict) else None
|
||||
),
|
||||
} for item in observation_rows]
|
||||
decision_payload = {
|
||||
'id': int(decision.id), 'field_id': config['field_id'], 'field_code': config['field_code'], 'line_id': line_id,
|
||||
'status': status, 'value': _json_value(value), 'reason_code': reason,
|
||||
'observation_ids': list(decision.supporting_observation_ids_json or []),
|
||||
# 保守取所有已采纳证据的最低置信度,防止一条低可信来源被高可信来源掩盖。
|
||||
'confidence': min((float(item.confidence) for item in observation_rows), default=0.0),
|
||||
}
|
||||
return value, status, observations, decision_payload
|
||||
|
||||
|
||||
def _backend_rows(
|
||||
def _layout_rows(
|
||||
documents: list[ShippingNoticeDocument], *, schema_definition: dict[str, Any],
|
||||
layout_candidates_by_document: dict[int, list[dict[str, Any]]] | None,
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""从 EML/PDF Document 保留列边界的文本生成后端表格观察原料。"""
|
||||
contract = compile_table_header_contract(schema_definition)
|
||||
"""
|
||||
读取 Run 冻结的 accepted layout cell 候选;纯文本猜列只生成复核原因。
|
||||
|
||||
Args:
|
||||
documents: 当前 Intake 锁定 Document。
|
||||
schema_definition: Run 冻结 Schema,用于 field_id/code 一致性校验。
|
||||
layout_candidates_by_document: document_id 到冻结 L4 candidates 的映射。
|
||||
|
||||
Returns:
|
||||
可形成 verified Observation 的 accepted 行,以及机器可读阻断原因。
|
||||
"""
|
||||
fields_by_id = {
|
||||
str(item.get('field_id') or ''): str(item.get('field_code') or '')
|
||||
for item in schema_definition.get('fields') or [] if isinstance(item, dict)
|
||||
}
|
||||
document_map = {int(item.id): item for item in documents}
|
||||
rows: list[dict[str, Any]] = []
|
||||
issues: list[dict[str, Any]] = []
|
||||
frozen = layout_candidates_by_document or {}
|
||||
for document in documents:
|
||||
inspected = inspect_notice_table_text(str(document.extracted_text or ''), contract=contract)
|
||||
parsed_rows = inspected['lines']
|
||||
if inspected['ambiguous_fields']:
|
||||
issues.append({
|
||||
'document_id': int(document.id),
|
||||
'reason': 'ambiguous_table_headers',
|
||||
'field_codes': list(inspected['ambiguous_fields']),
|
||||
})
|
||||
for position, raw in enumerate(parsed_rows):
|
||||
if isinstance(raw, dict):
|
||||
rows.append({**raw, '_document': document, '_position': position})
|
||||
candidates = frozen.get(int(document.id)) or []
|
||||
if not candidates:
|
||||
inspected = inspect_notice_table_text(
|
||||
str(document.extracted_text or ''),
|
||||
contract=compile_table_header_contract(schema_definition),
|
||||
)
|
||||
if inspected.get('lines') or inspected.get('ambiguous_fields'):
|
||||
issues.append({
|
||||
'document_id': int(document.id),
|
||||
'reason': 'plain_text_table_has_no_cell_evidence',
|
||||
'field_codes': sorted({
|
||||
str(code) for row in inspected.get('lines') or [] if isinstance(row, dict)
|
||||
for code, value in row.items() if value not in (None, '')
|
||||
} | {str(code) for code in inspected.get('ambiguous_fields') or []}),
|
||||
})
|
||||
continue
|
||||
for candidate in candidates:
|
||||
if not isinstance(candidate, dict) or candidate.get('mapping_status') != 'accepted':
|
||||
issues.append({
|
||||
'document_id': int(document.id),
|
||||
'reason': 'layout_table_needs_review',
|
||||
'field_codes': sorted({
|
||||
fields_by_id.get(str(field.get('field_id') or ''), '')
|
||||
for row in candidate.get('rows') or [] if isinstance(row, dict)
|
||||
for field in row.get('fields') or [] if isinstance(field, dict)
|
||||
} - {''}),
|
||||
})
|
||||
continue
|
||||
for raw_row in candidate.get('rows') or []:
|
||||
if not isinstance(raw_row, dict) or raw_row.get('role') in {'deleted', 'empty', 'summary', 'repeated_header'}:
|
||||
continue
|
||||
row: dict[str, Any] = {
|
||||
'_document': document,
|
||||
'_page_no': int(candidate.get('page_no') or 1),
|
||||
'_table_id': str(candidate.get('table_id') or ''),
|
||||
'_row_index': int(raw_row.get('row_index') or 0),
|
||||
'_evidence': {},
|
||||
}
|
||||
for field in raw_row.get('fields') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
field_id = str(field.get('field_id') or '')
|
||||
code = fields_by_id.get(field_id)
|
||||
if not code or not field.get('cell_id') or not field.get('evidence_ref'):
|
||||
continue
|
||||
row[code] = field.get('value')
|
||||
row['_evidence'][code] = {
|
||||
'evidence_ref': str(field['evidence_ref']),
|
||||
'quote': str(field.get('quote') or field.get('value') or '')[:1000],
|
||||
'metadata': {
|
||||
'kind': 'layout_cell', 'page_no': row['_page_no'],
|
||||
'table_id': row['_table_id'], 'row_index': row['_row_index'],
|
||||
'column_index': int(field.get('column_index') or 0),
|
||||
'cell_id': str(field['cell_id']),
|
||||
},
|
||||
}
|
||||
if row['_evidence']:
|
||||
rows.append(row)
|
||||
unknown_ids = set(frozen) - set(document_map)
|
||||
if unknown_ids:
|
||||
issues.append({'document_id': None, 'reason': 'layout_candidate_document_mismatch', 'field_codes': []})
|
||||
return rows, issues
|
||||
|
||||
|
||||
def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str, Any]],
|
||||
rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""使用当前动态行任一稳定字段值关联后端表格行,避免按行号或目标字段自证。"""
|
||||
signatures: list[tuple[str, Any]] = []
|
||||
"""仅用同 Document 的强身份字段关联 layout 行,禁止 Qty 等常见值导致跨文档串行。"""
|
||||
strong_codes = {
|
||||
'part_number', 'customer_part_number', 'aws_part_number',
|
||||
'reservation_id', 'line_no', 'po_number',
|
||||
}
|
||||
signatures: list[tuple[str, Any, int]] = []
|
||||
for raw in raw_fields:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
config = configs.get(str(raw.get('field_id') or ''))
|
||||
if config is None:
|
||||
if config is None or str(config.get('field_code') or '') not in strong_codes:
|
||||
continue
|
||||
for item in raw.get('observations') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
value = _normalize(item.get('value'), config)
|
||||
if value is not None:
|
||||
signatures.append((str(config['field_code']), value))
|
||||
document_id = item.get('document_id')
|
||||
if value is not None and str(document_id or '').isdigit():
|
||||
signatures.append((str(config['field_code']), value, int(document_id)))
|
||||
configs_by_code = {str(item['field_code']): item for item in configs.values()}
|
||||
matched = []
|
||||
for row in rows:
|
||||
for code, expected in signatures:
|
||||
for code, expected, document_id in signatures:
|
||||
if int(row['_document'].id) != document_id:
|
||||
continue
|
||||
config = configs_by_code.get(code)
|
||||
if config is None or row.get(code) in (None, ''):
|
||||
continue
|
||||
@@ -324,7 +419,7 @@ def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str,
|
||||
|
||||
|
||||
def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""从已关联后端表格行读取当前字段候选,用于一致或冲突裁决。"""
|
||||
"""从已关联 accepted layout cell 读取当前字段候选,用于一致或冲突裁决。"""
|
||||
if not rows:
|
||||
return []
|
||||
code = str(config['field_code'])
|
||||
@@ -335,9 +430,13 @@ def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) -
|
||||
value = _normalize(row.get(code), config)
|
||||
if value is None or not _validate(value, config):
|
||||
continue
|
||||
evidence = row.get('_evidence', {}).get(code) if isinstance(row.get('_evidence'), dict) else None
|
||||
if not isinstance(evidence, dict):
|
||||
continue
|
||||
result.append({
|
||||
'value': value, 'document': row['_document'], 'quote': None, 'confidence': 0.9,
|
||||
'source_type': 'backend_table', 'extractor': 'backend_table',
|
||||
'value': value, 'document': row['_document'], 'quote': evidence['quote'], 'confidence': 1.0,
|
||||
'source_type': 'attachment_table', 'extractor': 'layout_schema_mapping',
|
||||
'evidence_ref': evidence['evidence_ref'], 'evidence_metadata': evidence['metadata'],
|
||||
})
|
||||
return result
|
||||
|
||||
@@ -351,6 +450,8 @@ def persist_dynamic_order(
|
||||
actor_id: int | None,
|
||||
schema_version_id: int | None = None,
|
||||
frozen_mail_context: dict[str, Any] | None = None,
|
||||
layout_candidates_by_document: dict[int, list[dict[str, Any]]] | None = None,
|
||||
frozen_evidence_text_by_document: dict[int, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""按当前 published 或 Run 锁定版本裁决订单,返回下游投影与阻断字段。"""
|
||||
version = (
|
||||
@@ -407,7 +508,10 @@ def persist_dynamic_order(
|
||||
observations.extend(context_observations)
|
||||
decisions.extend(context_decisions)
|
||||
blocked.extend(context_blocked)
|
||||
backend_rows, table_issues = _backend_rows(documents, schema_definition=version.definition_json or {})
|
||||
backend_rows, table_issues = _layout_rows(
|
||||
documents, schema_definition=version.definition_json or {},
|
||||
layout_candidates_by_document=layout_candidates_by_document,
|
||||
)
|
||||
for issue in table_issues:
|
||||
blocked.extend(str(code) for code in issue['field_codes'])
|
||||
groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [
|
||||
@@ -438,6 +542,7 @@ def persist_dynamic_order(
|
||||
value, status, field_observations, decision = _persist_field(
|
||||
extraction=extraction, line_id=line_id, raw=raw, config=config, documents=document_map,
|
||||
backend_candidates=_backend_candidates(config, rows=associated_rows),
|
||||
frozen_evidence_text_by_document=frozen_evidence_text_by_document,
|
||||
)
|
||||
observations.extend(field_observations)
|
||||
decision['line_position'] = position
|
||||
@@ -455,6 +560,7 @@ def persist_dynamic_order(
|
||||
value, status, field_observations, decision = _persist_field(
|
||||
extraction=extraction, line_id=line_id, raw={}, config=config, documents=document_map,
|
||||
backend_candidates=_backend_candidates(config, rows=associated_rows),
|
||||
frozen_evidence_text_by_document=frozen_evidence_text_by_document,
|
||||
)
|
||||
decision['line_position'] = position
|
||||
observations.extend(field_observations)
|
||||
@@ -490,4 +596,17 @@ def persist_dynamic_order(
|
||||
'observations': observations,
|
||||
'decisions': decisions,
|
||||
'customer_matches': customer_matches,
|
||||
'auto_create_key_field_thresholds': {
|
||||
str(item['field_code']): float(item['minimum_confidence'])
|
||||
for item in all_configs.values()
|
||||
if item.get('auto_create_key_field') is True and item.get('minimum_confidence') is not None
|
||||
},
|
||||
'required_key_field_codes': sorted({
|
||||
str(item['field_code'])
|
||||
for item in all_configs.values()
|
||||
if item.get('required') and (
|
||||
item.get('business_purpose') in {'part_number', 'quantity', 'reservation_id'}
|
||||
or item.get('field_code') == 'po_number'
|
||||
)
|
||||
}),
|
||||
}
|
||||
@@ -112,6 +112,30 @@ def _definition(version: ShippingOrderSchemaVersion) -> dict[str, Any]:
|
||||
return _copy_json(version.definition_json or {'schema_code': SCHEMA_CODE, 'version': version.version, 'fields': []})
|
||||
|
||||
|
||||
def _auto_creation_policy(raw: Any) -> dict[str, Any]:
|
||||
"""校验订单解析自动建单开关;字段阈值由各字段配置独立维护。"""
|
||||
policy = raw if isinstance(raw, dict) else {}
|
||||
enabled = policy.get('enabled', False)
|
||||
if not isinstance(enabled, bool):
|
||||
raise ValidationError('auto_creation_policy.enabled must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
return {'enabled': enabled}
|
||||
|
||||
|
||||
def get_auto_creation_policy() -> dict[str, Any]:
|
||||
"""返回订单解析运行策略;Schema 未初始化时默认关闭自动建单。"""
|
||||
schema = _schema()
|
||||
return _auto_creation_policy(schema.auto_creation_policy_json if schema else {})
|
||||
|
||||
|
||||
def save_auto_creation_policy(raw: Any, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""更新订单解析自动建单总开关,不修改字段模板或历史版本。"""
|
||||
schema = _require_schema()
|
||||
schema.auto_creation_policy_json = _auto_creation_policy(raw)
|
||||
schema.updated_by_id = actor_id
|
||||
db.session.commit()
|
||||
return get_auto_creation_policy()
|
||||
|
||||
|
||||
def _enabled_fields(definition: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""筛选当前版本实际生效字段,供发布门禁和 Dify 运行契约复用。"""
|
||||
return [dict(item) for item in definition.get('fields') or [] if item.get('enabled', True)]
|
||||
@@ -308,6 +332,7 @@ def get_state() -> dict[str, Any]:
|
||||
'display_name': schema.display_name,
|
||||
'description': schema.description,
|
||||
'status': schema.status,
|
||||
'auto_creation_policy': get_auto_creation_policy(),
|
||||
},
|
||||
# Retired fields remain available to historical records, not the current configuration workspace.
|
||||
'fields': [_field_payload(item) for item in ShippingOrderField.query.filter_by(
|
||||
@@ -793,7 +818,7 @@ def delete_field(
|
||||
def _field_runtime_references(field_id: str) -> list[str]:
|
||||
"""返回字段仍被哪些可运行下游配置引用,供退役与 Schema 发布共用。"""
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryParsingProfile,
|
||||
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingOrderDocumentProfile,
|
||||
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition,
|
||||
)
|
||||
references: list[str] = []
|
||||
@@ -810,6 +835,18 @@ def _field_runtime_references(field_id: str) -> list[str]:
|
||||
)
|
||||
if parsing_reference:
|
||||
references.append('inventory_parsing_profile')
|
||||
order_profile_reference = any(
|
||||
any(
|
||||
str(target.get('field_id') or '') == field_id
|
||||
for rule in (profile.definition_json or {}).get('column_rules', []) if isinstance(rule, dict)
|
||||
for target in rule.get('target_fields', []) if isinstance(target, dict)
|
||||
)
|
||||
for profile in ShippingOrderDocumentProfile.query.filter(
|
||||
ShippingOrderDocumentProfile.status.in_(['draft', 'published'])
|
||||
).all()
|
||||
)
|
||||
if order_profile_reference:
|
||||
references.append('order_document_profile')
|
||||
template_reference = any(
|
||||
any(
|
||||
item.get('source_kind') == 'order_field' and str(item.get('source_key') or '') == field_id
|
||||
@@ -968,6 +1005,19 @@ def save_draft(
|
||||
if field.value_type != 'enum' and enum_options:
|
||||
raise ValidationError('enum_options only applies to enum fields', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
business_purpose = _business_purpose(raw.get('business_purpose'), field=field)
|
||||
auto_create_key_field = raw.get('auto_create_key_field', False)
|
||||
if not isinstance(auto_create_key_field, bool):
|
||||
raise ValidationError('auto_create_key_field must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
raw_threshold = raw.get('minimum_confidence')
|
||||
if auto_create_key_field:
|
||||
try:
|
||||
minimum_confidence = float(raw_threshold)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('minimum_confidence is required for key field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') from exc
|
||||
if not 0 <= minimum_confidence <= 1:
|
||||
raise ValidationError('minimum_confidence must be between 0 and 1', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
else:
|
||||
minimum_confidence = None
|
||||
context_source = _context_source_snapshot(raw, field=field)
|
||||
dify_exposure_policy, available_for_customer_identity = _version_context_policy(
|
||||
raw, source=context_source,
|
||||
@@ -996,6 +1046,8 @@ def save_draft(
|
||||
'display_name': display_name,
|
||||
'description': str(raw.get('description') or '').strip() or None,
|
||||
'business_purpose': business_purpose,
|
||||
'auto_create_key_field': auto_create_key_field,
|
||||
'minimum_confidence': round(minimum_confidence, 2) if minimum_confidence is not None else None,
|
||||
'required': required,
|
||||
'aliases': aliases,
|
||||
'normalizer_key': normalizer,
|
||||
@@ -1011,7 +1063,11 @@ def save_draft(
|
||||
'available_for_customer_identity': available_for_customer_identity,
|
||||
'sequence': sequence,
|
||||
})
|
||||
after = {'schema_code': version.schema.schema_code, 'version': version.version, 'fields': normalized_fields}
|
||||
after = {
|
||||
'schema_code': version.schema.schema_code,
|
||||
'version': version.version,
|
||||
'fields': normalized_fields,
|
||||
}
|
||||
compile_table_header_contract(after)
|
||||
version.definition_json = after
|
||||
version.lock_version += 1
|
||||
|
||||
@@ -146,16 +146,27 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
||||
job_type=JobType.SHIPPING_NOTICE_PARSE,
|
||||
on_recovered=sync_intake_after_parse_job_recovery,
|
||||
)
|
||||
count = int(run_count) + int(parse_count)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import sync_layout_after_job_recovery
|
||||
|
||||
layout_count = recover_stale_jobs(
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
timeout_seconds=float(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS', 360,
|
||||
) or 360),
|
||||
job_type=JobType.SHIPPING_DOCUMENT_LAYOUT,
|
||||
on_recovered=sync_layout_after_job_recovery,
|
||||
)
|
||||
count = int(run_count) + int(parse_count) + int(layout_count)
|
||||
cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
|
||||
if cleanup_warnings:
|
||||
logger.warning('rpa callback cleanup warnings: %s', '; '.join(cleanup_warnings[:5]))
|
||||
if count:
|
||||
logger.warning(
|
||||
'recovered %s stale shipping_notice job(s) (run=%s parse=%s)',
|
||||
'recovered %s stale shipping_notice job(s) (run=%s parse=%s layout=%s)',
|
||||
count,
|
||||
run_count,
|
||||
parse_count,
|
||||
layout_count,
|
||||
)
|
||||
if cleanup_count:
|
||||
logger.info('processed %s rpa callback cleanup job(s)', cleanup_count)
|
||||
@@ -178,6 +189,7 @@ def claim_next_shipping_notice_job() -> Job | None:
|
||||
JobType.SHIPPING_NOTICE_RUN,
|
||||
JobType.SHIPPING_NOTICE_PARSE,
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
JobType.SHIPPING_DOCUMENT_LAYOUT,
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@@ -11,10 +11,8 @@ from __future__ import annotations
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
# 常见 Reservation ID:纯数字,如 1000140351(通常 8~12 位)
|
||||
RESERVATION_ID_NUMERIC_RE = re.compile(r"^\d{8,12}$")
|
||||
# 部分库存源使用带字母/连字符的业务单号,如 AWS-311、ORD-3002、R-1。
|
||||
RESERVATION_ID_BUSINESS_RE = re.compile(r"^[A-Z0-9][A-Z0-9._/-]{1,63}$", re.IGNORECASE)
|
||||
# Reservation ID 业务契约固定为 5 位或 10 位纯数字。
|
||||
RESERVATION_ID_NUMERIC_RE = re.compile(r"^(?:\d{5}|\d{10})$")
|
||||
# 数据库主键、哈希或 UUID 不属于业务 Reservation ID。
|
||||
INTERNAL_HEX_ID_RE = re.compile(r"^[0-9a-f]{32}$", re.IGNORECASE)
|
||||
INTERNAL_UUID_RE = re.compile(
|
||||
@@ -22,7 +20,7 @@ INTERNAL_UUID_RE = re.compile(
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# Wistron 等 PO:PR Number = ADU_S-ENCWIW260528126265@1000140351
|
||||
RESERVATION_AT_SUFFIX_RE = re.compile(r"@(\d{8,12})\b")
|
||||
RESERVATION_AT_SUFFIX_RE = re.compile(r"@(\d{10}|\d{5})\b")
|
||||
PR_NUMBER_LINE_RE = re.compile(
|
||||
r"PR\s*Number\s*[::]?\s*([^\n\r]+)",
|
||||
re.IGNORECASE,
|
||||
@@ -101,7 +99,7 @@ def find_reservation_id_in_document(text: str) -> str:
|
||||
|
||||
|
||||
def looks_like_reservation_id(value: Any) -> bool:
|
||||
"""判断标准化后的值是否符合 8~12 位纯数字 Reservation ID 格式。"""
|
||||
"""判断标准化后的值是否符合 5 位或 10 位纯数字 Reservation ID 格式。"""
|
||||
text = normalize_reservation_id(value)
|
||||
return bool(text and RESERVATION_ID_NUMERIC_RE.fullmatch(text))
|
||||
|
||||
@@ -110,10 +108,10 @@ def is_valid_reservation_id(value: Any, *, numeric_only: bool = False) -> bool:
|
||||
"""
|
||||
判断候选值是否可作为业务 Reservation ID。
|
||||
|
||||
核心逻辑:默认兼容数字型与现有字母型业务单号,但明确拒绝 32 位 hex、UUID、纯字母等内部或弱语义值。
|
||||
核心逻辑:只接受 5 位或 10 位纯数字;字母型编号、其他长度数字、hex 和 UUID 均拒绝。
|
||||
Args:
|
||||
value: 待校验的原始值。
|
||||
numeric_only: 为 True 时仅接受 8~12 位纯数字,用于明确的 External Reservation 模板。
|
||||
numeric_only: 兼容既有调用签名;当前统一契约始终只接受 5 位或 10 位纯数字。
|
||||
|
||||
Returns:
|
||||
bool: 值是否满足当前 Reservation ID 契约。
|
||||
@@ -121,15 +119,7 @@ def is_valid_reservation_id(value: Any, *, numeric_only: bool = False) -> bool:
|
||||
text = extract_reservation_id(value)
|
||||
if not text or INTERNAL_HEX_ID_RE.fullmatch(text) or INTERNAL_UUID_RE.fullmatch(text):
|
||||
return False
|
||||
if RESERVATION_ID_NUMERIC_RE.fullmatch(text):
|
||||
return True
|
||||
if numeric_only:
|
||||
return False
|
||||
return bool(
|
||||
RESERVATION_ID_BUSINESS_RE.fullmatch(text)
|
||||
and re.search(r"[A-Z]", text, re.IGNORECASE)
|
||||
and re.search(r"\d", text)
|
||||
)
|
||||
return bool(RESERVATION_ID_NUMERIC_RE.fullmatch(text))
|
||||
|
||||
|
||||
def validated_reservation_id(value: Any, *, numeric_only: bool = False) -> str:
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Add versioned shipping order document profiles.
|
||||
|
||||
Revision ID: a68f8091a2b4
|
||||
Revises: a67f8091a2b3
|
||||
Create Date: 2026-07-21 23:40:00.000000
|
||||
|
||||
用途:持久化订单模板结构指纹、固定列规则、Schema 绑定和发布生命周期。
|
||||
依赖:shipping_order_schema_versions、users。
|
||||
逻辑:同一 profile_code 版本递增且只能有一个 published;Run 使用完整 JSON 快照而不是依赖可变当前行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a68f8091a2b4'
|
||||
down_revision = 'a67f8091a2b3'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建订单文档 Profile 版本表及发布唯一门禁。"""
|
||||
op.add_column(
|
||||
'shipping_notice_documents',
|
||||
sa.Column('layout_snapshot_json', sa.JSON(), nullable=True),
|
||||
)
|
||||
op.create_table(
|
||||
'shipping_order_document_profiles',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('profile_code', sa.String(length=64), nullable=False),
|
||||
sa.Column('display_name', sa.String(length=128), nullable=False),
|
||||
sa.Column('version', sa.Integer(), nullable=False),
|
||||
sa.Column('status', sa.String(length=16), server_default='draft', nullable=False),
|
||||
sa.Column('schema_version_id', sa.Integer(), nullable=False),
|
||||
sa.Column('structure_fingerprint', sa.String(length=64), nullable=False),
|
||||
sa.Column('definition_json', sa.JSON(), nullable=False),
|
||||
sa.Column('checksum', sa.String(length=64), nullable=True),
|
||||
sa.Column('lock_version', sa.Integer(), server_default='1', nullable=False),
|
||||
sa.Column('change_note', sa.Text(), nullable=True),
|
||||
sa.Column('source_profile_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('published_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('published_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('retired_at', sa.DateTime(), nullable=True),
|
||||
sa.CheckConstraint(
|
||||
"status IN ('draft', 'published', 'retired')",
|
||||
name='ck_shipping_order_document_profiles_status',
|
||||
),
|
||||
sa.ForeignKeyConstraint(['created_by_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['published_by_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['schema_version_id'], ['shipping_order_schema_versions.id']),
|
||||
sa.ForeignKeyConstraint(['source_profile_id'], ['shipping_order_document_profiles.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint(
|
||||
'profile_code', 'version', name='uq_shipping_order_document_profiles_code_version',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_document_profiles_schema_status',
|
||||
'shipping_order_document_profiles', ['schema_version_id', 'status'], unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_document_profiles_fingerprint',
|
||||
'shipping_order_document_profiles', ['structure_fingerprint'], unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
'uq_shipping_order_document_profiles_one_published',
|
||||
'shipping_order_document_profiles', ['profile_code'], unique=True,
|
||||
postgresql_where=sa.text("status = 'published'"),
|
||||
sqlite_where=sa.text("status = 'published'"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除订单文档 Profile 表。"""
|
||||
op.drop_index(
|
||||
'uq_shipping_order_document_profiles_one_published',
|
||||
table_name='shipping_order_document_profiles',
|
||||
)
|
||||
op.drop_index(
|
||||
'ix_shipping_order_document_profiles_fingerprint',
|
||||
table_name='shipping_order_document_profiles',
|
||||
)
|
||||
op.drop_index(
|
||||
'ix_shipping_order_document_profiles_schema_status',
|
||||
table_name='shipping_order_document_profiles',
|
||||
)
|
||||
op.drop_table('shipping_order_document_profiles')
|
||||
op.drop_column('shipping_notice_documents', 'layout_snapshot_json')
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Add versioned shipping document layout lifecycle.
|
||||
|
||||
Revision ID: a69f8091a2b5
|
||||
Revises: a68f8091a2b4
|
||||
Create Date: 2026-07-22 02:20:00.000000
|
||||
|
||||
用途:将 Document 单 JSON 布局快照迁移为版本化状态、checksum、质量结果和 Worker 租约。
|
||||
依赖:shipping_notice_documents、jobs。
|
||||
逻辑:旧快照回填为 version=1/current;downgrade 恢复当前 payload,再移除生命周期表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a69f8091a2b5'
|
||||
down_revision = 'a68f8091a2b4'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _encoded_payload(value) -> tuple[str, int]:
|
||||
"""返回旧 JSON 快照的稳定 checksum 和 UTF-8 字节数。"""
|
||||
encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
return hashlib.sha256(encoded).hexdigest(), len(encoded)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建布局版本表、回填旧快照并切换 Document 当前版本外键。"""
|
||||
op.create_index(
|
||||
'uq_jobs_shipping_document_layout_active_ref', 'jobs',
|
||||
['domain', 'job_type', 'business_ref'], unique=True,
|
||||
postgresql_where=sa.text(
|
||||
"job_type = 'shipping_document_layout' AND status IN ('queued', 'running') "
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
sqlite_where=sa.text(
|
||||
"job_type = 'shipping_document_layout' AND status IN ('queued', 'running') "
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
)
|
||||
op.create_table(
|
||||
'shipping_document_layout_versions',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('version', sa.Integer(), nullable=False),
|
||||
sa.Column('status', sa.String(length=24), server_default='queued', nullable=False),
|
||||
sa.Column('source_content_hash', sa.String(length=64), nullable=False),
|
||||
sa.Column('parser_key', sa.String(length=128), nullable=False),
|
||||
sa.Column('parser_name', sa.String(length=32), nullable=False),
|
||||
sa.Column('parser_version', sa.String(length=64), nullable=True),
|
||||
sa.Column('backend', sa.String(length=32), nullable=True),
|
||||
sa.Column('contract_version', sa.String(length=64), nullable=False),
|
||||
sa.Column('payload_json', sa.JSON(), nullable=True),
|
||||
sa.Column('payload_checksum', sa.String(length=64), nullable=True),
|
||||
sa.Column('payload_size_bytes', sa.Integer(), server_default='0', nullable=False),
|
||||
sa.Column('quality_json', sa.JSON(), nullable=True),
|
||||
sa.Column('issues_json', sa.JSON(), nullable=False),
|
||||
sa.Column('job_id', sa.Integer(), nullable=True),
|
||||
sa.Column('lease_token', sa.String(length=64), nullable=True),
|
||||
sa.Column('attempt_count', sa.Integer(), server_default='0', nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('started_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('finished_at', sa.DateTime(), nullable=True),
|
||||
sa.CheckConstraint(
|
||||
"status IN ('queued', 'running', 'ready', 'needs_review', 'failed', 'unsupported')",
|
||||
name='ck_shipping_document_layout_status',
|
||||
),
|
||||
sa.ForeignKeyConstraint(['document_id'], ['shipping_notice_documents.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['job_id'], ['jobs.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('document_id', 'version', name='uq_shipping_document_layout_document_version'),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_document_layout_document_status', 'shipping_document_layout_versions',
|
||||
['document_id', 'status'], unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_document_layout_content_parser', 'shipping_document_layout_versions',
|
||||
['source_content_hash', 'parser_key'], unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_document_layout_versions_job_id', 'shipping_document_layout_versions',
|
||||
['job_id'], unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
'uq_shipping_document_layout_one_active', 'shipping_document_layout_versions',
|
||||
['document_id'], unique=True,
|
||||
postgresql_where=sa.text("status IN ('queued', 'running')"),
|
||||
sqlite_where=sa.text("status IN ('queued', 'running')"),
|
||||
)
|
||||
with op.batch_alter_table('shipping_notice_documents') as batch:
|
||||
batch.add_column(sa.Column('current_layout_version_id', sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_notice_documents_current_layout_version',
|
||||
'shipping_document_layout_versions', ['current_layout_version_id'], ['id'],
|
||||
ondelete='SET NULL',
|
||||
)
|
||||
|
||||
bind = op.get_bind()
|
||||
documents = sa.table(
|
||||
'shipping_notice_documents',
|
||||
sa.column('id', sa.Integer()),
|
||||
sa.column('content_hash', sa.String()),
|
||||
sa.column('layout_snapshot_json', sa.JSON()),
|
||||
sa.column('current_layout_version_id', sa.Integer()),
|
||||
)
|
||||
versions = sa.table(
|
||||
'shipping_document_layout_versions',
|
||||
sa.column('id', sa.Integer()), sa.column('document_id', sa.Integer()),
|
||||
sa.column('version', sa.Integer()), sa.column('status', sa.String()),
|
||||
sa.column('source_content_hash', sa.String()), sa.column('parser_key', sa.String()),
|
||||
sa.column('parser_name', sa.String()), sa.column('parser_version', sa.String()),
|
||||
sa.column('backend', sa.String()), sa.column('contract_version', sa.String()),
|
||||
sa.column('payload_json', sa.JSON()), sa.column('payload_checksum', sa.String()),
|
||||
sa.column('payload_size_bytes', sa.Integer()), sa.column('quality_json', sa.JSON()),
|
||||
sa.column('issues_json', sa.JSON()), sa.column('attempt_count', sa.Integer()),
|
||||
sa.column('created_at', sa.DateTime()), sa.column('updated_at', sa.DateTime()),
|
||||
sa.column('finished_at', sa.DateTime()),
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
rows = bind.execute(sa.select(
|
||||
documents.c.id, documents.c.content_hash, documents.c.layout_snapshot_json,
|
||||
).where(documents.c.layout_snapshot_json.is_not(None))).mappings().all()
|
||||
for row in rows:
|
||||
payload = row['layout_snapshot_json'] if isinstance(row['layout_snapshot_json'], dict) else {}
|
||||
checksum, size = _encoded_payload(payload)
|
||||
status = str(payload.get('status') or 'failed')
|
||||
if status not in {'ready', 'failed', 'unsupported'}:
|
||||
status = 'failed'
|
||||
bind.execute(versions.insert().values(
|
||||
document_id=row['id'], version=1, status=status,
|
||||
source_content_hash=str(row['content_hash'] or checksum)[:64].ljust(64, '0'),
|
||||
# 旧单列快照没有可验证的 parser revision,必须显式隔离以触发新生命周期重解析。
|
||||
parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:legacy',
|
||||
parser_name=str(payload.get('provider') or 'mineru')[:32],
|
||||
parser_version=str(payload.get('provider_version') or '')[:64] or None,
|
||||
backend=str(payload.get('backend') or 'pipeline')[:32],
|
||||
contract_version=str(payload.get('snapshot_version') or 'shipping_document_table_snapshot.v1')[:64],
|
||||
payload_json=payload, payload_checksum=checksum, payload_size_bytes=size,
|
||||
quality_json=payload.get('capability') if isinstance(payload.get('capability'), dict) else None,
|
||||
issues_json=list(payload.get('issues') or []), attempt_count=1,
|
||||
created_at=now, updated_at=now, finished_at=now,
|
||||
))
|
||||
version_id = bind.execute(sa.select(versions.c.id).where(
|
||||
versions.c.document_id == row['id'], versions.c.version == 1,
|
||||
)).scalar_one()
|
||||
bind.execute(documents.update().where(documents.c.id == row['id']).values(
|
||||
current_layout_version_id=version_id,
|
||||
))
|
||||
with op.batch_alter_table('shipping_notice_documents') as batch:
|
||||
batch.drop_column('layout_snapshot_json')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复 Document 当前 JSON 快照并移除版本化布局生命周期。"""
|
||||
with op.batch_alter_table('shipping_notice_documents') as batch:
|
||||
batch.add_column(sa.Column('layout_snapshot_json', sa.JSON(), nullable=True))
|
||||
bind = op.get_bind()
|
||||
bind.execute(sa.text(
|
||||
'UPDATE shipping_notice_documents '
|
||||
'SET layout_snapshot_json = ('
|
||||
'SELECT payload_json FROM shipping_document_layout_versions '
|
||||
'WHERE shipping_document_layout_versions.id = shipping_notice_documents.current_layout_version_id'
|
||||
') WHERE current_layout_version_id IS NOT NULL'
|
||||
))
|
||||
with op.batch_alter_table('shipping_notice_documents') as batch:
|
||||
batch.drop_constraint('fk_shipping_notice_documents_current_layout_version', type_='foreignkey')
|
||||
batch.drop_column('current_layout_version_id')
|
||||
op.drop_index('uq_shipping_document_layout_one_active', table_name='shipping_document_layout_versions')
|
||||
op.drop_index('ix_shipping_document_layout_versions_job_id', table_name='shipping_document_layout_versions')
|
||||
op.drop_index('ix_shipping_document_layout_content_parser', table_name='shipping_document_layout_versions')
|
||||
op.drop_index('ix_shipping_document_layout_document_status', table_name='shipping_document_layout_versions')
|
||||
op.drop_table('shipping_document_layout_versions')
|
||||
op.drop_index('uq_jobs_shipping_document_layout_active_ref', table_name='jobs')
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Add traceable layout evidence to order observations.
|
||||
|
||||
Revision ID: a70f8091a2b6
|
||||
Revises: a69f8091a2b5
|
||||
Create Date: 2026-07-22 08:30:00.000000
|
||||
|
||||
用途:为动态订单 Observation 保存稳定 evidence_ref 与脱敏版面定位元数据。
|
||||
依赖:shipping_order_field_observations、L4 冻结 layout schema candidates。
|
||||
逻辑:upgrade 仅新增可空审计列;downgrade 完整移除,不改写历史业务值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a70f8091a2b6'
|
||||
down_revision = 'a69f8091a2b5'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""新增稳定证据引用与结构化版面定位列。"""
|
||||
with op.batch_alter_table('shipping_order_field_observations') as batch:
|
||||
batch.add_column(sa.Column('evidence_ref', sa.String(length=512), nullable=True))
|
||||
batch.add_column(sa.Column('evidence_metadata_json', sa.JSON(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除 L6 版面证据列,保留既有 Observation 值和文本 quote。"""
|
||||
with op.batch_alter_table('shipping_order_field_observations') as batch:
|
||||
batch.drop_column('evidence_metadata_json')
|
||||
batch.drop_column('evidence_ref')
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Add L7 order extraction quality gate.
|
||||
|
||||
Revision ID: a71f8091a2b7
|
||||
Revises: a70f8091a2b6
|
||||
Create Date: 2026-07-22 11:10:00.000000
|
||||
|
||||
用途:新增订单抽取影子验收批次/双人标签,并允许 Runtime Binding 引用批准批次。
|
||||
依赖:agents、users、shipping_order_schema_versions、shipping_order_extraction_runs、agent_runtime_bindings。
|
||||
逻辑:质量事实独立持久化;绑定只保存批准批次外键,downgrade 先移除引用再删除质量表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a71f8091a2b7'
|
||||
down_revision = 'a70f8091a2b6'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建 L7 质量批次/标签并增加 Runtime Binding 批准批次引用。"""
|
||||
op.create_table(
|
||||
'shipping_order_extraction_quality_batches',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('batch_no', sa.String(64), nullable=False),
|
||||
sa.Column('owner_agent_id', sa.Integer(), sa.ForeignKey('agents.id'), nullable=False),
|
||||
sa.Column('schema_version_id', sa.Integer(), sa.ForeignKey('shipping_order_schema_versions.id'), nullable=False),
|
||||
sa.Column('contract_version', sa.String(64), nullable=False, server_default='unit_v3'),
|
||||
sa.Column('threshold_version', sa.String(32), nullable=False, server_default='l7.v1'),
|
||||
sa.Column('status', sa.String(32), nullable=False, server_default='collecting'),
|
||||
sa.Column('created_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False),
|
||||
sa.Column('business_approved_by_id', sa.Integer(), sa.ForeignKey('users.id')),
|
||||
sa.Column('business_approved_at', sa.DateTime()),
|
||||
sa.Column('technical_approved_by_id', sa.Integer(), sa.ForeignKey('users.id')),
|
||||
sa.Column('technical_approved_at', sa.DateTime()),
|
||||
sa.Column('approved_at', sa.DateTime()),
|
||||
sa.Column('rejected_by_id', sa.Integer(), sa.ForeignKey('users.id')),
|
||||
sa.Column('rejected_at', sa.DateTime()),
|
||||
sa.Column('rejection_reason', sa.Text()),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint("status IN ('collecting', 'ready', 'approved', 'rejected')", name='ck_shipping_order_extraction_quality_batches_status'),
|
||||
sa.UniqueConstraint('batch_no', name='uq_shipping_order_extraction_quality_batches_no'),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_extraction_quality_batches_owner_created',
|
||||
'shipping_order_extraction_quality_batches', ['owner_agent_id', 'created_at'],
|
||||
)
|
||||
op.create_table(
|
||||
'shipping_order_extraction_quality_labels',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('batch_id', sa.Integer(), sa.ForeignKey('shipping_order_extraction_quality_batches.id', ondelete='CASCADE'), nullable=False),
|
||||
sa.Column('run_id', sa.Integer(), sa.ForeignKey('shipping_order_extraction_runs.id'), nullable=False),
|
||||
sa.Column('reviewer_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False),
|
||||
sa.Column('core_expected_count', sa.Integer(), nullable=False),
|
||||
sa.Column('core_extracted_count', sa.Integer(), nullable=False),
|
||||
sa.Column('core_correct_count', sa.Integer(), nullable=False),
|
||||
sa.Column('wrong_merge', sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column('wrong_split', sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column('wrong_auto_create', sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint('core_expected_count >= 0', name='ck_shipping_order_quality_expected_nonnegative'),
|
||||
sa.CheckConstraint('core_extracted_count >= 0', name='ck_shipping_order_quality_extracted_nonnegative'),
|
||||
sa.CheckConstraint('core_correct_count >= 0', name='ck_shipping_order_quality_correct_nonnegative'),
|
||||
sa.UniqueConstraint('batch_id', 'run_id', 'reviewer_id', name='uq_shipping_order_quality_label_reviewer'),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_quality_labels_batch_run',
|
||||
'shipping_order_extraction_quality_labels', ['batch_id', 'run_id'],
|
||||
)
|
||||
with op.batch_alter_table('agent_runtime_bindings') as batch:
|
||||
batch.add_column(sa.Column('quality_batch_id', sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_agent_runtime_bindings_quality_batch',
|
||||
'shipping_order_extraction_quality_batches', ['quality_batch_id'], ['id'],
|
||||
)
|
||||
batch.create_index('ix_agent_runtime_bindings_quality_batch', ['quality_batch_id'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除 Runtime Binding 引用及 L7 质量事实表。"""
|
||||
with op.batch_alter_table('agent_runtime_bindings') as batch:
|
||||
batch.drop_index('ix_agent_runtime_bindings_quality_batch')
|
||||
batch.drop_constraint('fk_agent_runtime_bindings_quality_batch', type_='foreignkey')
|
||||
batch.drop_column('quality_batch_id')
|
||||
op.drop_index('ix_shipping_order_quality_labels_batch_run', table_name='shipping_order_extraction_quality_labels')
|
||||
op.drop_table('shipping_order_extraction_quality_labels')
|
||||
op.drop_index(
|
||||
'ix_shipping_order_extraction_quality_batches_owner_created',
|
||||
table_name='shipping_order_extraction_quality_batches',
|
||||
)
|
||||
op.drop_table('shipping_order_extraction_quality_batches')
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
"""Freeze quality batch on order extraction runs.
|
||||
|
||||
Revision ID: a72f8091a2b8
|
||||
Revises: a71f8091a2b7
|
||||
Create Date: 2026-07-22 11:45:00.000000
|
||||
|
||||
用途:在订单抽取 Run 上冻结自动建单质量批次,保证配置批准事实与实际执行可追溯。
|
||||
依赖:shipping_order_extraction_runs、shipping_order_extraction_quality_batches。
|
||||
逻辑:Run 创建时复制 Runtime Binding 的质量批次外键;降级只移除 Run 引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a72f8091a2b8'
|
||||
down_revision = 'a71f8091a2b7'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为订单抽取 Run 增加可空质量批次外键及索引。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch:
|
||||
batch.add_column(sa.Column('quality_batch_id', sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_order_extraction_runs_quality_batch',
|
||||
'shipping_order_extraction_quality_batches', ['quality_batch_id'], ['id'],
|
||||
)
|
||||
batch.create_index('ix_shipping_order_extraction_runs_quality_batch', ['quality_batch_id'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除订单抽取 Run 的质量批次引用。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch:
|
||||
batch.drop_index('ix_shipping_order_extraction_runs_quality_batch')
|
||||
batch.drop_constraint('fk_shipping_order_extraction_runs_quality_batch', type_='foreignkey')
|
||||
batch.drop_column('quality_batch_id')
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Remove selectable order extraction protocol versions.
|
||||
|
||||
Revision ID: a73f8091a2b9
|
||||
Revises: a72f8091a2b8
|
||||
Create Date: 2026-07-22 09:30:00.000000
|
||||
|
||||
用途:订单抽取只保留唯一 execution_manifest 结构,清理运行配置和质量批次中的协议版本分支。
|
||||
依赖:agent_runtime_bindings、shipping_order_extraction_runs、shipping_order_extraction_quality_batches。
|
||||
逻辑:移除旧 JSON 配置键和质量批次列;旧 Run 保留审计事实但不能按旧协议重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a73f8091a2b9'
|
||||
down_revision = 'a72f8091a2b8'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
_RETIRED_BINDING_KEYS = ('workflow_contract_version', 'unit_concurrency', 'unit_max_attempts', 'unit_retry_backoff_ms', 'max_model_units', 'provider_max_concurrency', 'circuit_failure_threshold', 'circuit_cooldown_seconds', 'auto_create_enabled')
|
||||
|
||||
|
||||
def _remove_json_key(table: str, column: str, *, mark_retired_runs: bool = False) -> None:
|
||||
"""按数据库方言清理已迁移配置键;旧 Run 标记为不可按旧快照重试。
|
||||
|
||||
核心逻辑:Postgres 的 `json` 列不支持 `?|` / `-`,先转 jsonb 再写回 json。
|
||||
"""
|
||||
dialect = op.get_bind().dialect.name
|
||||
if dialect == 'postgresql':
|
||||
# [STEP] SQLAlchemy JSON 在 Postgres 默认为 json;操作符仅 jsonb 可用。
|
||||
keys = ' - '.join(f"'{key}'" for key in _RETIRED_BINDING_KEYS)
|
||||
replacement = f"(({column}::jsonb - {keys})"
|
||||
if mark_retired_runs:
|
||||
replacement = f"{replacement} || jsonb_build_object('retired_protocol', true)"
|
||||
replacement = f"{replacement})::json"
|
||||
op.execute(sa.text(
|
||||
f"UPDATE {table} SET {column} = {replacement} "
|
||||
f"WHERE {column}::jsonb ?| ARRAY[{','.join(repr(key) for key in _RETIRED_BINDING_KEYS)}]"
|
||||
))
|
||||
elif dialect == 'sqlite':
|
||||
paths = ', '.join(repr(f'$.{key}') for key in _RETIRED_BINDING_KEYS)
|
||||
replacement = (
|
||||
f"json_set(json_remove({column}, {paths}), '$.retired_protocol', json('true'))"
|
||||
if mark_retired_runs else f"json_remove({column}, {paths})"
|
||||
)
|
||||
op.execute(sa.text(
|
||||
f"UPDATE {table} SET {column} = {replacement} "
|
||||
f"WHERE {' OR '.join(f"json_type({column}, '$.{key}') IS NOT NULL" for key in _RETIRED_BINDING_KEYS)}"
|
||||
))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""清理版本开关并删除质量批次的协议版本列。"""
|
||||
_remove_json_key('agent_runtime_bindings', 'config_json')
|
||||
_remove_json_key('shipping_order_extraction_runs', 'provider_config_json', mark_retired_runs=True)
|
||||
with op.batch_alter_table('shipping_order_extraction_quality_batches') as batch:
|
||||
batch.drop_column('contract_version')
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""仅恢复质量批次字段;不恢复已删除的多协议运行配置。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_quality_batches') as batch:
|
||||
batch.add_column(sa.Column('contract_version', sa.String(64), nullable=False, server_default='legacy'))
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Remove automatic-creation quality-batch coupling.
|
||||
|
||||
Revision ID: a74f8091a2ba
|
||||
Revises: a73f8091a2b9
|
||||
Create Date: 2026-07-22 11:20:00.000000
|
||||
|
||||
用途:自动建单策略改由订单字段模板的运行配置管理,移除应用能力绑定和 Run 的质量批次外键。
|
||||
依赖:agent_runtime_bindings、shipping_order_extraction_runs。
|
||||
逻辑:质量批次及其标签保留用于独立质量分析,不再是自动建单的配置来源或运行门禁。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'a74f8091a2ba'
|
||||
down_revision = 'a73f8091a2b9'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""删除已废弃的质量批次外键,并增加字段模板的自动建单总开关配置。"""
|
||||
with op.batch_alter_table('agent_runtime_bindings') as batch:
|
||||
batch.drop_column('quality_batch_id')
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch:
|
||||
batch.drop_column('quality_batch_id')
|
||||
with op.batch_alter_table('shipping_order_schemas') as batch:
|
||||
batch.add_column(sa.Column('auto_creation_policy_json', sa.JSON(), nullable=False, server_default='{}'))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复列结构;不会恢复已移除的历史绑定关系。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch:
|
||||
batch.add_column(sa.Column('quality_batch_id', sa.Integer(), nullable=True))
|
||||
with op.batch_alter_table('agent_runtime_bindings') as batch:
|
||||
batch.add_column(sa.Column('quality_batch_id', sa.Integer(), nullable=True))
|
||||
with op.batch_alter_table('shipping_order_schemas') as batch:
|
||||
batch.drop_column('auto_creation_policy_json')
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Add immutable reparse lineage and versioned extraction candidates.
|
||||
|
||||
Revision ID: a74f8091a2c0
|
||||
Revises: a73f8091a2b9
|
||||
Create Date: 2026-07-22 12:10:00.000000
|
||||
|
||||
用途:为订单重新识别保留来源/后继 Run 审计链,并让候选按 Run 版本保存。
|
||||
依赖:shipping_order_extraction_runs、shipping_notice_candidates。
|
||||
逻辑:旧候选初始保持 current;新 Run 成功写入候选后由服务层撤销旧版本的可消费资格。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'a74f8091a2c0'
|
||||
down_revision = 'a73f8091a2b9'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""增加 Run 谱系字段,并把 Candidate 唯一键收敛至同一 Run 版本。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch:
|
||||
batch.add_column(sa.Column('reparse_of_run_id', sa.Integer(), nullable=True))
|
||||
batch.add_column(sa.Column('superseded_by_run_id', sa.Integer(), nullable=True))
|
||||
batch.add_column(sa.Column('reparse_reason', sa.String(length=64), nullable=True))
|
||||
batch.add_column(sa.Column('reparse_comment', sa.Text(), nullable=True))
|
||||
batch.add_column(sa.Column('superseded_at', sa.DateTime(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_order_extraction_runs_reparse_source',
|
||||
'shipping_order_extraction_runs', ['reparse_of_run_id'], ['id'],
|
||||
)
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_order_extraction_runs_superseding_run',
|
||||
'shipping_order_extraction_runs', ['superseded_by_run_id'], ['id'],
|
||||
)
|
||||
batch.create_index('ix_shipping_order_extraction_runs_reparse_of', ['reparse_of_run_id'])
|
||||
batch.create_index('ix_shipping_order_extraction_runs_superseded_by', ['superseded_by_run_id'])
|
||||
with op.batch_alter_table('shipping_notice_candidates') as batch:
|
||||
batch.drop_constraint('uq_shipping_notice_candidates_intake_key', type_='unique')
|
||||
batch.add_column(sa.Column('is_current_version', sa.Boolean(), nullable=False, server_default=sa.text('true')))
|
||||
batch.add_column(sa.Column('selected_before_superseded', sa.Boolean(), nullable=True))
|
||||
batch.create_unique_constraint(
|
||||
'uq_shipping_notice_candidates_intake_key_run',
|
||||
['intake_id', 'candidate_key', 'order_extraction_run_id'],
|
||||
)
|
||||
batch.create_index('ix_shipping_notice_candidates_current_version', ['is_current_version'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除重新识别谱系;仅用于未包含版本化候选的开发环境回退。"""
|
||||
with op.batch_alter_table('shipping_notice_candidates') as batch:
|
||||
batch.drop_index('ix_shipping_notice_candidates_current_version')
|
||||
batch.drop_constraint('uq_shipping_notice_candidates_intake_key_run', type_='unique')
|
||||
batch.drop_column('selected_before_superseded')
|
||||
batch.drop_column('is_current_version')
|
||||
batch.create_unique_constraint('uq_shipping_notice_candidates_intake_key', ['intake_id', 'candidate_key'])
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch:
|
||||
batch.drop_index('ix_shipping_order_extraction_runs_superseded_by')
|
||||
batch.drop_index('ix_shipping_order_extraction_runs_reparse_of')
|
||||
batch.drop_constraint('fk_shipping_order_extraction_runs_superseding_run', type_='foreignkey')
|
||||
batch.drop_constraint('fk_shipping_order_extraction_runs_reparse_source', type_='foreignkey')
|
||||
batch.drop_column('superseded_at')
|
||||
batch.drop_column('reparse_comment')
|
||||
batch.drop_column('reparse_reason')
|
||||
batch.drop_column('superseded_by_run_id')
|
||||
batch.drop_column('reparse_of_run_id')
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Merge quality-binding removal and reparse lineage heads.
|
||||
|
||||
Revision ID: a75f8091a2c1
|
||||
Revises: a74f8091a2ba, a74f8091a2c0
|
||||
Create Date: 2026-07-22 10:31:00.000000
|
||||
|
||||
用途:合并两条并行 head,恢复单一 Alembic 升级路径。
|
||||
依赖:a74f8091a2ba(移除质量批次外键)、a74f8091a2c0(重新识别谱系)。
|
||||
逻辑:纯合并节点,不改表结构;upgrade/downgrade 为空。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
revision = 'a75f8091a2c1'
|
||||
down_revision = ('a74f8091a2ba', 'a74f8091a2c0')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""合并节点无 DDL。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""合并节点无 DDL。"""
|
||||
pass
|
||||
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
backend/migrations/versions/a76f8091a2c2_repair_order_schema_auto_creation_policy.py
|
||||
|
||||
用途:修复 Alembic 已到 head、但订单 Schema 缺少自动建单策略列的结构漂移。
|
||||
依赖:Alembic Operations、SQLAlchemy Inspector、a75f8091a2c1 merge head。
|
||||
逻辑:升级仅在实际列缺失时补列;已正确执行旧迁移的环境保持幂等,降级仅移除该列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'a76f8091a2c2'
|
||||
down_revision = 'a75f8091a2c1'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _column_exists(table_name: str, column_name: str) -> bool:
|
||||
"""
|
||||
查询迁移连接中的实际列,避免结构已正确的环境重复执行 DDL。
|
||||
|
||||
Args:
|
||||
table_name: 当前数据库中的目标表名。
|
||||
column_name: 需要确认的目标列名。
|
||||
|
||||
Returns:
|
||||
bool: 目标列是否已存在。
|
||||
"""
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
return column_name in {item['name'] for item in inspector.get_columns(table_name)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""缺列时补充自动建单策略 JSON;已有列的环境仅推进 Alembic 版本。"""
|
||||
if _column_exists('shipping_order_schemas', 'auto_creation_policy_json'):
|
||||
return
|
||||
with op.batch_alter_table('shipping_order_schemas') as batch:
|
||||
batch.add_column(sa.Column(
|
||||
'auto_creation_policy_json', sa.JSON(), nullable=False, server_default='{}',
|
||||
))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""存在时移除自动建单策略列,使本增量迁移可安全往返。"""
|
||||
if not _column_exists('shipping_order_schemas', 'auto_creation_policy_json'):
|
||||
return
|
||||
with op.batch_alter_table('shipping_order_schemas') as batch:
|
||||
batch.drop_column('auto_creation_policy_json')
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
用途:为订单抽取运行绑定和 Run 冻结 L7 已批准质量批次。
|
||||
依赖:agent_runtime_bindings、shipping_order_extraction_runs、质量批次表。
|
||||
逻辑:自动建单只能引用可审计质量批次;历史手动或复核 Run 保持空值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'a77f8091a2c3'
|
||||
down_revision = 'a76f8091a2c2'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _column_exists(table_name: str, column_name: str) -> bool:
|
||||
"""检查列是否已存在,使修复性迁移可重复执行。"""
|
||||
return column_name in {item['name'] for item in sa.inspect(op.get_bind()).get_columns(table_name)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为绑定和 Run 增加可空质量批次外键,兼容既有非自动建单记录。"""
|
||||
for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'):
|
||||
if _column_exists(table_name, 'quality_batch_id'):
|
||||
continue
|
||||
with op.batch_alter_table(table_name) as batch:
|
||||
batch.add_column(sa.Column('quality_batch_id', sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
f'fk_{table_name}_quality_batch',
|
||||
'shipping_order_extraction_quality_batches', ['quality_batch_id'], ['id'],
|
||||
)
|
||||
batch.create_index(f'ix_{table_name}_quality_batch_id', ['quality_batch_id'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除质量批次外键和列,恢复上一版本模型结构。"""
|
||||
for table_name in ('shipping_order_extraction_runs', 'agent_runtime_bindings'):
|
||||
if not _column_exists(table_name, 'quality_batch_id'):
|
||||
continue
|
||||
with op.batch_alter_table(table_name) as batch:
|
||||
batch.drop_index(f'ix_{table_name}_quality_batch_id')
|
||||
batch.drop_constraint(f'fk_{table_name}_quality_batch', type_='foreignkey')
|
||||
batch.drop_column('quality_batch_id')
|
||||
@@ -0,0 +1,291 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
backend/scripts/build_shipping_layout_truth_workbench.py
|
||||
|
||||
用途:从受控 EML 样本生成仓库外的离线 PDF cell 真值标注工作台,并校验导出结果。
|
||||
依赖:MinerU adapter、pypdfium2、Pillow、OpenCV 候选和 layout annotation 契约。
|
||||
逻辑:附件仅在内存中解析;页面图、候选文本和人工 JSON 只写显式仓库外目录,控制台只输出哈希与计数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import sys
|
||||
from email import policy
|
||||
from email.parser import BytesParser
|
||||
from hashlib import sha256
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pypdfium2 as pdfium
|
||||
from PIL import Image
|
||||
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
REPOSITORY_ROOT = BACKEND_ROOT.parent
|
||||
if str(BACKEND_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(BACKEND_ROOT))
|
||||
|
||||
from app.services.shipping_notice.document_layout.evaluation import LayoutAnnotation
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.mineru import (
|
||||
MinerUClient,
|
||||
MinerUClientConfig,
|
||||
parse_mineru_candidate,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.opencv_table import (
|
||||
reconstruct_opencv_table_geometry,
|
||||
validate_opencv_cell_text,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import (
|
||||
align_html_cells_from_positioned_text,
|
||||
)
|
||||
|
||||
|
||||
def _external_output_path(raw: str | Path) -> Path:
|
||||
"""解析并验证输出目录必须位于 Git 仓库外,避免真实样本被误提交。"""
|
||||
path = Path(raw).expanduser().resolve()
|
||||
try:
|
||||
path.relative_to(REPOSITORY_ROOT.resolve())
|
||||
except ValueError:
|
||||
return path
|
||||
raise ValueError('layout truth workbench output must be outside the repository')
|
||||
|
||||
|
||||
def _iter_pdf_attachments(eml_dir: Path):
|
||||
"""从 EML 内存读取唯一 PDF 附件;不把文件名或邮件正文写入输出。"""
|
||||
seen: set[str] = set()
|
||||
for eml_path in sorted(eml_dir.glob('*.eml')):
|
||||
message = BytesParser(policy=policy.default).parsebytes(eml_path.read_bytes())
|
||||
for part in message.walk():
|
||||
filename = str(part.get_filename() or '')
|
||||
if not filename.lower().endswith('.pdf'):
|
||||
continue
|
||||
content = part.get_payload(decode=True) or b''
|
||||
digest = sha256(content).hexdigest()
|
||||
if not content or digest in seen:
|
||||
continue
|
||||
seen.add(digest)
|
||||
yield digest, content
|
||||
|
||||
|
||||
def _positioned_characters(text_page: Any, *, page_height: float) -> list[dict[str, Any]]:
|
||||
"""把 PDFium 左下原点字符框转换为版面契约使用的左上原点坐标。"""
|
||||
result: list[dict[str, Any]] = []
|
||||
for index in range(text_page.count_chars()):
|
||||
text = text_page.get_text_range(index, 1)
|
||||
if not text:
|
||||
continue
|
||||
left, bottom, right, top = text_page.get_charbox(index, loose=True)
|
||||
if right <= left or top <= bottom:
|
||||
continue
|
||||
result.append({
|
||||
'text': text,
|
||||
'bbox': {'x0': left, 'y0': page_height - top, 'x1': right, 'y1': page_height - bottom},
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def _candidate_tables(parse_candidate: Any, pdf: Any, *, image_scale: float) -> tuple[list[dict], list[dict]]:
|
||||
"""生成页面图片元数据和严格 cell 候选;候选不等同人工真值。"""
|
||||
pages: list[dict[str, Any]] = []
|
||||
tables: list[dict[str, Any]] = []
|
||||
page_map = {item.page_no: item for item in parse_candidate.pages}
|
||||
for page_no in range(1, len(pdf) + 1):
|
||||
page = pdf[page_no - 1]
|
||||
width, height = page.get_size()
|
||||
pages.append({'page_no': page_no, 'width': width, 'height': height})
|
||||
candidate_page = page_map.get(page_no)
|
||||
if candidate_page is None or not candidate_page.tables:
|
||||
continue
|
||||
bitmap = page.render(scale=image_scale)
|
||||
image = np.asarray(bitmap.to_numpy()).copy()
|
||||
text_page = page.get_textpage()
|
||||
characters = _positioned_characters(text_page, page_height=height)
|
||||
for table_index, table in enumerate(candidate_page.tables):
|
||||
grid = parse_html_grid(table.html, table_id=table.candidate_id)
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
image,
|
||||
page_width=width,
|
||||
page_height=height,
|
||||
table_bbox=table.bbox,
|
||||
grid=grid,
|
||||
)
|
||||
cell_boxes: dict[str, dict[str, float]] = {}
|
||||
candidate_source = 'none'
|
||||
if geometry.ready:
|
||||
def bounded_text_reader(box):
|
||||
return text_page.get_text_bounded(
|
||||
left=box.x0,
|
||||
bottom=height - box.y1,
|
||||
right=box.x1,
|
||||
top=height - box.y0,
|
||||
)
|
||||
|
||||
validation = validate_opencv_cell_text(
|
||||
geometry,
|
||||
grid=grid,
|
||||
bounded_text_reader=bounded_text_reader,
|
||||
)
|
||||
if validation.accepted:
|
||||
cell_boxes = {item.cell_id: item.normalized_bbox.model_dump() for item in geometry.cells}
|
||||
candidate_source = 'opencv_text_validated'
|
||||
if not cell_boxes:
|
||||
alignment = align_html_cells_from_positioned_text(
|
||||
grid,
|
||||
characters=characters,
|
||||
table_bbox=table.bbox,
|
||||
page_width=width,
|
||||
page_height=height,
|
||||
)
|
||||
cell_boxes = {item.cell_id: item.normalized_bbox.model_dump() for item in alignment.cells}
|
||||
candidate_source = 'native_text_partial' if cell_boxes else 'none'
|
||||
tables.append({
|
||||
'annotation_id': f'table-p{page_no}-{table_index}',
|
||||
'page_no': page_no,
|
||||
'table_index': table_index,
|
||||
'normalized_bbox': table.normalized_bbox.model_dump(),
|
||||
'candidate_source': candidate_source,
|
||||
'cells': [{
|
||||
'annotation_id': f'cell-p{page_no}-{table_index}-{index}',
|
||||
'page_no': page_no,
|
||||
'table_index': table_index,
|
||||
'row_index': cell.row_index,
|
||||
'column_index': cell.column_index,
|
||||
'normalized_bbox': cell_boxes.get(cell.cell_id),
|
||||
'normalized_text': cell.text,
|
||||
'role': 'header' if cell.is_header else 'data',
|
||||
'expected_field_code': None,
|
||||
} for index, cell in enumerate(grid.cells)],
|
||||
})
|
||||
return pages, tables
|
||||
|
||||
|
||||
def _write_page_images(pdf: Any, sample_dir: Path, *, image_scale: float) -> None:
|
||||
"""渲染清晰页面图供人工框选;只写仓库外样本目录。"""
|
||||
for page_index in range(len(pdf)):
|
||||
image = pdf[page_index].render(scale=image_scale).to_pil().convert('RGB')
|
||||
image.save(sample_dir / f'page-{page_index + 1}.png', optimize=True)
|
||||
|
||||
|
||||
def _workbench_html(manifest: dict[str, Any]) -> str:
|
||||
"""生成无外部依赖的离线标注页面,导出结果符合 annotation.v1。"""
|
||||
payload = json.dumps(manifest, ensure_ascii=False).replace('</', '<\\/')
|
||||
return f'''<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Shipping Layout Truth Workbench</title><style>
|
||||
body{{margin:0;font:14px system-ui;background:#f1f5f9;color:#0f172a}} header{{padding:12px 18px;background:#0f172a;color:white}}
|
||||
main{{display:grid;grid-template-columns:300px 1fr 320px;height:calc(100vh - 48px)}} aside{{overflow:auto;padding:12px;background:white;border-right:1px solid #cbd5e1}}
|
||||
#stage{{overflow:auto;padding:18px}} #canvasWrap{{position:relative;display:inline-block;background:white;box-shadow:0 2px 12px #94a3b8}}
|
||||
canvas{{display:block;cursor:crosshair}} button,input,select{{box-sizing:border-box;margin:3px 0;padding:7px;border:1px solid #94a3b8;border-radius:6px}}
|
||||
button{{cursor:pointer;background:white}} button.primary{{background:#2563eb;color:white}} .item{{padding:7px;margin:4px 0;border:1px solid #e2e8f0;border-radius:6px;cursor:pointer}}
|
||||
.item.active{{border-color:#2563eb;background:#eff6ff}} .bad{{color:#b91c1c}} label{{display:block;margin-top:8px;color:#475569}} .row{{display:flex;gap:6px;flex-wrap:wrap}}
|
||||
</style></head><body><header>订单 PDF Cell 真值标注 - 样本 {html.escape(manifest['sample_id'])}</header>
|
||||
<main><aside><div id="pages"></div><hr><div class="row"><button id="addTable">新增表格</button><button id="addCell">新增 Cell</button></div><div id="items"></div></aside>
|
||||
<section id="stage"><div id="canvasWrap"><canvas id="canvas"></canvas></div></section>
|
||||
<aside><div id="editor"></div><hr><button class="primary" id="export">导出 annotation.json</button><button id="validate">本地完整性检查</button><pre id="status"></pre></aside></main>
|
||||
<script>const state={payload},canvas=document.querySelector('#canvas'),ctx=canvas.getContext('2d');let page=1,selected=null,drawing=null,img=new Image();
|
||||
const pageData=()=>state.pages.find(x=>x.page_no===page), tables=()=>state.tables.filter(x=>x.page_no===page), boxPx=b=>[b.x0*canvas.width,b.y0*canvas.height,b.x1*canvas.width,b.y1*canvas.height];
|
||||
function loadPage(n){{page=n;img=new Image();img.onload=()=>{{canvas.width=img.width;canvas.height=img.height;draw()}};img.src=`page-${{n}}.png`;renderLists()}}
|
||||
function draw(){{ctx.drawImage(img,0,0);for(const t of tables()){{drawBox(t.normalized_bbox,'#2563eb',t===selected?5:2);for(const c of t.cells)if(c.normalized_bbox)drawBox(c.normalized_bbox,c===selected?'#dc2626':'#f59e0b',c===selected?5:2)}}if(drawing)drawBox(drawing,'#16a34a',3)}}
|
||||
function drawBox(b,color,w){{const [x0,y0,x1,y1]=boxPx(b);ctx.strokeStyle=color;ctx.lineWidth=w;ctx.strokeRect(x0,y0,x1-x0,y1-y0)}}
|
||||
function renderLists(){{document.querySelector('#pages').innerHTML='<b>页面</b>'+state.pages.map(p=>`<button onclick="loadPage(${{p.page_no}})">${{p.page_no}}</button>`).join('');document.querySelector('#items').innerHTML=tables().map(t=>`<div class="item ${{t===selected?'active':''}}" onclick="pick('${{t.annotation_id}}')">表 ${{t.table_index}} (${{t.candidate_source}})</div>`+t.cells.map(c=>`<div class="item ${{c===selected?'active':''}}" onclick="pick('${{c.annotation_id}}')">r${{c.row_index}} c${{c.column_index}} ${{c.normalized_bbox?'':'<span class=bad>待画框</span>'}}</div>`).join('')).join('');renderEditor();draw()}}
|
||||
window.pick=id=>{{selected=state.tables.find(t=>t.annotation_id===id)||state.tables.flatMap(t=>t.cells).find(c=>c.annotation_id===id);renderLists()}};window.loadPage=loadPage;
|
||||
function renderEditor(){{const e=document.querySelector('#editor');if(!selected){{e.innerHTML='请选择表格或 Cell';return}}const cell='row_index'in selected;e.innerHTML=`<b>${{cell?'Cell':'表格'}}</b><label>normalized_text</label><input id="txt" value="${{esc(selected.normalized_text||'')}}" ${{cell?'':'disabled'}}><label>role</label><select id="role" ${{cell?'':'disabled'}}>${{['header','data','summary','deleted','empty'].map(x=>`<option ${{selected.role===x?'selected':''}}>${{x}}</option>`).join('')}}</select><label>expected_field_code</label><input id="field" value="${{esc(selected.expected_field_code||'')}}" ${{cell?'':'disabled'}}><div class=row><button id="redraw">重画框</button><button id="remove">删除</button></div>`;if(cell){{e.querySelector('#txt').oninput=x=>selected.normalized_text=x.target.value;e.querySelector('#role').onchange=x=>selected.role=x.target.value;e.querySelector('#field').oninput=x=>selected.expected_field_code=x.target.value||null}}e.querySelector('#redraw').onclick=()=>{{drawing='armed';status('请在页面拖拽矩形')}};e.querySelector('#remove').onclick=()=>{{for(const t of state.tables){{if(t===selected)state.tables=state.tables.filter(x=>x!==t);else t.cells=t.cells.filter(x=>x!==selected)}}selected=null;renderLists()}}}}
|
||||
function esc(v){{return String(v).replace(/[&<>"']/g,x=>({{'&':'&','<':'<','>':'>','"':'"',"'":'''}}[x]))}}
|
||||
canvas.onpointerdown=e=>{{if(drawing!=='armed')return;const r=canvas.getBoundingClientRect();drawing={{x0:(e.clientX-r.left)/r.width,y0:(e.clientY-r.top)/r.height,x1:0,y1:0}}}};canvas.onpointermove=e=>{{if(!drawing||drawing==='armed')return;const r=canvas.getBoundingClientRect();drawing.x1=(e.clientX-r.left)/r.width;drawing.y1=(e.clientY-r.top)/r.height;draw()}};canvas.onpointerup=()=>{{if(!drawing||drawing==='armed'||!selected)return;selected.normalized_bbox={{x0:Math.min(drawing.x0,drawing.x1),y0:Math.min(drawing.y0,drawing.y1),x1:Math.max(drawing.x0,drawing.x1),y1:Math.max(drawing.y0,drawing.y1)}};drawing=null;renderLists()}};
|
||||
document.querySelector('#addTable').onclick=()=>{{const i=state.tables.length;const t={{annotation_id:`table-manual-${{i}}`,page_no:page,table_index:tables().length,normalized_bbox:null,candidate_source:'manual',cells:[]}};state.tables.push(t);selected=t;drawing='armed';renderLists()}};
|
||||
document.querySelector('#addCell').onclick=()=>{{const t=tables()[0];if(!t)return status('当前页需先有表格');const i=t.cells.length,c={{annotation_id:`cell-manual-${{page}}-${{t.table_index}}-${{i}}`,page_no:page,table_index:t.table_index,row_index:0,column_index:0,normalized_bbox:null,normalized_text:'',role:'data',expected_field_code:null}};t.cells.push(c);selected=c;drawing='armed';renderLists()}};
|
||||
function annotation(){{return{{schema_version:'shipping_document_layout_annotation.v1',layout_schema_version:'shipping_document_layout.v1',sample_id:state.sample_id,content_hash:state.content_hash,categories:state.categories,tables:state.tables.map(t=>({{annotation_id:t.annotation_id,page_no:t.page_no,table_index:t.table_index,normalized_bbox:t.normalized_bbox,cells:t.cells.map(c=>({{annotation_id:c.annotation_id,page_no:c.page_no,table_index:c.table_index,row_index:+c.row_index,column_index:+c.column_index,normalized_bbox:c.normalized_bbox,normalized_text:c.normalized_text,role:c.role,expected_field_code:c.expected_field_code||null}})),continuation_of:t.continuation_of||null}}))}}}}
|
||||
function problems(){{const a=annotation(),p=[];for(const t of a.tables){{if(!t.normalized_bbox)p.push(`${{t.annotation_id}} 缺表框`);for(const c of t.cells)if(!c.normalized_bbox)p.push(`${{c.annotation_id}} 缺 cell 框`)}}return p}}
|
||||
document.querySelector('#validate').onclick=()=>{{const p=problems();status(p.length?p.join('\n'):'浏览器基础检查通过;请再运行脚本 validate')}};document.querySelector('#export').onclick=()=>{{const p=problems();if(p.length)return status(p.join('\n'));const blob=new Blob([JSON.stringify(annotation(),null,2)],{{type:'application/json'}}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=`${{state.sample_id}}.annotation.json`;a.click();URL.revokeObjectURL(a.href)}};function status(v){{document.querySelector('#status').textContent=v}}loadPage(1);
|
||||
</script></body></html>'''
|
||||
|
||||
|
||||
def build_workbench(args: argparse.Namespace) -> int:
|
||||
"""调用 MinerU 并为每个唯一 PDF 生成仓库外离线标注页面。"""
|
||||
source = Path(args.eml_dir).expanduser().resolve()
|
||||
output = _external_output_path(args.output_dir)
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
index_rows: list[str] = []
|
||||
count = 0
|
||||
for digest, content in _iter_pdf_attachments(source):
|
||||
if args.limit and count >= args.limit:
|
||||
break
|
||||
client = MinerUClient(MinerUClientConfig(
|
||||
base_url=args.mineru_url,
|
||||
backend='pipeline',
|
||||
read_timeout_seconds=args.timeout,
|
||||
poll_interval_seconds=1,
|
||||
))
|
||||
candidate = parse_mineru_candidate(client.parse_file_async(filename='sample.pdf', content=content))
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
sample_id = f'pdf-{digest[:12]}'
|
||||
sample_dir = output / sample_id
|
||||
sample_dir.mkdir(parents=True, exist_ok=True)
|
||||
_write_page_images(pdf, sample_dir, image_scale=args.image_scale)
|
||||
pages, tables = _candidate_tables(candidate, pdf, image_scale=args.image_scale)
|
||||
manifest = {
|
||||
'sample_id': sample_id,
|
||||
'content_hash': digest,
|
||||
'categories': ['native_pdf', 'eml_attachment'],
|
||||
'pages': pages,
|
||||
'tables': tables,
|
||||
}
|
||||
(sample_dir / 'workbench.html').write_text(_workbench_html(manifest), encoding='utf-8')
|
||||
index_rows.append(f'<li><a href="{sample_id}/workbench.html">{sample_id}</a> - {len(pages)} pages, {len(tables)} tables</li>')
|
||||
count += 1
|
||||
print(f'generated sample={sample_id} pages={len(pages)} tables={len(tables)}')
|
||||
(output / 'index.html').write_text(
|
||||
'<!doctype html><meta charset="utf-8"><h1>Shipping Layout Truth Workbench</h1><ol>'
|
||||
+ ''.join(index_rows) + '</ol>',
|
||||
encoding='utf-8',
|
||||
)
|
||||
print(f'generated_count={count} output={output}')
|
||||
return 0
|
||||
|
||||
|
||||
def validate_annotations(args: argparse.Namespace) -> int:
|
||||
"""使用正式 annotation.v1 契约校验单个 JSON 或目录中的全部导出。"""
|
||||
target = Path(args.path).expanduser().resolve()
|
||||
files = [target] if target.is_file() else sorted(target.rglob('*.annotation.json'))
|
||||
if not files:
|
||||
print('no annotation files found', file=sys.stderr)
|
||||
return 2
|
||||
failed = 0
|
||||
for path in files:
|
||||
try:
|
||||
annotation = LayoutAnnotation.model_validate_json(path.read_text(encoding='utf-8'))
|
||||
print(f'valid sample={annotation.sample_id} tables={len(annotation.tables)} cells={sum(len(t.cells) for t in annotation.tables)}')
|
||||
except Exception as exc:
|
||||
failed += 1
|
||||
print(f'invalid file={path.name} error={type(exc).__name__}', file=sys.stderr)
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
"""解析 build/validate 子命令,MinerU URL 只接受运行参数,不写项目配置。"""
|
||||
parser = argparse.ArgumentParser(description='Build or validate shipping layout truth workbench')
|
||||
subparsers = parser.add_subparsers(dest='command', required=True)
|
||||
build = subparsers.add_parser('build')
|
||||
build.add_argument('--eml-dir', required=True)
|
||||
build.add_argument('--output-dir', required=True)
|
||||
build.add_argument('--mineru-url', required=True)
|
||||
build.add_argument('--timeout', type=int, default=300)
|
||||
build.add_argument('--image-scale', type=float, default=2.0)
|
||||
build.add_argument('--limit', type=int, default=0)
|
||||
validate = subparsers.add_parser('validate')
|
||||
validate.add_argument('path')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""执行离线工作台生成或人工真值契约校验。"""
|
||||
args = parse_args()
|
||||
return build_workbench(args) if args.command == 'build' else validate_annotations(args)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
backend/tests/test_admin_shipping_document_layouts.py
|
||||
|
||||
用途:验证布局版本管理员诊断、隐私字段最小化和显式重解析幂等 API。
|
||||
依赖:admin API、layout lifecycle、统一响应 envelope。
|
||||
逻辑:普通用户拒绝;管理员只见状态/checksum/计数,重复重解析复用活动版本。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from tests.conftest import parse_api_data
|
||||
from tests.test_shipping_document_layout_lifecycle import _document, _snapshot
|
||||
|
||||
|
||||
def test_layout_admin_api_is_private_and_reparse_is_idempotent(app):
|
||||
"""诊断不得泄露 payload/html/bbox;重解析重复点击只保留一个活动版本。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
document_id = document.id
|
||||
record_inline_layout_snapshot(document, {
|
||||
**_snapshot(), 'tables': [{'html': '<table>secret</table>', 'bbox': {'x0': 1}}],
|
||||
})
|
||||
db.session.add(User(
|
||||
username='layout-admin', email='layout-admin@example.com', role='admin', status='active',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
client = app.test_client()
|
||||
denied = client.get(
|
||||
f'/api/admin/shipping-notice/documents/{document_id}/layout-versions',
|
||||
headers={'X-Username': 'layout-owner', 'X-Role': 'user'},
|
||||
)
|
||||
assert denied.status_code == 403
|
||||
|
||||
headers = {'X-Username': 'layout-admin', 'X-Role': 'admin'}
|
||||
listed = client.get(
|
||||
f'/api/admin/shipping-notice/documents/{document_id}/layout-versions', headers=headers,
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
versions = parse_api_data(listed.get_json())
|
||||
assert versions[0]['table_count'] == 1
|
||||
assert 'payload_json' not in versions[0]
|
||||
assert 'html' not in str(versions[0]).lower()
|
||||
assert 'bbox' not in str(versions[0]).lower()
|
||||
|
||||
first = client.post(
|
||||
f'/api/admin/shipping-notice/documents/{document_id}/layout-reparse', headers=headers,
|
||||
)
|
||||
second = client.post(
|
||||
f'/api/admin/shipping-notice/documents/{document_id}/layout-reparse', headers=headers,
|
||||
)
|
||||
assert first.status_code == 202
|
||||
assert second.status_code == 202
|
||||
assert parse_api_data(first.get_json())['id'] == parse_api_data(second.get_json())['id']
|
||||
@@ -31,10 +31,12 @@ from app.jobs.queue import claim_next_job, recover_stale_jobs
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent, AgentRuntimeBinding, Job, ShippingNoticeCandidate, ShippingNoticeDocument,
|
||||
ShippingOrderExtraction, ShippingOrderExtractionRun, ShippingOrderSchemaVersion, User,
|
||||
ShippingOrderDocumentProfile, ShippingOrderExtraction, ShippingOrderExtractionRun,
|
||||
ShippingOrderSchemaVersion, User,
|
||||
)
|
||||
from app.services.agent_runtime_binding_service import resolve_runtime_binding, save_runtime_binding
|
||||
from app.services.admin.agent_service import update_agent_permissions
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from app.services.admin.agent_service import list_agents
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
build_order_extraction_workflow_inputs, execute_order_extraction_workflow,
|
||||
@@ -95,6 +97,50 @@ def test_binding_catalog_exposes_internal_executor_role_constraint(app):
|
||||
assert binding.provider_agent.exposure_mode == 'internal'
|
||||
|
||||
|
||||
def test_binding_rejects_retired_workflow_contract_version(app):
|
||||
"""唯一协议不接受历史版本开关,防止运行时重新出现双格式分支。"""
|
||||
with app.app_context():
|
||||
owner = Agent(name='Owner', agent_code='shipping_notice', runtime_provider='hybrid')
|
||||
provider = Agent(
|
||||
name='Workflow Provider', agent_code='generic', runtime_provider='dify',
|
||||
dify_app_type='workflow', exposure_mode='internal', dify_app_id='workflow-provider',
|
||||
dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True,
|
||||
)
|
||||
db.session.add_all([owner, provider])
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
save_runtime_binding(
|
||||
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider.id, enabled=True,
|
||||
config={'workflow_contract_version': 'latest'},
|
||||
)
|
||||
|
||||
assert caught.value.code == 'AGENT.RUNTIME_BINDING_CONFIG_INVALID'
|
||||
|
||||
|
||||
def test_binding_rejects_retired_workflow_contract_version_with_auto_create(app):
|
||||
"""自动建单也不得通过历史版本配置绕过唯一协议约束。"""
|
||||
with app.app_context():
|
||||
owner = Agent(name='Owner', agent_code='shipping_notice', runtime_provider='hybrid')
|
||||
provider = Agent(
|
||||
name='Workflow Provider', agent_code='generic', runtime_provider='dify',
|
||||
dify_app_type='workflow', exposure_mode='internal', dify_app_id='workflow-provider',
|
||||
dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True,
|
||||
)
|
||||
db.session.add_all([owner, provider])
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
save_runtime_binding(
|
||||
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider.id, enabled=True,
|
||||
config={'workflow_contract_version': 'legacy', 'auto_create_enabled': True},
|
||||
)
|
||||
|
||||
assert caught.value.code == 'AGENT.RUNTIME_BINDING_CONFIG_INVALID'
|
||||
|
||||
|
||||
def test_internal_executor_cannot_receive_user_permissions(app):
|
||||
"""内部执行器只能被运行时绑定,不能进入用户授权关系。"""
|
||||
with app.app_context():
|
||||
@@ -182,14 +228,6 @@ def test_runtime_binding_admin_api_and_internal_agent_hidden(app, client, admin_
|
||||
assert saved.get_json()['data']['config'] == {
|
||||
'timeout_seconds': 600,
|
||||
'max_attempts': 2,
|
||||
'unit_concurrency': 2,
|
||||
'unit_max_attempts': 2,
|
||||
'unit_retry_backoff_ms': 500,
|
||||
'max_model_units': 20,
|
||||
'provider_max_concurrency': 4,
|
||||
'circuit_failure_threshold': 5,
|
||||
'circuit_cooldown_seconds': 60,
|
||||
'auto_create_enabled': False,
|
||||
}
|
||||
assert 'dify_api_key' not in saved.get_json()['data']
|
||||
|
||||
@@ -473,7 +511,9 @@ def test_dify_terminal_contract_error_does_not_retry_or_open_circuit(app):
|
||||
)
|
||||
run_snapshot = {
|
||||
'id': 1, 'run_no': 'SNER-CONTRACT-ERROR', 'user_id': 1,
|
||||
'schema_version_id': 1,
|
||||
'input_snapshot_hash': 'a' * 64, 'input_snapshot_json': {},
|
||||
'provider_config_json': {},
|
||||
}
|
||||
unit_snapshot = {
|
||||
'id': 1, 'intake_id': 1, 'document_id': 1,
|
||||
@@ -500,8 +540,8 @@ def test_dify_terminal_contract_error_does_not_retry_or_open_circuit(app):
|
||||
record_failure.assert_not_called()
|
||||
|
||||
|
||||
def test_workflow_inputs_use_frozen_extraction_contract_only(app):
|
||||
"""Workflow manifest 仅含冻结抽取契约与受控提示,完整定义不得旁路泄露。"""
|
||||
def test_workflow_inputs_use_unique_extraction_contract_only(app):
|
||||
"""唯一 Workflow manifest 仅含冻结抽取契约与受控提示,完整定义不得旁路泄露。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input()
|
||||
run, _ = create_order_extraction_run(
|
||||
@@ -511,21 +551,19 @@ def test_workflow_inputs_use_frozen_extraction_contract_only(app):
|
||||
inputs = build_order_extraction_workflow_inputs(run, unit=unit)
|
||||
manifest = json.loads(inputs['execution_manifest'])
|
||||
schema = manifest['extraction_contract']
|
||||
documents = manifest['documents']
|
||||
document = manifest['document']
|
||||
readonly_context = manifest['readonly_hints']
|
||||
|
||||
assert schema == run.input_snapshot_json['schema']['extraction_contract']
|
||||
assert manifest['contract_version'] == 'shipping_order_extraction.unit.v2'
|
||||
assert 'contract_version' not in manifest
|
||||
assert manifest['run']['run_no'] == run.run_no
|
||||
assert manifest['unit']['unit_id'] == unit.id
|
||||
assert manifest['unit']['document_id'] == unit.document_id
|
||||
assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash
|
||||
assert 'definition' not in schema
|
||||
assert schema['fields'][0]['field_id'] == 'qty-id'
|
||||
assert len(documents) == 1
|
||||
assert set(documents[0]) == {'intake_id', 'intake_no', 'document'}
|
||||
assert documents[0]['document']['document_id'] == unit.document_id
|
||||
assert 'sales-' not in repr(documents).lower()
|
||||
assert document['document_id'] == unit.document_id
|
||||
assert 'sales-' not in repr(document).lower()
|
||||
assert readonly_context == []
|
||||
assert set(inputs) == {'execution_manifest'}
|
||||
|
||||
@@ -551,7 +589,7 @@ def test_workflow_execution_sends_only_versioned_manifest(app):
|
||||
inputs = mocked_run.call_args.kwargs['inputs']
|
||||
manifest = json.loads(inputs['execution_manifest'])
|
||||
assert set(inputs) == {'execution_manifest'}
|
||||
assert manifest['contract_version'] == 'shipping_order_extraction.unit.v2'
|
||||
assert 'contract_version' not in manifest
|
||||
assert manifest['run']['run_no'] == run.run_no
|
||||
assert manifest['unit']['unit_id'] == unit.id
|
||||
assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash
|
||||
@@ -559,8 +597,140 @@ def test_workflow_execution_sends_only_versioned_manifest(app):
|
||||
assert metadata['workflow_run_id'] == 'wf-manifest'
|
||||
|
||||
|
||||
def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app):
|
||||
"""冻结 Schema 可完整解析的表格单元必须零模型调用,并缓存可恢复的局部订单。"""
|
||||
def test_unique_manifest_sends_compact_layout_candidates_only(app):
|
||||
"""唯一 Manifest 只发送紧凑字段候选,禁止泄漏 bbox、HTML、token、cell_id 或 field_code。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='UNIT-V3')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
frozen = run.input_snapshot_json['intakes'][0]['documents'][0]
|
||||
frozen['layout_snapshot'] = {'html': 'RAW-HTML', 'bbox': [1, 2, 3, 4]}
|
||||
frozen['layout_schema_candidates'] = [{
|
||||
'page_no': 2, 'table_id': 'table-1', 'mapping_status': 'candidate',
|
||||
'issues': ['layout_table_not_accepted'],
|
||||
'rows': [{
|
||||
'row_index': 3, 'role': 'data', 'issues': [],
|
||||
'fields': [{
|
||||
'field_id': 'qty-id', 'field_code': 'qty', 'value': 30,
|
||||
'quote': 'Qty 30', 'column_index': 4, 'cell_id': 'secret-cell',
|
||||
'token_ids': ['secret-token'], 'evidence_ref': 'secret-ref',
|
||||
}],
|
||||
}],
|
||||
}]
|
||||
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest'])
|
||||
|
||||
assert 'contract_version' not in manifest
|
||||
assert manifest['structured_table_candidates'][0]['field_policy'] == 'suggested'
|
||||
assert manifest['structured_table_candidates'][0]['rows'][0]['fields'] == [{
|
||||
'column_index': 4, 'field_id': 'qty-id', 'value': 30, 'quote': 'Qty 30',
|
||||
}]
|
||||
assert 'documents' not in manifest
|
||||
serialized = repr({
|
||||
'document': manifest['document'],
|
||||
'structured_table_candidates': manifest['structured_table_candidates'],
|
||||
})
|
||||
for forbidden in ('RAW-HTML', 'bbox', 'secret-cell', 'secret-token', 'secret-ref', 'field_code'):
|
||||
assert forbidden not in serialized
|
||||
|
||||
|
||||
def test_unique_manifest_prefers_mineru_pdf_text_and_table_grid(app):
|
||||
"""PDF 有 ready MinerU 快照时应向模型发送分页文本和 TSV 表格,替换旧拍平文本。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='MINERU-TEXT')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
frozen = run.input_snapshot_json['intakes'][0]['documents'][0]
|
||||
frozen['filename'] = 'order.pdf'
|
||||
frozen['extracted_text'] = 'LEGACY-FLAT-TEXT'
|
||||
frozen['layout_snapshot'] = {
|
||||
'status': 'ready',
|
||||
'text_blocks': [{
|
||||
'page_no': 1, 'normalized_bbox': {'x0': 0.1, 'y0': 0.1},
|
||||
'text': 'PO Number: 4518838154',
|
||||
}],
|
||||
'tables': [{
|
||||
'table_id': 'table-1', 'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.3},
|
||||
'html': '<table><tr><th>Item</th><th>Reservation ID</th></tr>'
|
||||
'<tr><td>00020</td><td>12345</td></tr></table>',
|
||||
}],
|
||||
}
|
||||
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest'])
|
||||
|
||||
document = manifest['document']
|
||||
assert document['text_source'] == 'mineru'
|
||||
assert 'LEGACY-FLAT-TEXT' not in document['extracted_text']
|
||||
assert 'PO Number: 4518838154' in document['extracted_text']
|
||||
assert 'Item\tReservation ID' in document['extracted_text']
|
||||
assert '00020\t12345' in document['extracted_text']
|
||||
assert 'html' not in repr(document)
|
||||
|
||||
|
||||
def test_unique_manifest_accepted_layout_fields_cannot_be_overridden(app):
|
||||
"""唯一 Manifest 模型可以补充候选,但 accepted 字段缺失或改值必须被后端拒绝。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LOCKED-FIELD')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
run.input_snapshot_json['intakes'][0]['documents'][0]['layout_schema_candidates'] = [{
|
||||
'mapping_status': 'accepted', 'rows': [{
|
||||
'role': 'data', 'fields': [{'field_id': 'qty-id', 'value': 30}],
|
||||
}],
|
||||
}]
|
||||
invalid = [{
|
||||
'source_intake_no': intake.intake_no, 'primary_document_id': unit.document_id,
|
||||
'header_fields': [], 'lines': [{'fields': [{
|
||||
'field_id': 'qty-id', 'observations': [{
|
||||
'value': 31, 'document_id': unit.document_id,
|
||||
}],
|
||||
}]}],
|
||||
}]
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
validate_unit_orders(run, unit=unit, orders=invalid)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
|
||||
|
||||
def test_accepted_complete_layout_builds_order_without_provider(app):
|
||||
"""唯一 accepted 表格覆盖全部必填字段时必须直接生成订单,保持零 Provider 调用。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LAYOUT-ZERO-PROVIDER')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
run.input_snapshot_json['intakes'][0]['documents'][0]['layout_schema_candidates'] = [{
|
||||
'mapping_status': 'accepted', 'issues': [],
|
||||
'rows': [{
|
||||
'role': 'data', 'fields': [{
|
||||
'field_id': 'qty-id', 'value': 30, 'quote': 'Qty 30',
|
||||
}],
|
||||
}],
|
||||
}]
|
||||
from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders
|
||||
|
||||
orders = build_deterministic_unit_orders(run, unit=unit)
|
||||
|
||||
assert orders is not None
|
||||
assert orders[0]['lines'][0]['fields'][0]['field_id'] == 'qty-id'
|
||||
assert orders[0]['lines'][0]['fields'][0]['observations'][0]['value'] == 30
|
||||
|
||||
|
||||
def test_plain_text_complete_table_still_uses_provider(app):
|
||||
"""纯文本表格即使字段齐全也不能零 Provider,防止 L7 恢复猜列运行路径。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='DETERMINISTIC')
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
@@ -590,6 +760,7 @@ def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app):
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
return_value=([], {'workflow_run_id': 'wf-plain-text', 'execution_mode': 'dify'}),
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
@@ -602,11 +773,149 @@ def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app):
|
||||
db.session.expire_all()
|
||||
finished = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
unit = finished.extraction_plan.units[0]
|
||||
assert execute.call_count == 0
|
||||
assert submit.call_args.kwargs['orders'][0]['lines'][0]['fields']
|
||||
assert execute.call_count == 1
|
||||
assert submit.call_args.kwargs['orders'] == []
|
||||
assert unit.status == 'succeeded'
|
||||
assert unit.result_json['workflow']['execution_mode'] == 'deterministic'
|
||||
assert finished.provider_result_json['workflow']['deterministic_unit_count'] == 1
|
||||
assert unit.result_json['workflow']['execution_mode'] == 'dify'
|
||||
assert finished.provider_result_json['workflow']['deterministic_unit_count'] == 0
|
||||
|
||||
|
||||
def test_profile_template_candidate_uses_provider_after_l7_cleanup(app):
|
||||
"""Profile 仍提供紧凑语义候选,但未获 accepted cell 前不能跳过 Provider。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROFILE-MAP')
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
version.definition_json = {'fields': [
|
||||
{
|
||||
'field_id': 'customer-id', 'field_code': 'customer_part_number', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': False,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
|
||||
'value_type': 'decimal', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
|
||||
},
|
||||
]}
|
||||
html = (
|
||||
'<table><tr><th>LN</th><th>Part Number</th><th>Vendor Item#</th><th>Qty</th></tr>'
|
||||
'<tr><td>1</td><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>3</td></tr>'
|
||||
'<tr><td>2</td><td>CUSTOMER-Z</td><td>INTERNAL-Z</td><td>0</td></tr></table>'
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.order_profile import order_profile_structure_fingerprint
|
||||
|
||||
fingerprint = order_profile_structure_fingerprint(parse_html_grid(html, table_id='fixture'), header_row_index=0)
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='PO_312207', display_name='PO template', version=1, status='published',
|
||||
schema_version_id=version.id, structure_fingerprint=fingerprint, checksum='e' * 64,
|
||||
definition_json={
|
||||
'contract_version': 'shipping_order_document_profile.v1',
|
||||
'structure_fingerprint': fingerprint, 'header_row_index': 0,
|
||||
'data_start_row_index': 1, 'row_structure': 'preserved', 'drop_zero_qty': True,
|
||||
'column_rules': [
|
||||
{'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['customer_part_number'],
|
||||
'target_fields': [{'field_id': 'customer-id', 'field_code': 'customer_part_number'}]},
|
||||
{'column_index': 2, 'extractor_key': 'direct', 'target_field_codes': ['part_number'],
|
||||
'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}]},
|
||||
{'column_index': 3, 'extractor_key': 'direct', 'target_field_codes': ['qty'],
|
||||
'target_fields': [{'field_id': 'qty-id', 'field_code': 'qty'}]},
|
||||
],
|
||||
}, published_at=datetime.utcnow(),
|
||||
)
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru', 'backend': 'pipeline', 'status': 'ready', 'issues': [],
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html}],
|
||||
})
|
||||
db.session.add(profile)
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='profile-worker',
|
||||
)
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
return_value=([], {'workflow_run_id': 'wf-profile', 'execution_mode': 'dify'}),
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
},
|
||||
) as submit:
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
execute.assert_called_once()
|
||||
manifest = json.loads(execute.call_args.kwargs['run'].input_snapshot_json and build_order_extraction_workflow_inputs(
|
||||
run, unit=run.extraction_plan.units[0],
|
||||
)['execution_manifest'])
|
||||
assert manifest['structured_table_candidates'] == []
|
||||
assert submit.call_args.kwargs['orders'] == []
|
||||
|
||||
|
||||
def test_profile_layout_html_is_not_sent_to_dify(app):
|
||||
"""Profile 不完整而回退 Dify 时,Manifest 只能携带紧凑候选,不能含坐标或原始 HTML。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROFILE-TOKEN')
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru', 'backend': 'pipeline', 'status': 'ready', 'issues': [],
|
||||
'tables': [{
|
||||
'table_id': 'table-secret', 'page_no': 1,
|
||||
'bbox': {'x0': 1, 'y0': 2, 'x1': 3, 'y1': 4},
|
||||
'html': '<table><tr><td>RAW-LAYOUT-SECRET</td></tr></table>',
|
||||
}],
|
||||
})
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest'])
|
||||
|
||||
assert 'layout_snapshot' not in manifest['document']
|
||||
assert 'layout_schema_candidates' not in manifest['document']
|
||||
# 表格文字可作为 TSV 上下文提供给 LLM;布局 HTML 与坐标/证据内部标识不得泄漏。
|
||||
assert 'RAW-LAYOUT-SECRET' in manifest['document']['extracted_text']
|
||||
assert '<table' not in repr(manifest).lower()
|
||||
assert "'bbox'" not in repr(manifest)
|
||||
assert 'cell_id' not in repr(manifest)
|
||||
assert 'evidence_ref' not in repr(manifest)
|
||||
|
||||
|
||||
def test_multiple_profile_tables_fall_back_to_dify_instead_of_merging_orders(app):
|
||||
"""一个文档多张表命中 Profile 时不得自动合并成一张订单,必须交模型/复核拆单。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROFILE-MULTI')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_workflow._profile_table_candidates',
|
||||
return_value={
|
||||
'matched': True, 'blocking': False, 'issues': [],
|
||||
'tables': [{'rows': []}, {'rows': []}],
|
||||
},
|
||||
):
|
||||
from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders
|
||||
|
||||
assert build_deterministic_unit_orders(run, unit=unit) is None
|
||||
|
||||
|
||||
def test_unit_manifest_never_contains_sibling_document(app):
|
||||
@@ -635,8 +944,7 @@ def test_unit_manifest_never_contains_sibling_document(app):
|
||||
run, unit=unit,
|
||||
)['execution_manifest'])
|
||||
|
||||
assert len(manifest['documents']) == 1
|
||||
assert manifest['documents'][0]['document']['document_id'] == first.id
|
||||
assert manifest['document']['document_id'] == first.id
|
||||
assert 'SIBLING-SECRET-CONTENT' not in repr(manifest)
|
||||
|
||||
|
||||
@@ -683,12 +991,6 @@ def test_worker_runs_dify_units_with_frozen_concurrency_limit(app):
|
||||
classification='order_notice', parse_status='parsed',
|
||||
extracted_text=f'Unstructured document {index}',
|
||||
))
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 3, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
@@ -736,12 +1038,6 @@ def test_worker_retries_only_failed_unit_locally(app):
|
||||
"""单元首次网络失败后只重试该单元,并保存 attempt/latency 指标。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LOCAL-RETRY')
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 3, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 2, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
@@ -791,12 +1087,6 @@ def test_worker_persists_successful_units_when_one_unit_exhausts_retries(app):
|
||||
extracted_text='Second unstructured document',
|
||||
)
|
||||
db.session.add(second)
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 1, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
@@ -848,18 +1138,11 @@ def test_worker_blocks_model_calls_when_frozen_unit_budget_is_exceeded(app):
|
||||
content_hash='9' * 64, classification='order_notice', parse_status='parsed',
|
||||
extracted_text='Another unstructured document',
|
||||
))
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 1, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
'max_model_units': 1, 'provider_max_concurrency': 4,
|
||||
'circuit_failure_threshold': 5, 'circuit_cooldown_seconds': 60,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
run.provider_config_json = {**dict(run.provider_config_json or {}), 'max_model_units': 1}
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
backend/tests/test_order_document_profile_migration.py
|
||||
|
||||
用途:验证订单文档 Profile 迁移可升级、约束发布唯一性并可降级。
|
||||
依赖:Alembic migration module、临时 SQLite 连接。
|
||||
逻辑:直接执行迁移函数检查表、索引和生命周期约束,不依赖开发数据库。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_document_profile_migration_upgrade_and_downgrade(monkeypatch):
|
||||
"""迁移必须创建版本表和唯一 published 门禁,降级后完全移除。"""
|
||||
migration = importlib.import_module('migrations.versions.a68f8091a2b4_add_order_document_profiles')
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('shipping_order_schema_versions', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('shipping_notice_documents', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
metadata.create_all(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_order_document_profiles' in inspector.get_table_names()
|
||||
assert 'layout_snapshot_json' in {
|
||||
item['name'] for item in inspector.get_columns('shipping_notice_documents')
|
||||
}
|
||||
|
||||
table = sa.Table('shipping_order_document_profiles', sa.MetaData(), autoload_with=connection)
|
||||
base = {
|
||||
'display_name': 'Template', 'version': 1, 'schema_version_id': 1,
|
||||
'structure_fingerprint': 'a' * 64, 'definition_json': {}, 'lock_version': 1,
|
||||
'created_at': sa.func.current_timestamp(), 'updated_at': sa.func.current_timestamp(),
|
||||
}
|
||||
connection.execute(table.insert().values(profile_code='TEMPLATE_A', status='published', **base))
|
||||
duplicate = connection.begin_nested()
|
||||
with pytest.raises(sa.exc.IntegrityError):
|
||||
connection.execute(table.insert().values(
|
||||
profile_code='TEMPLATE_A', status='published', **{**base, 'version': 2},
|
||||
))
|
||||
duplicate.rollback()
|
||||
|
||||
migration.downgrade()
|
||||
assert 'shipping_order_document_profiles' not in sa.inspect(connection).get_table_names()
|
||||
assert 'layout_snapshot_json' not in {
|
||||
item['name'] for item in sa.inspect(connection).get_columns('shipping_notice_documents')
|
||||
}
|
||||
@@ -34,6 +34,24 @@ def _order(document_id, *, po='PO-1', part='PN-1', reservation='R-1', qty=1):
|
||||
}
|
||||
|
||||
|
||||
def _partial_order(document_id, *, po='PO-1', lines: list[dict]):
|
||||
"""构造只含当前 Document 可证明字段的订单片段,模拟 PDF/EML 分别返回。"""
|
||||
return {
|
||||
'source_intake_no': 'SNI-1', 'primary_document_id': document_id,
|
||||
'header_fields': [_field('po-id', po, document_id)] if po else [], 'lines': lines,
|
||||
}
|
||||
|
||||
|
||||
def _partial_line(document_id, *, part: str, reservation: str | None = None, qty: int | None = None):
|
||||
"""构造跨文档行片段;Reservation 缺失时不得伪造空 Observation。"""
|
||||
fields = [_field('part-id', part, document_id)]
|
||||
if reservation is not None:
|
||||
fields.append(_field('res-id', reservation, document_id))
|
||||
if qty is not None:
|
||||
fields.append(_field('qty-id', qty, document_id))
|
||||
return {'fields': fields}
|
||||
|
||||
|
||||
def test_same_po_merges_observations_and_preserves_conflicting_values():
|
||||
"""同一 PO 合并后 Qty 冲突证据必须同时存在,交由动态字段裁决阻断。"""
|
||||
merged = merge_unit_orders(
|
||||
@@ -57,3 +75,65 @@ def test_part_number_without_same_reservation_does_not_merge_without_po():
|
||||
)
|
||||
|
||||
assert len(merged) == 2
|
||||
|
||||
|
||||
def test_same_po_uniquely_merges_pdf_line_with_email_reservation_in_either_order():
|
||||
"""PDF 料号/数量与 EML 同料号 Reservation 唯一对应时,完成顺序不能影响行级补全。"""
|
||||
pdf = _partial_order(1, lines=[_partial_line(1, part='PN-1', qty=30)])
|
||||
email = _partial_order(2, lines=[_partial_line(2, part='PN-1', reservation='1000123456')])
|
||||
|
||||
for orders in ([pdf, email], [email, pdf]):
|
||||
merged = merge_unit_orders(orders=orders, schema_definition=DEFINITION)
|
||||
|
||||
assert len(merged) == 1
|
||||
assert len(merged[0]['lines']) == 1
|
||||
fields = {item['field_id']: item['observations'] for item in merged[0]['lines'][0]['fields']}
|
||||
assert fields['part-id'][0]['value'] == 'PN-1'
|
||||
assert fields['qty-id'][0]['value'] == 30
|
||||
assert fields['res-id'][0]['value'] == '1000123456'
|
||||
|
||||
|
||||
def test_same_po_duplicate_part_number_does_not_guess_reservation_line():
|
||||
"""同 PO 的多个相同料号无法唯一对应时,邮件 Reservation 不得猜测性填入任一 PDF 行。"""
|
||||
pdf = _partial_order(1, lines=[
|
||||
_partial_line(1, part='PN-1', qty=30),
|
||||
_partial_line(1, part='PN-1', qty=36),
|
||||
])
|
||||
email = _partial_order(2, lines=[_partial_line(2, part='PN-1', reservation='1000123456')])
|
||||
|
||||
merged = merge_unit_orders(orders=[pdf, email], schema_definition=DEFINITION)
|
||||
|
||||
assert len(merged) == 1
|
||||
assert len(merged[0]['lines']) == 3
|
||||
assert sum(
|
||||
1 for line in merged[0]['lines']
|
||||
if any(field['field_id'] == 'res-id' for field in line['fields'])
|
||||
) == 1
|
||||
|
||||
|
||||
def test_same_po_conflicting_reservations_do_not_merge_lines():
|
||||
"""同一强锚点已各自携带不同 Reservation 时必须保留两行,交由后续冲突裁决。"""
|
||||
first = _partial_order(1, lines=[_partial_line(1, part='PN-1', reservation='1000123456', qty=30)])
|
||||
second = _partial_order(2, lines=[_partial_line(2, part='PN-1', reservation='1000123457')])
|
||||
|
||||
merged = merge_unit_orders(orders=[first, second], schema_definition=DEFINITION)
|
||||
|
||||
assert len(merged) == 1
|
||||
assert len(merged[0]['lines']) == 2
|
||||
|
||||
|
||||
def test_same_po_conflicting_line_no_does_not_merge_same_part_number():
|
||||
"""料号一致但双方都有不同项次时,不能忽略项次而错误补入 Reservation。"""
|
||||
pdf_line = _partial_line(1, part='PN-1', qty=30)
|
||||
pdf_line['fields'].append(_field('line-id', '00010', 1))
|
||||
email_line = _partial_line(2, part='PN-1', reservation='1000123456')
|
||||
email_line['fields'].append(_field('line-id', '00020', 2))
|
||||
definition = {**DEFINITION, 'fields': [*DEFINITION['fields'], {'field_id': 'line-id', 'field_code': 'line_no'}]}
|
||||
|
||||
merged = merge_unit_orders(
|
||||
orders=[_partial_order(1, lines=[pdf_line]), _partial_order(2, lines=[email_line])],
|
||||
schema_definition=definition,
|
||||
)
|
||||
|
||||
assert len(merged) == 1
|
||||
assert len(merged[0]['lines']) == 2
|
||||
@@ -13,7 +13,11 @@ from copy import deepcopy
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.evaluation import evaluate_layout
|
||||
from app.services.shipping_notice.document_layout.evaluation import (
|
||||
PdfOrderQualityMetrics,
|
||||
review_pdf_order_quality_gate,
|
||||
evaluate_layout,
|
||||
)
|
||||
from tests.test_shipping_document_layout_contract import _document
|
||||
|
||||
|
||||
@@ -108,3 +112,93 @@ def test_evaluation_rejects_invalid_annotation_geometry():
|
||||
outside_table['tables'][0]['cells'][0]['normalized_bbox']['x0'] = 0.01
|
||||
with pytest.raises(ValidationError, match='within parent table'):
|
||||
evaluate_layout(outside_table, _document())
|
||||
|
||||
|
||||
def _pdf_order_truth(*, categories: list[str], status: str = 'active') -> dict:
|
||||
"""构造脱敏 PDF 订单行真值,覆盖删除归属和高风险字段的阶段门禁。"""
|
||||
line = {
|
||||
'line_id': 'line-00020',
|
||||
'table_annotation_id': 'table-1',
|
||||
'line_cell_ids': ['cell-item-00020', 'cell-qty-00020'],
|
||||
'status': status,
|
||||
'fields': [{
|
||||
'field_code': 'qty', 'value': 30, 'evidence_cell_ids': ['cell-qty-00020'],
|
||||
}],
|
||||
}
|
||||
if status == 'deleted':
|
||||
line['line_id'] = 'line-00010'
|
||||
line['deletion_marker_cell_id'] = 'cell-item-deleted'
|
||||
return {
|
||||
'schema_version': 'shipping_pdf_order_truth.v1',
|
||||
'sample_id': f'sample-{status}',
|
||||
'content_hash': 'c' * 64,
|
||||
'categories': categories,
|
||||
'lines': [line],
|
||||
}
|
||||
|
||||
|
||||
def test_pdf_order_quality_gate_passes_only_when_all_safety_rules_hold():
|
||||
"""六类样本齐全且零误删、零高风险误放行、零漏复核时才允许进入下一阶段。"""
|
||||
truth = [_pdf_order_truth(categories=[
|
||||
'normal_multi_line', 'continued_row', 'deleted_line', 'cross_page_header',
|
||||
'scanned_ocr', 'unreadable_pdf',
|
||||
])]
|
||||
gate = review_pdf_order_quality_gate(truth, PdfOrderQualityMetrics(
|
||||
active_truth_lines=1,
|
||||
deleted_truth_lines=1,
|
||||
active_lines_auto_released=1,
|
||||
active_lines_misdeleted=0,
|
||||
high_risk_auto_released_fields=1,
|
||||
incorrect_high_risk_auto_released_fields=0,
|
||||
unreliable_truth_lines=1,
|
||||
unreliable_lines_sent_to_review=1,
|
||||
))
|
||||
|
||||
assert gate.passed is True
|
||||
assert gate.reasons == []
|
||||
|
||||
|
||||
def test_pdf_order_quality_gate_blocks_missing_categories_and_unsafe_results():
|
||||
"""缺样本、误删有效行、错误放行或漏转复核中任一项存在时必须阻断阶段推进。"""
|
||||
gate = review_pdf_order_quality_gate(
|
||||
[_pdf_order_truth(categories=['deleted_line'])],
|
||||
{
|
||||
'active_truth_lines': 1,
|
||||
'deleted_truth_lines': 1,
|
||||
'active_lines_auto_released': 0,
|
||||
'active_lines_misdeleted': 1,
|
||||
'high_risk_auto_released_fields': 2,
|
||||
'incorrect_high_risk_auto_released_fields': 1,
|
||||
'unreliable_truth_lines': 2,
|
||||
'unreliable_lines_sent_to_review': 1,
|
||||
},
|
||||
)
|
||||
|
||||
assert gate.passed is False
|
||||
assert 'active_order_line_misdeleted' in gate.reasons
|
||||
assert 'incorrect_high_risk_field_auto_released' in gate.reasons
|
||||
assert 'unreliable_order_line_not_sent_to_review' in gate.reasons
|
||||
assert any(reason.startswith('pdf_order_truth_categories_missing:') for reason in gate.reasons)
|
||||
|
||||
|
||||
def test_pdf_order_truth_requires_a_marker_for_deleted_line_but_allows_review_truth():
|
||||
"""删除归属缺证据必须拒绝;待复核行保留真值字段,供漏转复核评测使用。"""
|
||||
deleted = _pdf_order_truth(categories=['deleted_line'], status='deleted')
|
||||
deleted['lines'][0].pop('deletion_marker_cell_id')
|
||||
with pytest.raises(ValidationError, match='deletion_marker_cell_id'):
|
||||
review_pdf_order_quality_gate([deleted], {
|
||||
'active_truth_lines': 0, 'deleted_truth_lines': 1,
|
||||
'active_lines_auto_released': 0, 'active_lines_misdeleted': 0,
|
||||
'high_risk_auto_released_fields': 0,
|
||||
'incorrect_high_risk_auto_released_fields': 0,
|
||||
'unreliable_truth_lines': 0, 'unreliable_lines_sent_to_review': 0,
|
||||
})
|
||||
|
||||
review = _pdf_order_truth(categories=['unreadable_pdf'], status='needs_review')
|
||||
assert review_pdf_order_quality_gate([review], {
|
||||
'active_truth_lines': 0, 'deleted_truth_lines': 0,
|
||||
'active_lines_auto_released': 0, 'active_lines_misdeleted': 0,
|
||||
'high_risk_auto_released_fields': 0,
|
||||
'incorrect_high_risk_auto_released_fields': 0,
|
||||
'unreliable_truth_lines': 1, 'unreliable_lines_sent_to_review': 1,
|
||||
}).passed is False
|
||||
@@ -0,0 +1,69 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_html_layout.py
|
||||
|
||||
用途:验证 EML HTML DOM 表格可安全转换为统一逻辑布局,且不携带主动内容。
|
||||
依赖:eml_parse HTML 清洗、html_layout、布局契约。
|
||||
逻辑:覆盖脚本/属性清理、rowspan/colspan、空 cell 和无有效表格候选。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from email import policy
|
||||
from email.parser import BytesParser
|
||||
|
||||
from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate
|
||||
from app.services.shipping_notice.eml_parse import _extract_body_html_tables
|
||||
|
||||
|
||||
def test_eml_html_tables_are_sanitized_before_layout():
|
||||
"""正文表格只保留结构与跨度,脚本、样式、链接和图片均不得进入临时片段。"""
|
||||
message = BytesParser(policy=policy.default).parsebytes(
|
||||
b'MIME-Version: 1.0\r\nContent-Type: text/html; charset=utf-8\r\n\r\n'
|
||||
b'<html><body><table style="color:red">'
|
||||
b'<tr><th rowspan="2" onclick="BAD()"><a href="https://x">Part</a></th>'
|
||||
b'<th>Qty<img src="cid:x"><script>SECRET()</script></th></tr>'
|
||||
b'<tr><td>2</td></tr></table></body></html>'
|
||||
)
|
||||
|
||||
tables = _extract_body_html_tables(message)
|
||||
|
||||
assert len(tables) == 1
|
||||
assert 'rowspan="2"' in tables[0]
|
||||
assert 'SECRET' not in tables[0]
|
||||
assert 'onclick' not in tables[0]
|
||||
assert 'href' not in tables[0]
|
||||
assert '<img' not in tables[0]
|
||||
assert 'Part' in tables[0]
|
||||
|
||||
|
||||
def test_html_layout_preserves_dom_spans_with_logical_coordinates():
|
||||
"""DOM 合并格应转换为不重叠逻辑 bbox,整体因无浏览器像素证据保持 needs_review。"""
|
||||
layout = build_html_layout_candidate(
|
||||
document_id=12, content_hash='e' * 64,
|
||||
tables=[
|
||||
'<table><tr><th rowspan="2">Part</th><th>Qty</th></tr>'
|
||||
'<tr><td></td></tr></table>',
|
||||
],
|
||||
)
|
||||
|
||||
table = layout.pages[0].tables[0]
|
||||
assert layout.quality.status == 'needs_review'
|
||||
assert table.rows[0].cells[0].row_span == 2
|
||||
assert table.rows[1].cells[0].text == ''
|
||||
assert table.rows[1].cells[0].token_ids == []
|
||||
assert all(cell.source == 'html' for row in table.rows for cell in row.cells)
|
||||
assert {item.code for item in layout.quality.issues} == {'html_logical_coordinates_only'}
|
||||
|
||||
|
||||
def test_invalid_html_tables_return_valid_empty_needs_review_layout():
|
||||
"""全部坏表仍须返回合法一页候选和问题码,不能因零页面尺寸抛契约异常。"""
|
||||
layout = build_html_layout_candidate(
|
||||
document_id=13, content_hash='f' * 64, tables=['<div>not a table</div>'],
|
||||
)
|
||||
|
||||
assert layout.pages[0].width == 1
|
||||
assert layout.pages[0].height == 1
|
||||
assert layout.pages[0].tables == []
|
||||
assert {item.code for item in layout.quality.issues} == {
|
||||
'html_logical_coordinates_only', 'html_table_invalid', 'html_table_structure_missing',
|
||||
}
|
||||
@@ -127,6 +127,40 @@ def test_repeated_header_deleted_summary_and_empty_rows_are_not_data():
|
||||
assert all(not row.fields for row in result.rows)
|
||||
|
||||
|
||||
def test_exclusive_deleted_marker_marks_the_unique_previous_detail_line_deleted():
|
||||
"""独占删除标记紧邻唯一明细时归属上一行,避免该行流入订单 Candidate。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Part</th><th>Qty</th></tr>'
|
||||
'<tr><td>DELETED-PART</td><td>3</td></tr><tr><td>Item deleted</td><td></td></tr>'
|
||||
'<tr><td>ACTIVE-PART</td><td>4</td></tr></table>',
|
||||
_field('part_number', ['Part']),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert [row.role for row in result.rows] == ['deleted', 'deleted', 'data']
|
||||
assert result.rows[0].fields == []
|
||||
assert {field.field_code: field.value for field in result.rows[2].fields} == {
|
||||
'part_number': 'ACTIVE-PART', 'qty': 4,
|
||||
}
|
||||
|
||||
|
||||
def test_displaced_deleted_marker_never_deletes_the_following_positive_line():
|
||||
"""零数量删除行与后置标记竞争时,正数量行必须保留并通过问题码进入人工复核。"""
|
||||
result = _map(
|
||||
'<table><tr><th>Part</th><th>Qty</th></tr>'
|
||||
'<tr><td>ITEM-0010</td><td>0</td></tr><tr><td>ITEM-0020</td><td>30</td></tr>'
|
||||
'<tr><td>Item deleted</td><td></td></tr></table>',
|
||||
_field('part_number', ['Part']),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert [row.role for row in result.rows] == ['deleted', 'data', 'deleted']
|
||||
assert {field.field_code: field.value for field in result.rows[1].fields} == {
|
||||
'part_number': 'ITEM-0020', 'qty': 30,
|
||||
}
|
||||
assert 'deletion_marker_target_ambiguous' in result.issues
|
||||
|
||||
|
||||
def test_explicit_zero_quantity_row_is_deleted_without_field_candidates():
|
||||
"""冻结 Qty 列明确为零的订单行必须删除,不能作为不完整 Candidate 流入后续。"""
|
||||
result = _map(
|
||||
@@ -298,6 +332,20 @@ def test_reservation_validator_rejects_line_number_shape():
|
||||
assert [(field.field_code, field.value) for field in result.rows[0].fields] == [('qty', 1)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reservation_id', ['20004', '2000484577'])
|
||||
def test_reservation_validator_keeps_valid_non_line_number_shapes(reservation_id):
|
||||
"""合法五位/十位预约号不能因项次防呆规则被误删。"""
|
||||
result = _map(
|
||||
f'<table><tr><th>Reservation ID</th><th>Qty</th></tr><tr><td>{reservation_id}</td><td>1</td></tr></table>',
|
||||
_field('reservation_id', ['Reservation ID'], normalizer_key='reservation_id'),
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert [(field.field_code, field.value) for field in result.rows[0].fields] == [
|
||||
('reservation_id', reservation_id), ('qty', 1),
|
||||
]
|
||||
|
||||
|
||||
def test_nested_table_rows_do_not_pollute_parent_grid():
|
||||
"""主表单元格内的嵌套展示表格不得被重复解析成主表数据行。"""
|
||||
grid = parse_html_grid(
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_job.py
|
||||
|
||||
用途:验证独立布局 Job 从对象存储读取附件、按 lease 收口并在失败时同步版本状态。
|
||||
依赖:shipping_document_layout handler、lifecycle、通用 Job queue。
|
||||
逻辑:构造 queued 版本后模拟 Worker claim;成功更新 current,失败重排不得留下 running lease。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers.shipping_document_layout import LAYOUT_JOB_ERROR, run_shipping_document_layout
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_layout_version
|
||||
from tests.test_shipping_document_layout_lifecycle import _document, _snapshot
|
||||
|
||||
|
||||
def _running_layout_job(app):
|
||||
"""创建布局版本并模拟通用队列已领取该 Job。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
document = _document()
|
||||
version = schedule_layout_version(document, force=True)
|
||||
job = db.session.get(Job, version.job_id)
|
||||
job.status = 'running'
|
||||
job.attempts = 1
|
||||
job.max_attempts = 3
|
||||
db.session.commit()
|
||||
return document, version, job
|
||||
|
||||
|
||||
def test_layout_job_completes_version_and_updates_document_current(app):
|
||||
"""成功 Provider 结果必须冻结 checksum 并成为 Document 当前布局。"""
|
||||
with app.app_context():
|
||||
document, version, job = _running_layout_job(app)
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_document_layout.read_asset_bytes', return_value=b'%PDF',
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot',
|
||||
return_value=_snapshot(marker='worker'),
|
||||
):
|
||||
run_shipping_document_layout(
|
||||
JobContext(config=dict(app.config), logger=None, extras={}),
|
||||
{'job_id': job.id},
|
||||
)
|
||||
|
||||
db.session.refresh(version)
|
||||
db.session.refresh(document)
|
||||
db.session.refresh(job)
|
||||
assert version.status == 'ready'
|
||||
assert version.payload_checksum
|
||||
assert version.lease_token is None
|
||||
assert document.current_layout_version_id == version.id
|
||||
assert job.status == 'success'
|
||||
|
||||
|
||||
def test_layout_job_failure_requeues_version_and_clears_lease(app):
|
||||
"""可重试异常必须让 Job/版本同时回 queued,禁止版本永久 running。"""
|
||||
with app.app_context():
|
||||
_document_row, version, job = _running_layout_job(app)
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_document_layout.read_asset_bytes',
|
||||
side_effect=RuntimeError('temporary storage failure'),
|
||||
):
|
||||
with pytest.raises(RuntimeError, match='temporary storage failure'):
|
||||
run_shipping_document_layout(
|
||||
JobContext(config=dict(app.config), logger=None, extras={}),
|
||||
{'job_id': job.id},
|
||||
)
|
||||
|
||||
db.session.refresh(version)
|
||||
db.session.refresh(job)
|
||||
assert job.status == 'queued'
|
||||
assert version.status == 'queued'
|
||||
assert version.lease_token is None
|
||||
assert job.error_message == LAYOUT_JOB_ERROR
|
||||
|
||||
|
||||
def test_layout_job_exhaustion_fails_version_without_leaking_provider_error(app):
|
||||
"""最后一次失败必须同步终结布局版本,Job 只保留稳定错误码而非内部异常。"""
|
||||
with app.app_context():
|
||||
_document_row, version, job = _running_layout_job(app)
|
||||
job.max_attempts = 1
|
||||
db.session.commit()
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_document_layout.read_asset_bytes',
|
||||
side_effect=RuntimeError('secret storage endpoint failed'),
|
||||
):
|
||||
with pytest.raises(RuntimeError, match='secret storage endpoint failed'):
|
||||
run_shipping_document_layout(
|
||||
JobContext(config=dict(app.config), logger=None, extras={}),
|
||||
{'job_id': job.id},
|
||||
)
|
||||
|
||||
db.session.refresh(version)
|
||||
db.session.refresh(job)
|
||||
assert job.status == 'failed'
|
||||
assert job.error_message == LAYOUT_JOB_ERROR
|
||||
assert 'secret storage endpoint' not in str(job.error_message)
|
||||
assert version.status == 'failed'
|
||||
assert version.lease_token is None
|
||||
assert 'shipping_document_layout_job_exhausted' in version.issues_json
|
||||
@@ -0,0 +1,209 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_lifecycle.py
|
||||
|
||||
用途:验证 L1 版面快照 checksum、版本幂等、容量门禁和当前成功版本保护。
|
||||
依赖:ShippingNoticeDocument/LayoutVersion、document_layout.lifecycle、Flask 测试库。
|
||||
逻辑:相同快照复用;新失败/超限版本保留审计但不覆盖旧成功引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import Job, ShippingDocumentLayoutVersion, ShippingNoticeDocument, ShippingNoticeIntake, FileAsset, User
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
canonical_layout_payload,
|
||||
claim_layout_version,
|
||||
complete_layout_version,
|
||||
current_layout_snapshot,
|
||||
record_inline_layout_snapshot,
|
||||
schedule_layout_version,
|
||||
schedule_document_layouts,
|
||||
sync_layout_after_job_recovery,
|
||||
)
|
||||
|
||||
|
||||
def _document() -> ShippingNoticeDocument:
|
||||
"""创建带稳定内容哈希的最小附件 Document。"""
|
||||
user = User(username='layout-owner', email='layout-owner@example.com', role='user', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no='FA-LAYOUT-L1', owner_user_id=user.id, original_filename='sample.pdf',
|
||||
storage_provider='minio', storage_bucket='test', storage_key='sample.pdf',
|
||||
content_hash='a' * 64, file_size=10, mime_type='application/pdf',
|
||||
upload_status='ready', lifecycle_status='referenced',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-LAYOUT-L1', asset_id=asset.id, user_id=user.id,
|
||||
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id, asset_id=asset.id, document_type='attachment',
|
||||
attachment_key='sample.pdf', filename='sample.pdf', content_hash='a' * 64,
|
||||
classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
return document
|
||||
|
||||
|
||||
def _snapshot(*, status: str = 'ready', marker: str = 'v1') -> dict:
|
||||
"""构造不含正文的紧凑布局快照。"""
|
||||
return {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru', 'provider_version': '3.1.14', 'backend': 'pipeline',
|
||||
'status': status, 'tables': [], 'issues': [], 'marker': marker,
|
||||
}
|
||||
|
||||
|
||||
def test_layout_snapshot_checksum_and_idempotent_current_version(app):
|
||||
"""相同内容/parser/checksum 重放不得新增版本,成功快照应成为唯一当前引用。"""
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
checksum, size = canonical_layout_payload(_snapshot())
|
||||
first = record_inline_layout_snapshot(document, _snapshot())
|
||||
replay = record_inline_layout_snapshot(document, _snapshot())
|
||||
db.session.commit()
|
||||
|
||||
assert first.id == replay.id
|
||||
assert first.payload_checksum == checksum
|
||||
assert first.payload_size_bytes == size
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 1
|
||||
assert document.current_layout_version_id == first.id
|
||||
assert current_layout_snapshot(document)['marker'] == 'v1'
|
||||
|
||||
|
||||
def test_failed_or_oversized_layout_does_not_replace_last_good_version(app):
|
||||
"""失败/超限版本必须可审计,但绝不能覆盖 Document 上一次成功布局。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 200
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
good = record_inline_layout_snapshot(document, _snapshot())
|
||||
failed = record_inline_layout_snapshot(document, _snapshot(status='failed', marker='failed'))
|
||||
oversized = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(marker='large'), 'tables': [{'html': 'X' * 500}],
|
||||
})
|
||||
db.session.commit()
|
||||
|
||||
assert failed.status == 'failed'
|
||||
assert oversized.status == 'failed'
|
||||
assert oversized.payload_json is None
|
||||
assert 'shipping_document_layout_snapshot_size_exceeded' in oversized.issues_json
|
||||
assert document.current_layout_version_id == good.id
|
||||
assert current_layout_snapshot(document)['marker'] == 'v1'
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 3
|
||||
|
||||
|
||||
def test_layout_schedule_is_idempotent_and_force_creates_next_version(app):
|
||||
"""同 parser 成功版本默认复用;显式重解析创建下一 queued 版本及独立 Job。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
ready = record_inline_layout_snapshot(document, _snapshot())
|
||||
reused = schedule_layout_version(document)
|
||||
forced = schedule_layout_version(document, force=True)
|
||||
db.session.commit()
|
||||
|
||||
assert reused.id == ready.id
|
||||
assert forced.id != ready.id
|
||||
assert forced.version == 2
|
||||
assert forced.status == 'queued'
|
||||
assert forced.job_id is not None
|
||||
job = db.session.get(Job, forced.job_id)
|
||||
assert job.job_type == 'shipping_document_layout'
|
||||
assert job.payload_json == {'layout_version_id': forced.id}
|
||||
|
||||
|
||||
def test_layout_parser_revision_change_creates_new_version_without_force(app):
|
||||
"""运维提升 parser revision 后不得复用旧 Provider/模型结果。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
old = record_inline_layout_snapshot(
|
||||
document, _snapshot(),
|
||||
parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:v1',
|
||||
)
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_PARSER_REVISION'] = 'v2'
|
||||
new = schedule_layout_version(document)
|
||||
db.session.commit()
|
||||
|
||||
assert new.id != old.id
|
||||
assert new.version == 2
|
||||
assert new.parser_key.endswith(':v2')
|
||||
|
||||
|
||||
def test_layout_recovery_invalidates_old_lease_and_preserves_good_current(app):
|
||||
"""Job 回收后版本回 queued 并清 lease,旧 Worker 结果不得覆盖当前成功版本。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
ready = record_inline_layout_snapshot(document, _snapshot())
|
||||
pending = schedule_layout_version(document, force=True)
|
||||
job = db.session.get(Job, pending.job_id)
|
||||
job.status = 'running'
|
||||
job.attempts = 1
|
||||
db.session.commit()
|
||||
claimed = claim_layout_version(pending.id, job_id=job.id, owned_attempt=1)
|
||||
assert claimed is not None
|
||||
_version, old_lease = claimed
|
||||
|
||||
job.status = 'queued'
|
||||
sync_layout_after_job_recovery(job)
|
||||
db.session.commit()
|
||||
|
||||
assert pending.status == 'queued'
|
||||
assert pending.lease_token is None
|
||||
assert complete_layout_version(
|
||||
pending.id, lease_token=old_lease, snapshot=_snapshot(marker='stale'),
|
||||
) is False
|
||||
db.session.refresh(document)
|
||||
assert document.current_layout_version_id == ready.id
|
||||
|
||||
|
||||
def test_layout_document_budget_creates_unsupported_audit_versions(app):
|
||||
"""超过单 Intake 配额的支持附件必须有 unsupported 审计,不能静默跳过。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE'] = 1
|
||||
with app.app_context():
|
||||
first = _document()
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=first.intake_id, asset_id=first.asset_id, document_type='attachment',
|
||||
attachment_key='second.pdf', filename='second.pdf', content_hash='b' * 64,
|
||||
classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
text = ShippingNoticeDocument(
|
||||
intake_id=first.intake_id, asset_id=first.asset_id, document_type='attachment',
|
||||
attachment_key='notes.txt', filename='notes.txt', content_hash='c' * 64,
|
||||
classification='order_notice', parse_status='parsed',
|
||||
)
|
||||
db.session.add_all([second, text])
|
||||
db.session.flush()
|
||||
|
||||
versions = schedule_document_layouts([first, text, second])
|
||||
db.session.commit()
|
||||
|
||||
assert len(versions) == 2
|
||||
assert versions[0].status == 'queued'
|
||||
assert versions[1].status == 'unsupported'
|
||||
assert versions[1].issues_json == ['mineru_intake_document_budget_exceeded']
|
||||
assert ShippingDocumentLayoutVersion.query.filter_by(document_id=text.id).count() == 0
|
||||
|
||||
|
||||
def test_deleting_document_cascades_layout_versions(app):
|
||||
"""Document 删除必须先解除 current 引用,并级联清理其全部布局版本。"""
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
version = record_inline_layout_snapshot(document, _snapshot())
|
||||
document_id = document.id
|
||||
version_id = version.id
|
||||
db.session.commit()
|
||||
|
||||
db.session.delete(document)
|
||||
db.session.commit()
|
||||
|
||||
assert db.session.get(ShippingNoticeDocument, document_id) is None
|
||||
assert db.session.get(ShippingDocumentLayoutVersion, version_id) is None
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_lifecycle_migration.py
|
||||
|
||||
用途:验证 L1 布局生命周期迁移回填旧快照、建立版本/活动唯一约束并可完整降级。
|
||||
依赖:Alembic Operations、SQLite 内存库、a69f8091a2b5 迁移。
|
||||
逻辑:构造上一 revision 最小表,升级后校验 checksum/current FK,降级恢复原 JSON。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import json
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_document_layout_lifecycle_migration_round_trip(monkeypatch):
|
||||
"""旧布局 JSON 必须无损迁入版本表,活动唯一索引和 downgrade 恢复均生效。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a69f8091a2b5_add_document_layout_lifecycle',
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'jobs', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('domain', sa.String(64)), sa.Column('job_type', sa.String(64)),
|
||||
sa.Column('business_ref', sa.String(128)), sa.Column('status', sa.String(32)),
|
||||
)
|
||||
documents = sa.Table(
|
||||
'shipping_notice_documents', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('content_hash', sa.String(64)),
|
||||
sa.Column('layout_snapshot_json', sa.JSON()),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
payload = {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru', 'provider_version': '3.1.14', 'backend': 'pipeline',
|
||||
'status': 'ready', 'tables': [], 'issues': ['mineru_cell_coordinates_missing'],
|
||||
}
|
||||
connection.execute(documents.insert().values(
|
||||
id=1, content_hash='a' * 64, layout_snapshot_json=payload,
|
||||
))
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_document_layout_versions' in inspector.get_table_names()
|
||||
assert 'uq_jobs_shipping_document_layout_active_ref' in {
|
||||
item['name'] for item in inspector.get_indexes('jobs')
|
||||
}
|
||||
columns = {item['name'] for item in inspector.get_columns('shipping_notice_documents')}
|
||||
assert 'current_layout_version_id' in columns
|
||||
assert 'layout_snapshot_json' not in columns
|
||||
versions = sa.Table(
|
||||
'shipping_document_layout_versions', sa.MetaData(), autoload_with=connection,
|
||||
)
|
||||
version = connection.execute(sa.select(versions)).mappings().one()
|
||||
assert version['status'] == 'ready'
|
||||
assert version['parser_key'].endswith(':legacy')
|
||||
assert version['payload_json'] == payload
|
||||
assert len(version['payload_checksum']) == 64
|
||||
current_id = connection.execute(sa.text(
|
||||
'SELECT current_layout_version_id FROM shipping_notice_documents WHERE id = 1',
|
||||
)).scalar_one()
|
||||
assert current_id == version['id']
|
||||
|
||||
duplicate = connection.begin_nested()
|
||||
with pytest.raises(sa.exc.IntegrityError):
|
||||
connection.execute(versions.insert().values(
|
||||
document_id=1, version=2, status='queued', source_content_hash='a' * 64,
|
||||
parser_key='next', parser_name='mineru', contract_version='v1', issues_json=[],
|
||||
payload_size_bytes=0, attempt_count=0,
|
||||
created_at=sa.func.current_timestamp(), updated_at=sa.func.current_timestamp(),
|
||||
))
|
||||
connection.execute(versions.insert().values(
|
||||
document_id=1, version=3, status='running', source_content_hash='a' * 64,
|
||||
parser_key='next-2', parser_name='mineru', contract_version='v1', issues_json=[],
|
||||
payload_size_bytes=0, attempt_count=0,
|
||||
created_at=sa.func.current_timestamp(), updated_at=sa.func.current_timestamp(),
|
||||
))
|
||||
duplicate.rollback()
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_document_layout_versions' not in inspector.get_table_names()
|
||||
assert 'uq_jobs_shipping_document_layout_active_ref' not in {
|
||||
item['name'] for item in inspector.get_indexes('jobs')
|
||||
}
|
||||
columns = {item['name'] for item in inspector.get_columns('shipping_notice_documents')}
|
||||
assert 'layout_snapshot_json' in columns
|
||||
restored = connection.execute(sa.text(
|
||||
'SELECT layout_snapshot_json FROM shipping_notice_documents WHERE id = 1',
|
||||
)).scalar_one()
|
||||
assert (json.loads(restored) if isinstance(restored, str) else restored) == payload
|
||||
@@ -108,6 +108,26 @@ class _FakeSession:
|
||||
return self.response
|
||||
|
||||
|
||||
class _AsyncSession:
|
||||
"""模拟 `/tasks` 提交、状态轮询和结果读取。"""
|
||||
|
||||
def __init__(self, result: dict):
|
||||
self.result = result
|
||||
self.calls: list[str] = []
|
||||
|
||||
def post(self, url: str, **_kwargs):
|
||||
"""返回异步任务 ID。"""
|
||||
self.calls.append(url)
|
||||
return _FakeResponse({'task_id': 'task-async'}, status_code=202)
|
||||
|
||||
def get(self, url: str, **_kwargs):
|
||||
"""第一次读取终态,结果接口返回完整 MinerU payload。"""
|
||||
self.calls.append(url)
|
||||
if url.endswith('/result'):
|
||||
return _FakeResponse(self.result)
|
||||
return _FakeResponse({'task_id': 'task-async', 'status': 'completed'})
|
||||
|
||||
|
||||
def test_mineru_candidate_preserves_table_structure_but_blocks_cell_evidence():
|
||||
"""只有整表 bbox + HTML 时必须保留行列候选并阻止确定性单元格证据。"""
|
||||
candidate = parse_mineru_candidate(_mineru_payload())
|
||||
@@ -188,6 +208,23 @@ def test_mineru_client_sends_bounded_single_file_request():
|
||||
assert response.closed is True
|
||||
|
||||
|
||||
def test_mineru_async_client_submits_polls_and_reads_result_without_long_post():
|
||||
"""生产调用应使用 `/tasks` 短提交,再通过状态和结果接口获取 completed payload。"""
|
||||
session = _AsyncSession(_mineru_payload())
|
||||
client = MinerUClient(MinerUClientConfig(
|
||||
base_url='http://mineru.internal:8100', poll_interval_seconds=0.01,
|
||||
), session=session)
|
||||
|
||||
payload = client.parse_file_async(filename='fixture.pdf', content=b'%PDF')
|
||||
|
||||
assert payload['status'] == 'completed'
|
||||
assert session.calls == [
|
||||
'http://mineru.internal:8100/tasks',
|
||||
'http://mineru.internal:8100/tasks/task-async',
|
||||
'http://mineru.internal:8100/tasks/task-async/result',
|
||||
]
|
||||
|
||||
|
||||
def test_mineru_client_rejects_unsupported_empty_and_large_files_before_network():
|
||||
"""文件类型、空内容和上传上限必须在 HTTP 请求前拒绝。"""
|
||||
session = _FakeSession(_FakeResponse(_mineru_payload()))
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_native_pdf.py
|
||||
|
||||
用途:验证原生 PDF 字符证据与 MinerU HTML 组合为保守、可追溯的 layout.v1 候选。
|
||||
依赖:native_pdf、MinerU candidate、布局契约和 mock PDF 页面。
|
||||
逻辑:覆盖唯一文本成功、重复文本拒绝、扫描无文本和 runtime 内嵌候选;任何结果都不得自动 accepted。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
from io import BytesIO
|
||||
|
||||
import numpy as np
|
||||
from pypdf import PdfWriter
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.mineru import (
|
||||
MinerUCapabilityReport,
|
||||
MinerUPageCandidate,
|
||||
MinerUParseCandidate,
|
||||
MinerUTableCandidate,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
NativePdfPage,
|
||||
build_native_pdf_layout_candidate,
|
||||
extract_native_pdf_pages,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import (
|
||||
OcrCellEvidence,
|
||||
OcrLine,
|
||||
OcrTableEvidence,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.runtime import build_mineru_table_snapshot
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
|
||||
|
||||
|
||||
def _candidate(html: str) -> MinerUParseCandidate:
|
||||
"""构造单页 MinerU HTML 表格候选,不提供 Provider 原生 cell bbox。"""
|
||||
return MinerUParseCandidate(
|
||||
provider_version='3.1.14', backend='pipeline',
|
||||
pages=[MinerUPageCandidate(
|
||||
page_no=1, width=200, height=100,
|
||||
tables=[MinerUTableCandidate(
|
||||
candidate_id='table-1', page_no=1,
|
||||
bbox=LayoutBBox(x0=5, y0=5, x1=190, y1=80),
|
||||
normalized_bbox=LayoutBBox(x0=.025, y0=.05, x1=.95, y1=.8),
|
||||
html=html, row_count=1, cell_count=2,
|
||||
has_rowspan=False, has_colspan=False,
|
||||
)],
|
||||
)],
|
||||
capability=MinerUCapabilityReport(
|
||||
provider_version='3.1.14', backend='pipeline', page_count=1,
|
||||
page_size_count=1, bbox_object_count=1, html_table_count=1,
|
||||
html_row_count=1, html_cell_count=2, text_block_count=0,
|
||||
cell_bbox_count=0, has_page_coordinates=True, has_table_structure=True,
|
||||
has_cell_coordinates=False, deterministic_cell_evidence_ready=False,
|
||||
issues=['mineru_cell_coordinates_missing'],
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _page(text: str) -> NativePdfPage:
|
||||
"""为单行文本构造从左到右且位于表内的 PDF glyph 页面。"""
|
||||
characters = [
|
||||
PositionedCharacter(
|
||||
text=char, source_index=index,
|
||||
bbox=LayoutBBox(x0=10 + index * 8, y0=20, x1=16 + index * 8, y1=30),
|
||||
)
|
||||
for index, char in enumerate(text)
|
||||
]
|
||||
return NativePdfPage(
|
||||
page_no=1, width=200, height=100, rotation=0,
|
||||
characters=characters, image=np.full((200, 400), 255, dtype=np.uint8),
|
||||
)
|
||||
|
||||
|
||||
def test_native_pdf_unique_text_builds_traceable_needs_review_layout():
|
||||
"""唯一文本可形成 cell/token 引用,但人工真值延期时整体仍必须 needs_review。"""
|
||||
mineru = _candidate('<table><tr><th>Part</th><th>Qty</th></tr></table>')
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
return_value=[_page('PartQty')],
|
||||
):
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=7, content_hash='a' * 64, content=b'%PDF', mineru=mineru,
|
||||
)
|
||||
|
||||
assert layout.quality.status == 'needs_review'
|
||||
assert layout.pages[0].tables[0].status == 'needs_review'
|
||||
assert len(layout.pages[0].tokens) == 7
|
||||
cells = layout.pages[0].tables[0].rows[0].cells
|
||||
assert len(cells) == 2
|
||||
assert all(cell.token_ids for cell in cells)
|
||||
assert {item.code for item in layout.quality.issues} >= {
|
||||
'document_cell_truth_deferred', 'native_pdf_cells_from_unique_text_candidate',
|
||||
}
|
||||
|
||||
|
||||
def test_native_pdf_repeated_text_does_not_create_cells():
|
||||
"""重复表头不得按 HTML 顺序分配 glyph;候选保留阻断问题且没有表。"""
|
||||
mineru = _candidate('<table><tr><th>Qty</th><th>Qty</th></tr></table>')
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
return_value=[_page('QtyQty')],
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.reconstruct_opencv_table_geometry',
|
||||
) as opencv:
|
||||
opencv.return_value.ready = False
|
||||
opencv.return_value.issues = ['opencv_table_grid_not_detected']
|
||||
opencv.return_value.cells = []
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=8, content_hash='b' * 64, content=b'%PDF', mineru=mineru,
|
||||
)
|
||||
|
||||
assert layout.pages[0].tables == []
|
||||
codes = {item.code for item in layout.quality.issues}
|
||||
assert 'text_cell_alignment_text_not_unique' in codes
|
||||
assert 'native_pdf_no_resolved_tables' in codes
|
||||
|
||||
|
||||
def test_runtime_embeds_layout_candidate_without_changing_ready_snapshot(app):
|
||||
"""PDF Job 可保存 layout.v1 候选,同时维持现有 Profile 使用的 ready 表格快照。"""
|
||||
app.config.update(
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
|
||||
)
|
||||
mineru = _candidate('<table><tr><th>Part</th><th>Qty</th></tr></table>')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
|
||||
return_value={'status': 'completed'},
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
|
||||
return_value=mineru,
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
return_value=[_page('PartQty')],
|
||||
):
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename='order.pdf', content=b'%PDF', document_id=9, content_hash='c' * 64,
|
||||
)
|
||||
|
||||
assert snapshot['status'] == 'ready'
|
||||
assert snapshot['layout_candidate']['schema_version'] == 'shipping_document_layout.v1'
|
||||
assert snapshot['layout_candidate']['quality']['status'] == 'needs_review'
|
||||
assert 'PRIVATE' not in repr(snapshot)
|
||||
|
||||
|
||||
def test_runtime_native_pdf_failure_keeps_mineru_table_snapshot(app):
|
||||
"""PDFium 候选失败只记录问题码,不得丢弃已成功取得的 MinerU HTML 表格。"""
|
||||
app.config.update(
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
|
||||
)
|
||||
mineru = _candidate('<table><tr><th>Part</th><th>Qty</th></tr></table>')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
|
||||
return_value={'status': 'completed'},
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
|
||||
return_value=mineru,
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_layout_candidate',
|
||||
side_effect=RuntimeError('broken pdf'),
|
||||
):
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename='order.pdf', content=b'%PDF', document_id=9, content_hash='c' * 64,
|
||||
)
|
||||
|
||||
assert snapshot['status'] == 'ready'
|
||||
assert len(snapshot['tables']) == 1
|
||||
assert 'layout_candidate' not in snapshot
|
||||
assert 'native_pdf_layout_candidate_invalid' in snapshot['issues']
|
||||
|
||||
|
||||
def test_blank_pdf_has_page_geometry_without_fake_text_or_cells():
|
||||
"""真实无文本 PDF 只能提供页面尺寸,禁止生成虚构 token 或表格单元格。"""
|
||||
output = BytesIO()
|
||||
writer = PdfWriter()
|
||||
writer.add_blank_page(width=200, height=100)
|
||||
writer.write(output)
|
||||
|
||||
pages = extract_native_pdf_pages(output.getvalue(), render_scale=1)
|
||||
|
||||
assert len(pages) == 1
|
||||
assert pages[0].width == 200
|
||||
assert pages[0].height == 100
|
||||
assert pages[0].characters == []
|
||||
|
||||
|
||||
def test_bad_table_is_isolated_from_other_native_pdf_tables():
|
||||
"""一张越界坏表不得抹除同页另一张可追溯表,问题应定位到坏表。"""
|
||||
mineru = _candidate('<table><tr><th>Part</th><th>Qty</th></tr></table>')
|
||||
good = mineru.pages[0].tables[0]
|
||||
bad = good.model_copy(update={
|
||||
'candidate_id': 'table-bad',
|
||||
'bbox': LayoutBBox(x0=5, y0=5, x1=250, y1=80),
|
||||
})
|
||||
mineru.pages[0].tables = [good, bad]
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
return_value=[_page('PartQty')],
|
||||
):
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=10, content_hash='d' * 64, content=b'%PDF', mineru=mineru,
|
||||
)
|
||||
|
||||
assert len(layout.pages[0].tables) == 1
|
||||
assert any(
|
||||
item.code == 'native_pdf_table_candidate_invalid' and item.table_id == 'table-bad'
|
||||
for item in layout.quality.issues
|
||||
)
|
||||
|
||||
|
||||
def test_scanned_pdf_uses_ocr_tokens_only_after_grid_evidence():
|
||||
"""无原生字符页只有在 OCR+网格门禁 ready 时才能生成 source=ocr 的 token/cell。"""
|
||||
mineru = _candidate('<table><tr><th>Part</th><th>Qty</th></tr></table>')
|
||||
page = NativePdfPage(
|
||||
page_no=1, width=200, height=100, rotation=0, characters=[],
|
||||
image=np.full((200, 400), 255, dtype=np.uint8),
|
||||
)
|
||||
grid_cell_ids = ['table-1:r0:c0', 'table-1:r0:c1']
|
||||
evidence = OcrTableEvidence(
|
||||
ready=True,
|
||||
lines=[
|
||||
OcrLine(text='Part', bbox=LayoutBBox(x0=10, y0=10, x1=60, y1=30), confidence=.99),
|
||||
OcrLine(text='Qty', bbox=LayoutBBox(x0=110, y0=10, x1=150, y1=30), confidence=.98),
|
||||
],
|
||||
cells=[
|
||||
OcrCellEvidence(
|
||||
cell_id=grid_cell_ids[0], bbox=LayoutBBox(x0=5, y0=5, x1=100, y1=40),
|
||||
line_indices=[0],
|
||||
),
|
||||
OcrCellEvidence(
|
||||
cell_id=grid_cell_ids[1], bbox=LayoutBBox(x0=100, y0=5, x1=190, y1=40),
|
||||
line_indices=[1],
|
||||
),
|
||||
],
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
return_value=[page],
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.reconstruct_opencv_table_geometry',
|
||||
) as geometry, patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.validate_opencv_cell_text',
|
||||
) as validation, patch(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.build_ocr_table_evidence',
|
||||
return_value=evidence,
|
||||
):
|
||||
geometry.return_value.ready = False
|
||||
geometry.return_value.issues = ['opencv_table_grid_not_detected']
|
||||
geometry.return_value.cells = []
|
||||
validation.return_value.accepted = False
|
||||
validation.return_value.issues = ['opencv_table_geometry_not_ready']
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=14, content_hash='1' * 64, content=b'%PDF', mineru=mineru,
|
||||
)
|
||||
|
||||
cells = layout.pages[0].tables[0].rows[0].cells
|
||||
assert all(cell.source == 'ocr' for cell in cells)
|
||||
assert all(cell.token_ids for cell in cells)
|
||||
assert all(token.source == 'ocr' for token in layout.pages[0].tokens)
|
||||
assert 'ocr_pdf_cells_from_grid_candidate' in {item.code for item in layout.quality.issues}
|
||||
@@ -0,0 +1,99 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_ocr_pdf.py
|
||||
|
||||
用途:验证 RapidOCR 多边形坐标适配和扫描表三重门禁。
|
||||
依赖:ocr_pdf、OpenCV 几何结果、HTML 网格。
|
||||
逻辑:覆盖坐标缩放、低置信过滤、引擎不可用与完整 cell 文本验收。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import (
|
||||
OcrLine,
|
||||
build_ocr_table_evidence,
|
||||
extract_ocr_lines,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.opencv_table import (
|
||||
OpenCVCellGeometry,
|
||||
OpenCVTableGeometryResult,
|
||||
)
|
||||
|
||||
|
||||
def test_rapidocr_polygon_is_scaled_to_pdf_page_and_filters_low_confidence():
|
||||
"""OCR 像素框必须按渲染图与 PDF 页面比例转换,低置信结果不得保留。"""
|
||||
image = np.zeros((200, 400, 3), dtype=np.uint8)
|
||||
response = [
|
||||
[[[40, 20], [120, 20], [120, 60], [40, 60]], 'Part', 0.95],
|
||||
[[[200, 20], [240, 20], [240, 60], [200, 60]], 'bad', 0.4],
|
||||
]
|
||||
with patch('app.services.shipping_notice.document_layout.ocr_pdf._ocr_engine') as engine:
|
||||
engine.return_value.return_value = (response, 0.1)
|
||||
lines = extract_ocr_lines(image, page_width=200, page_height=100)
|
||||
|
||||
assert len(lines) == 1
|
||||
assert lines[0].text == 'Part'
|
||||
assert lines[0].bbox.model_dump() == {'x0': 20.0, 'y0': 10.0, 'x1': 60.0, 'y1': 30.0}
|
||||
|
||||
|
||||
def test_ocr_table_requires_geometry_and_all_cell_text():
|
||||
"""扫描表仅在网格 ready 且全部非空 cell OCR 文本一致时输出 cell evidence。"""
|
||||
grid = parse_html_grid(
|
||||
'<table><tr><th>Part</th><th>Qty</th></tr></table>', table_id='ocr',
|
||||
)
|
||||
geometry = OpenCVTableGeometryResult(
|
||||
ready=True, consensus_count=2, row_count=1, column_count=2,
|
||||
cells=[
|
||||
OpenCVCellGeometry(
|
||||
cell_id=grid.cells[0].cell_id, row_index=0, column_index=0,
|
||||
row_span=1, column_span=1,
|
||||
bbox=LayoutBBox(x0=0, y0=0, x1=100, y1=50),
|
||||
normalized_bbox=LayoutBBox(x0=0, y0=0, x1=.5, y1=.5),
|
||||
),
|
||||
OpenCVCellGeometry(
|
||||
cell_id=grid.cells[1].cell_id, row_index=0, column_index=1,
|
||||
row_span=1, column_span=1,
|
||||
bbox=LayoutBBox(x0=100, y0=0, x1=200, y1=50),
|
||||
normalized_bbox=LayoutBBox(x0=.5, y0=0, x1=1, y1=.5),
|
||||
),
|
||||
],
|
||||
)
|
||||
lines = [
|
||||
OcrLine(text='Part', bbox=LayoutBBox(x0=10, y0=10, x1=50, y1=30), confidence=.99),
|
||||
OcrLine(text='Qty', bbox=LayoutBBox(x0=120, y0=10, x1=150, y1=30), confidence=.98),
|
||||
]
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines', return_value=lines,
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf.reconstruct_opencv_table_geometry',
|
||||
return_value=geometry,
|
||||
):
|
||||
result = build_ocr_table_evidence(
|
||||
image=np.zeros((100, 200), dtype=np.uint8), page_width=200, page_height=100,
|
||||
table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=50), grid=grid,
|
||||
)
|
||||
|
||||
assert result.ready is True
|
||||
assert [item.line_indices for item in result.cells] == [[0], [1]]
|
||||
|
||||
|
||||
def test_ocr_engine_failure_is_safe_unsupported_candidate():
|
||||
"""OCR 引擎缺失或异常必须返回机器问题码,不得抛出或生成 cell。"""
|
||||
grid = parse_html_grid('<table><tr><td>A</td></tr></table>', table_id='fail')
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines',
|
||||
side_effect=RuntimeError('model missing'),
|
||||
):
|
||||
result = build_ocr_table_evidence(
|
||||
image=np.zeros((100, 100), dtype=np.uint8), page_width=100, page_height=100,
|
||||
table_bbox=LayoutBBox(x0=0, y0=0, x1=100, y1=100), grid=grid,
|
||||
)
|
||||
|
||||
assert result.ready is False
|
||||
assert result.cells == []
|
||||
assert result.issues == ['ocr_engine_unavailable']
|
||||
@@ -0,0 +1,152 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_runtime.py
|
||||
|
||||
用途:验证 Intake 阶段 MinerU 紧凑文本/表格快照、降级行为和容量门禁。
|
||||
依赖:document_layout.runtime/mineru 构造候选、Flask 测试配置。
|
||||
逻辑:Mock 客户端避免真实网络;只允许受预算文本块、表格 HTML 和能力摘要进入快照,原响应不得持久化。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.mineru import (
|
||||
MinerUCapabilityReport,
|
||||
MinerUPageCandidate,
|
||||
MinerUParseCandidate,
|
||||
MinerUTableCandidate,
|
||||
MinerUTextCandidate,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.runtime import (
|
||||
attach_mineru_layout_snapshots,
|
||||
build_mineru_table_snapshot,
|
||||
)
|
||||
|
||||
|
||||
def _candidate() -> MinerUParseCandidate:
|
||||
"""构造包含文本与表格的 MinerU 候选,验证紧凑快照内容。"""
|
||||
return MinerUParseCandidate(
|
||||
task_id='task-private',
|
||||
provider_version='3.1.14',
|
||||
backend='pipeline',
|
||||
pages=[MinerUPageCandidate(
|
||||
page_no=1,
|
||||
width=100,
|
||||
height=200,
|
||||
text_blocks=[MinerUTextCandidate(
|
||||
candidate_id='text-1', page_no=1,
|
||||
bbox=LayoutBBox(x0=1, y0=1, x1=10, y1=10),
|
||||
normalized_bbox=LayoutBBox(x0=.01, y0=.01, x1=.1, y1=.05),
|
||||
text='PRIVATE-NON-TABLE-TEXT', content_type='text',
|
||||
)],
|
||||
tables=[MinerUTableCandidate(
|
||||
candidate_id='table-1', page_no=1,
|
||||
bbox=LayoutBBox(x0=1, y0=20, x1=90, y1=100),
|
||||
normalized_bbox=LayoutBBox(x0=.01, y0=.1, x1=.9, y1=.5),
|
||||
html='<table><tr><th>Part</th></tr><tr><td>A</td></tr></table>',
|
||||
row_count=2, cell_count=2, has_rowspan=False, has_colspan=False,
|
||||
)],
|
||||
)],
|
||||
capability=MinerUCapabilityReport(
|
||||
provider_version='3.1.14', backend='pipeline', page_count=1,
|
||||
page_size_count=1, bbox_object_count=2, html_table_count=1,
|
||||
html_row_count=2, html_cell_count=2, text_block_count=1,
|
||||
cell_bbox_count=0, has_page_coordinates=True, has_table_structure=True,
|
||||
has_cell_coordinates=False, deterministic_cell_evidence_ready=False,
|
||||
issues=['mineru_cell_coordinates_missing'],
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_runtime_persists_compact_text_and_table_snapshot_without_raw_response(app):
|
||||
"""快照保存受控文本和表格,但不得保存 task_id 或 Provider 原始响应。"""
|
||||
app.config.update(
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
|
||||
)
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
|
||||
return_value={'status': 'completed'},
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
|
||||
return_value=_candidate(),
|
||||
):
|
||||
snapshot = build_mineru_table_snapshot(filename='order.pdf', content=b'%PDF')
|
||||
|
||||
assert snapshot['status'] == 'ready'
|
||||
assert snapshot['text_blocks'][0]['text'] == 'PRIVATE-NON-TABLE-TEXT'
|
||||
assert snapshot['tables'][0]['html'].startswith('<table>')
|
||||
assert 'task-private' not in repr(snapshot)
|
||||
assert snapshot['issues'] == ['mineru_cell_coordinates_missing']
|
||||
|
||||
|
||||
def test_runtime_limits_persisted_mineru_text(app):
|
||||
"""MinerU 文本超过既有通知字符预算时应丢弃超额块并记录问题码。"""
|
||||
app.config.update(
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=10,
|
||||
)
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
|
||||
return_value={'status': 'completed'},
|
||||
), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
|
||||
return_value=_candidate(),
|
||||
):
|
||||
snapshot = build_mineru_table_snapshot(filename='order.pdf', content=b'%PDF')
|
||||
|
||||
assert snapshot['text_blocks'] == []
|
||||
assert 'mineru_text_budget_exceeded' in snapshot['issues']
|
||||
|
||||
|
||||
def test_runtime_provider_failure_is_safe_fallback(app):
|
||||
"""MinerU 失败只记录错误码并返回空表,不能抛出导致 Intake 文本解析失败。"""
|
||||
app.config.update(
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
|
||||
)
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
|
||||
side_effect=ServiceUnavailableError('failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE'),
|
||||
):
|
||||
snapshot = build_mineru_table_snapshot(filename='order.pdf', content=b'%PDF')
|
||||
|
||||
assert snapshot == {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru', 'backend': 'pipeline', 'status': 'failed',
|
||||
'tables': [], 'issues': ['SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE'],
|
||||
}
|
||||
|
||||
|
||||
def test_runtime_attachment_budget_preserves_order_and_marks_overflow(app):
|
||||
"""EML 多附件只并发处理预算内文档,超量附件显式降级且原顺序不变。"""
|
||||
app.config.update(
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=2,
|
||||
SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2,
|
||||
)
|
||||
result = type('Result', (), {'meta': {'attachments': [
|
||||
{'filename': 'first.pdf', '_payload_bytes': b'1'},
|
||||
{'filename': 'second.pdf', '_payload_bytes': b'2'},
|
||||
{'filename': 'third.pdf', '_payload_bytes': b'3'},
|
||||
]}})()
|
||||
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.build_mineru_table_snapshot',
|
||||
side_effect=lambda *, filename, content, **_kwargs: {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru', 'backend': 'pipeline', 'status': 'ready',
|
||||
'tables': [], 'issues': [], 'marker': filename,
|
||||
},
|
||||
) as parse:
|
||||
attach_mineru_layout_snapshots(result)
|
||||
|
||||
rows = result.meta['attachments']
|
||||
assert parse.call_count == 2
|
||||
assert rows[0]['layout_snapshot']['marker'] == 'first.pdf'
|
||||
assert rows[1]['layout_snapshot']['marker'] == 'second.pdf'
|
||||
assert rows[2]['layout_snapshot']['status'] == 'skipped_budget'
|
||||
@@ -0,0 +1,169 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_schema_mapping.py
|
||||
|
||||
用途:验证 layout.v1 真实 cell/token 证据按 Run 冻结 Schema 映射,不回退 HTML 私有 ID 或猜测跨页。
|
||||
依赖:schema_mapping、布局契约、TableHeaderContract。
|
||||
逻辑:覆盖后置表头、重复列、零 Qty、needs_review、token 引用和显式 continuation。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import (
|
||||
LayoutBBox,
|
||||
LayoutCell,
|
||||
LayoutDocument,
|
||||
LayoutIssue,
|
||||
LayoutPage,
|
||||
LayoutParserInfo,
|
||||
LayoutQuality,
|
||||
LayoutRow,
|
||||
LayoutTable,
|
||||
LayoutToken,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
def _cell(
|
||||
cell_id: str, row: int, column: int, text: str, *, token_id: str, role: str,
|
||||
) -> LayoutCell:
|
||||
"""构造一格具有稳定 token 引用的布局证据。"""
|
||||
bbox = LayoutBBox(x0=column * 100, y0=row * 30, x1=(column + 1) * 100, y1=(row + 1) * 30)
|
||||
return LayoutCell(
|
||||
cell_id=cell_id, row_index=row, column_index=column,
|
||||
text=text, normalized_text=text.casefold(), bbox=bbox,
|
||||
normalized_bbox=LayoutBBox(
|
||||
x0=column / 3, y0=row / 4, x1=(column + 1) / 3, y1=(row + 1) / 4,
|
||||
),
|
||||
token_ids=[token_id], source='native_text', confidence=1, role=role,
|
||||
)
|
||||
|
||||
|
||||
def _layout(*, duplicate_part: bool = False, continuation: bool = False) -> LayoutDocument:
|
||||
"""构造标题行后置、两条数据行(第二条 Qty=0)的 layout.v1。"""
|
||||
rows_data = [
|
||||
[('title', 'Purchase Order', 'header')],
|
||||
[
|
||||
('h-part', 'Part Number', 'header'),
|
||||
('h-qty', 'Qty', 'header'),
|
||||
('h-extra', 'Part Number' if duplicate_part else 'Reservation ID', 'header'),
|
||||
],
|
||||
[('v-part', 'A-1', 'data'), ('v-qty', '2', 'data'), ('v-rsv', '2000484577', 'data')],
|
||||
[('z-part', 'A-2', 'data'), ('z-qty', '0', 'data'), ('z-rsv', '2000484578', 'data')],
|
||||
]
|
||||
rows = []
|
||||
tokens = []
|
||||
for row_index, values in enumerate(rows_data):
|
||||
cells = []
|
||||
for column_index, (cell_id, text, role) in enumerate(values):
|
||||
token_id = f't-{cell_id}'
|
||||
cell = _cell(
|
||||
cell_id, row_index, column_index, text, token_id=token_id, role=role,
|
||||
)
|
||||
cells.append(cell)
|
||||
tokens.append(LayoutToken(
|
||||
token_id=token_id, text=text, normalized_text=text.casefold(),
|
||||
bbox=cell.bbox, normalized_bbox=cell.normalized_bbox,
|
||||
source='native_text', confidence=1,
|
||||
))
|
||||
rows.append(LayoutRow(
|
||||
row_id=f'row-{row_index}', row_index=row_index, cells=cells,
|
||||
role='header' if row_index <= 1 else 'data',
|
||||
))
|
||||
table = LayoutTable(
|
||||
table_id='table-main', bbox=LayoutBBox(x0=0, y0=0, x1=300, y1=120),
|
||||
normalized_bbox=LayoutBBox(x0=0, y0=0, x1=1, y1=1), rows=rows,
|
||||
header_row_indices=[0, 1], continuation_of='table-parent' if continuation else None,
|
||||
confidence=0, status='needs_review',
|
||||
)
|
||||
pages = [LayoutPage(page_no=1, width=300, height=120, tokens=tokens, tables=[table])]
|
||||
if continuation:
|
||||
parent = LayoutTable(
|
||||
table_id='table-parent', bbox=LayoutBBox(x0=0, y0=0, x1=300, y1=30),
|
||||
normalized_bbox=LayoutBBox(x0=0, y0=0, x1=1, y1=.25),
|
||||
rows=[LayoutRow(
|
||||
row_id='parent-row', row_index=0,
|
||||
cells=[_cell('parent-cell', 0, 0, 'Part Number', token_id='parent-token', role='header')],
|
||||
role='header',
|
||||
)],
|
||||
header_row_indices=[0], confidence=0, status='needs_review',
|
||||
)
|
||||
pages = [
|
||||
LayoutPage(
|
||||
page_no=1, width=300, height=120,
|
||||
tokens=[LayoutToken(
|
||||
token_id='parent-token', text='Part Number', normalized_text='part number',
|
||||
bbox=parent.rows[0].cells[0].bbox,
|
||||
normalized_bbox=parent.rows[0].cells[0].normalized_bbox,
|
||||
source='native_text', confidence=1,
|
||||
)], tables=[parent],
|
||||
),
|
||||
LayoutPage(page_no=2, width=300, height=120, tokens=tokens, tables=[table]),
|
||||
]
|
||||
return LayoutDocument(
|
||||
document_id=21, content_hash='a' * 64,
|
||||
parser=LayoutParserInfo(name='test', version='v1'), pages=pages,
|
||||
quality=LayoutQuality(
|
||||
status='needs_review', confidence=0,
|
||||
issues=[LayoutIssue(code='truth_deferred', severity='blocking')],
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _contract():
|
||||
"""构造包含客户料号、数量和 Reservation 的冻结 Schema。"""
|
||||
return compile_table_header_contract({'fields': [
|
||||
{
|
||||
'field_id': 'part-id', 'field_code': 'customer_part_number',
|
||||
'scope': 'line', 'value_type': 'string', 'enabled': True,
|
||||
'aliases': ['Part Number'], 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty-id', 'field_code': 'qty',
|
||||
'scope': 'line', 'value_type': 'decimal', 'enabled': True,
|
||||
'aliases': ['Qty'], 'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
|
||||
},
|
||||
{
|
||||
'field_id': 'rsv-id', 'field_code': 'reservation_id',
|
||||
'scope': 'line', 'value_type': 'string', 'enabled': True,
|
||||
'aliases': ['Reservation ID'], 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
]})
|
||||
|
||||
|
||||
def test_layout_mapping_preserves_real_cell_and_token_evidence_and_zero_qty():
|
||||
"""后置表头应精确映射,字段引用真实 layout cell/token,显式 Qty=0 行删除。"""
|
||||
mapped = map_layout_document_to_schema(_layout(), contract=_contract())[0]
|
||||
|
||||
assert mapped['header_row_index'] == 1
|
||||
assert mapped['mapping_status'] == 'candidate'
|
||||
assert 'layout_table_not_accepted' in mapped['issues']
|
||||
data = next(row for row in mapped['rows'] if row['row_index'] == 2)
|
||||
assert {field['field_id'] for field in data['fields']} == {'part-id', 'qty-id', 'rsv-id'}
|
||||
part = next(field for field in data['fields'] if field['field_id'] == 'part-id')
|
||||
assert part['cell_id'] == 'v-part'
|
||||
assert part['token_ids'] == ['t-v-part']
|
||||
assert part['evidence_ref'] == 'layout:21:p1:table-main:v-part'
|
||||
deleted = next(row for row in mapped['rows'] if row['row_index'] == 3)
|
||||
assert deleted['role'] == 'deleted'
|
||||
assert deleted['fields'] == []
|
||||
|
||||
|
||||
def test_layout_mapping_blocks_duplicate_target_columns():
|
||||
"""同一字段命中两列时两列均 ambiguous,禁止选择左/右列。"""
|
||||
mapped = map_layout_document_to_schema(_layout(duplicate_part=True), contract=_contract())[0]
|
||||
|
||||
assert 'html_table_duplicate_field_columns' in mapped['issues']
|
||||
part_columns = [item for item in mapped['columns'] if 'customer_part_number' in item['candidates']]
|
||||
assert len(part_columns) == 2
|
||||
assert all(item['status'] == 'ambiguous' for item in part_columns)
|
||||
|
||||
|
||||
def test_layout_mapping_keeps_only_explicit_cross_page_continuation():
|
||||
"""跨页关系只透传契约中的 continuation_of,不按重复表头自动猜父表。"""
|
||||
mapped = map_layout_document_to_schema(_layout(continuation=True), contract=_contract())
|
||||
|
||||
child = next(item for item in mapped if item['table_id'] == 'table-main')
|
||||
parent = next(item for item in mapped if item['table_id'] == 'table-parent')
|
||||
assert child['continuation_of'] == 'table-parent'
|
||||
assert parent['continuation_of'] is None
|
||||
@@ -0,0 +1,153 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_layout_text_cell_alignment.py
|
||||
|
||||
用途:验证 PDF 原生字符坐标只在唯一、非重叠文本匹配时形成 cell bbox 候选。
|
||||
依赖:text_cell_alignment、html_table、LayoutBBox。
|
||||
逻辑:覆盖完整匹配、重复 Qty、空 cell、找不到文本和重叠子串,禁止任何猜框行为。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import (
|
||||
align_html_cells_from_positioned_text,
|
||||
)
|
||||
|
||||
|
||||
def _characters(text: str) -> list[dict]:
|
||||
"""为无空格字符串生成从左到右的构造字符坐标。"""
|
||||
return [
|
||||
{'text': char, 'bbox': {'x0': 10 + index * 5, 'y0': 20, 'x1': 14 + index * 5, 'y1': 30}}
|
||||
for index, char in enumerate(text)
|
||||
]
|
||||
|
||||
|
||||
def _align(html: str, text: str):
|
||||
"""使用固定页面和整表范围执行文本对齐。"""
|
||||
return align_html_cells_from_positioned_text(
|
||||
parse_html_grid(html, table_id='t'),
|
||||
characters=_characters(text),
|
||||
table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=100),
|
||||
page_width=200,
|
||||
page_height=100,
|
||||
)
|
||||
|
||||
|
||||
def test_unique_text_alignment_returns_normalized_cell_boxes():
|
||||
"""每个 cell 文本唯一时应返回对应字符并集及标准化坐标。"""
|
||||
result = _align(
|
||||
'<table><tr><th>Part</th><th>Qty</th></tr><tr><td>A1</td><td>20</td></tr></table>',
|
||||
'PartQtyA120',
|
||||
)
|
||||
|
||||
# 断言完整候选只来自唯一文本,不按列宽均分。
|
||||
assert result.complete is True
|
||||
assert result.matched_cell_count == 4
|
||||
assert result.cells[0].bbox.model_dump() == {'x0': 10.0, 'y0': 20.0, 'x1': 29.0, 'y1': 30.0}
|
||||
assert result.cells[0].normalized_bbox.x0 == 0.05
|
||||
assert result.cells[0].glyph_indices == [0, 1, 2, 3]
|
||||
|
||||
|
||||
def test_repeated_text_is_rejected_instead_of_selected_by_position():
|
||||
"""重复 Qty/值不得按首次出现或 HTML 顺序分配给 cell。"""
|
||||
result = _align(
|
||||
'<table><tr><th>Qty</th><th>Qty</th></tr></table>',
|
||||
'QtyQty',
|
||||
)
|
||||
|
||||
assert result.complete is False
|
||||
assert result.cells == []
|
||||
assert result.issues == ['text_cell_alignment_text_not_unique']
|
||||
|
||||
|
||||
def test_empty_and_missing_cells_remain_unmatched():
|
||||
"""空 cell 或文本层缺失不得生成零面积框或借用相邻字符。"""
|
||||
result = _align(
|
||||
'<table><tr><td>A1</td><td></td><td>Missing</td></tr></table>',
|
||||
'A1',
|
||||
)
|
||||
|
||||
assert result.complete is False
|
||||
assert result.matched_cell_count == 1
|
||||
assert result.issues == [
|
||||
'text_cell_alignment_empty_cell',
|
||||
'text_cell_alignment_text_not_found',
|
||||
]
|
||||
|
||||
|
||||
def test_overlapping_unique_substrings_do_not_share_glyphs():
|
||||
"""一个长 cell 与其唯一子串不能共享同一组 PDF 字符。"""
|
||||
result = _align(
|
||||
'<table><tr><td>ABC</td><td>BC</td></tr></table>',
|
||||
'ABC',
|
||||
)
|
||||
|
||||
assert result.complete is False
|
||||
assert result.matched_cell_count == 1
|
||||
assert result.issues == ['text_cell_alignment_glyph_overlap']
|
||||
|
||||
|
||||
def test_invalid_page_glyph_is_dropped_without_adjusting_coordinates():
|
||||
"""页面外 glyph 应被丢弃并记录问题,不能裁剪坐标后参与 cell 候选。"""
|
||||
characters = _characters('A1')
|
||||
characters.append({'text': 'X', 'bbox': {'x0': 20, 'y0': -2, 'x1': 24, 'y1': 5}})
|
||||
|
||||
result = align_html_cells_from_positioned_text(
|
||||
parse_html_grid('<table><tr><td>A1</td></tr></table>', table_id='invalid-glyph'),
|
||||
characters=characters,
|
||||
table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=100),
|
||||
page_width=200,
|
||||
page_height=100,
|
||||
)
|
||||
|
||||
assert result.complete is True
|
||||
assert result.matched_cell_count == 1
|
||||
assert result.issues == ['text_cell_alignment_invalid_character_bbox']
|
||||
|
||||
|
||||
def test_page_overflow_glyph_and_table_are_never_normalized():
|
||||
"""超出实际页面宽高的 glyph 被丢弃,整表 bbox 越界则直接拒绝。"""
|
||||
characters = _characters('A1')
|
||||
characters.append({'text': 'X', 'bbox': {'x0': 198, 'y0': 20, 'x1': 205, 'y1': 30}})
|
||||
grid = parse_html_grid('<table><tr><td>A1</td></tr></table>', table_id='page-overflow')
|
||||
|
||||
result = align_html_cells_from_positioned_text(
|
||||
grid,
|
||||
characters=characters,
|
||||
table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=100),
|
||||
page_width=200,
|
||||
page_height=100,
|
||||
)
|
||||
assert result.complete is True
|
||||
assert result.cells[0].normalized_bbox.x1 <= 1
|
||||
assert result.issues == ['text_cell_alignment_invalid_character_bbox']
|
||||
|
||||
with pytest.raises(ValueError, match='table bbox'):
|
||||
align_html_cells_from_positioned_text(
|
||||
grid,
|
||||
characters=_characters('A1'),
|
||||
table_bbox=LayoutBBox(x0=0, y0=0, x1=201, y1=100),
|
||||
page_width=200,
|
||||
page_height=100,
|
||||
)
|
||||
|
||||
|
||||
def test_unique_string_split_across_visual_rows_is_rejected():
|
||||
"""文本流中唯一但视觉上跨行的字符串不能被合并成一个大 cell bbox。"""
|
||||
characters = _characters('AB')
|
||||
characters[1]['bbox'] = {'x0': 10, 'y0': 60, 'x1': 14, 'y1': 70}
|
||||
|
||||
result = align_html_cells_from_positioned_text(
|
||||
parse_html_grid('<table><tr><td>AB</td></tr></table>', table_id='cross-row'),
|
||||
characters=characters,
|
||||
table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=100),
|
||||
page_width=200,
|
||||
page_height=100,
|
||||
)
|
||||
|
||||
assert result.complete is False
|
||||
assert result.cells == []
|
||||
assert result.issues == ['text_cell_alignment_geometry_discontinuous']
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
backend/tests/test_shipping_layout_truth_workbench.py
|
||||
|
||||
用途:验证人工真值工作台的仓库外输出门禁、离线页面和 annotation 契约校验入口。
|
||||
依赖:脚本模块、临时目录、正式 LayoutAnnotation。
|
||||
逻辑:不调用 MinerU;仅测试隐私路径和生成/校验纯函数,避免真实样本进入测试输出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _module():
|
||||
"""按脚本路径加载工作台模块,不依赖 scripts 包结构。"""
|
||||
path = Path(__file__).resolve().parents[1] / 'scripts' / 'build_shipping_layout_truth_workbench.py'
|
||||
spec = importlib.util.spec_from_file_location('shipping_layout_truth_workbench', path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
assert spec and spec.loader
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _manifest() -> dict:
|
||||
"""构造不含业务原文的最小离线工作台清单。"""
|
||||
return {
|
||||
'sample_id': 'pdf-aaaaaaaaaaaa',
|
||||
'content_hash': 'a' * 64,
|
||||
'categories': ['native_pdf'],
|
||||
'pages': [{'page_no': 1, 'width': 100, 'height': 200}],
|
||||
'tables': [],
|
||||
}
|
||||
|
||||
|
||||
def test_workbench_rejects_repository_output_and_builds_offline_html(tmp_path, monkeypatch):
|
||||
"""真实样本输出不得落仓库;离线页面不得依赖 CDN 或网络脚本。"""
|
||||
module = _module()
|
||||
repository = tmp_path / 'repository'
|
||||
repository.mkdir()
|
||||
monkeypatch.setattr(module, 'REPOSITORY_ROOT', repository)
|
||||
with pytest.raises(ValueError, match='outside'):
|
||||
module._external_output_path(repository / 'tmp' / 'truth')
|
||||
|
||||
external = tmp_path / 'external'
|
||||
assert module._external_output_path(external) == external.resolve()
|
||||
page = module._workbench_html(_manifest())
|
||||
assert 'shipping_document_layout_annotation.v1' in page
|
||||
assert 'http://' not in page and 'https://' not in page
|
||||
assert '导出 annotation.json' in page
|
||||
|
||||
|
||||
def test_layout_annotation_contract_accepts_workbench_export_shape():
|
||||
"""工作台导出字段必须能直接通过正式 annotation.v1 契约。"""
|
||||
module = _module()
|
||||
payload = {
|
||||
'schema_version': 'shipping_document_layout_annotation.v1',
|
||||
'layout_schema_version': 'shipping_document_layout.v1',
|
||||
'sample_id': 'pdf-aaaaaaaaaaaa',
|
||||
'content_hash': 'a' * 64,
|
||||
'categories': ['native_pdf'],
|
||||
'tables': [{
|
||||
'annotation_id': 'table-p1-0', 'page_no': 1, 'table_index': 0,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.9, 'y1': 0.9},
|
||||
'continuation_of': None,
|
||||
'cells': [{
|
||||
'annotation_id': 'cell-p1-0-0', 'page_no': 1, 'table_index': 0,
|
||||
'row_index': 0, 'column_index': 0,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.5, 'y1': 0.2},
|
||||
'normalized_text': 'Part', 'role': 'header', 'expected_field_code': 'part_number',
|
||||
}],
|
||||
}],
|
||||
}
|
||||
|
||||
annotation = module.LayoutAnnotation.model_validate_json(json.dumps(payload))
|
||||
assert annotation.tables[0].cells[0].expected_field_code == 'part_number'
|
||||
@@ -1319,9 +1319,9 @@ def test_flattened_text_does_not_guess_external_reservation_id():
|
||||
assert issues[0]["severity"] == "blocking"
|
||||
|
||||
|
||||
def test_adjudication_supports_non_numeric_reservation_templates():
|
||||
"""不同来源模板可使用字母型 Reservation ID,后端只排除内部 ID,不绑定单一数字模板。"""
|
||||
raw_text = "Part Number\tReservation Order\tQty\nA001\tAWS-311\t2"
|
||||
def test_adjudication_supports_five_digit_reservation_templates():
|
||||
"""不同来源模板可使用 5 位数字 Reservation ID,并保留明确列证据。"""
|
||||
raw_text = "Part Number\tReservation Order\tQty\nA001\t12345\t2"
|
||||
lines = [{"part_number": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}]
|
||||
|
||||
adjudicated, issues, status = adjudicate_notice_lines(
|
||||
@@ -1329,7 +1329,7 @@ def test_adjudication_supports_non_numeric_reservation_templates():
|
||||
)
|
||||
|
||||
assert status == "ready"
|
||||
assert adjudicated[0]["reservation_id"] == "AWS-311"
|
||||
assert adjudicated[0]["reservation_id"] == "12345"
|
||||
assert issues[0]["reason"] == "value_corrected"
|
||||
|
||||
|
||||
@@ -1368,6 +1368,15 @@ Part Number\tReservation ID\tQty\tUnit Price\tAmount
|
||||
assert lines[0]["reservation_id"] == "1000140351"
|
||||
|
||||
|
||||
def test_extract_notice_supports_five_digit_reservation_free_text():
|
||||
"""自由文本回退路径应识别 5 位 Reservation ID、内部料号和数量。"""
|
||||
parsed, _confidence, _warnings = _heuristic_extract("12345 10-40594-001 2")
|
||||
|
||||
assert parsed["lines"] == [{
|
||||
"reservation_id": "12345", "part_number": "10-40594-001", "qty": 2.0,
|
||||
}]
|
||||
|
||||
|
||||
def test_does_not_infer_reservation_id_without_configured_header():
|
||||
headers = ["Part Number", "Ref", "Qty"]
|
||||
rows = [["10-40594-001", 1000140351, 2]]
|
||||
|
||||
@@ -112,7 +112,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
structured_result_json={
|
||||
'business_summary': {
|
||||
'po_number': '7001',
|
||||
'lines': [{'reservation_id': 'R-1', 'part_number': 'SKU-1', 'qty': 1}],
|
||||
'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 1}],
|
||||
},
|
||||
},
|
||||
validation_status='needs_review',
|
||||
@@ -134,7 +134,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
'selected': False,
|
||||
'business_summary': {
|
||||
'po_number': '7001',
|
||||
'lines': [{'reservation_id': 'R-1', 'part_number': 'SKU-1', 'qty': 2}],
|
||||
'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 2}],
|
||||
},
|
||||
},
|
||||
headers=owner_headers,
|
||||
@@ -3333,8 +3333,13 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
|
||||
)
|
||||
eml_bytes = msg.as_bytes()
|
||||
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE'] = 4
|
||||
with app.app_context():
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
|
||||
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.build_mineru_table_snapshot',
|
||||
side_effect=AssertionError('Intake parse must not call MinerU inline'),
|
||||
):
|
||||
asset_data = upload_file_asset(
|
||||
user_id=shipping_user.id,
|
||||
upload=FileStorage(
|
||||
@@ -3408,6 +3413,12 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
|
||||
assert len(cands) == 0
|
||||
assert len(children) == 3
|
||||
assert len({c.content_hash for c in children}) == 3
|
||||
from app.models import Job, ShippingDocumentLayoutVersion
|
||||
|
||||
assert ShippingDocumentLayoutVersion.query.filter(
|
||||
ShippingDocumentLayoutVersion.document_id.in_([item.id for item in pdf_docs]),
|
||||
).count() == 3
|
||||
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3
|
||||
|
||||
detail = serialize_intake(refreshed_intake, asset=parent, include_parse_texts=True)
|
||||
assert detail['document_count'] == 4
|
||||
@@ -3431,6 +3442,8 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
|
||||
)
|
||||
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 4
|
||||
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 0
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 3
|
||||
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3
|
||||
assert (
|
||||
db.session.query(FileAsset)
|
||||
.filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
|
||||
@@ -3439,6 +3452,66 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
|
||||
)
|
||||
|
||||
|
||||
def test_run_intake_parse_persists_sanitized_email_html_layout_without_meta_leak(
|
||||
app, shipping_user, monkeypatch,
|
||||
):
|
||||
"""HTML 正文表格应生成独立布局版本,临时 HTML 不得进入 Intake 摘要或 Dify 文档正文。"""
|
||||
from email.message import EmailMessage
|
||||
from io import BytesIO
|
||||
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app.models import ShippingDocumentLayoutVersion
|
||||
from app.services.file_assets.service import upload_file_asset
|
||||
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
|
||||
|
||||
msg = EmailMessage()
|
||||
msg['Subject'] = 'HTML table order'
|
||||
msg.set_content('PO 12345')
|
||||
msg.add_alternative(
|
||||
'<html><body><script>SECRET()</script><table style="color:red">'
|
||||
'<tr><th>Part</th><th>Qty</th></tr><tr><td>A-1</td><td>2</td></tr>'
|
||||
'</table></body></html>',
|
||||
subtype='html',
|
||||
)
|
||||
eml_bytes = msg.as_bytes()
|
||||
with app.app_context(), patch(
|
||||
'app.services.file_assets.service.file_asset_storage.upload_bytes',
|
||||
):
|
||||
asset_data = upload_file_asset(
|
||||
user_id=shipping_user.id,
|
||||
upload=FileStorage(
|
||||
stream=BytesIO(eml_bytes), filename='html-order.eml', content_type='message/rfc822',
|
||||
),
|
||||
)
|
||||
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-HTML-LAYOUT', asset_id=parent.id, user_id=shipping_user.id,
|
||||
purpose='shipping_notice', parse_status='parsing', parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
|
||||
lambda _asset: eml_bytes,
|
||||
)
|
||||
|
||||
result = run_intake_parse(intake, parent)
|
||||
db.session.expire_all()
|
||||
body = ShippingNoticeDocument.query.filter_by(
|
||||
intake_id=intake.id, document_type='email_body',
|
||||
).one()
|
||||
version = ShippingDocumentLayoutVersion.query.filter_by(document_id=body.id).one()
|
||||
structured = db.session.get(ShippingNoticeIntake, intake.id).structured_result_json
|
||||
|
||||
assert result['status'] == 'parsed'
|
||||
assert version.status == 'needs_review'
|
||||
assert version.payload_json['layout_candidate']['parser']['name'] == 'eml-html-dom'
|
||||
assert 'SECRET' not in repr(version.payload_json)
|
||||
assert 'body_html_tables' not in repr(structured)
|
||||
assert '<table' not in repr(structured)
|
||||
|
||||
|
||||
def test_stage2_supporting_pdf_without_po_has_document_but_no_candidate(
|
||||
app, shipping_user, monkeypatch,
|
||||
):
|
||||
|
||||
@@ -57,17 +57,17 @@ def test_parse_aws_inventory_headers(app):
|
||||
with app.app_context():
|
||||
headers = ["Supplier Sku", "AWS Sku", "COM ID", "Qty Available", "Qty", "ODM ID"]
|
||||
data = [
|
||||
["D4-A", "10-40594-001", "AWS-311", 2, 1, "16754796"],
|
||||
["D4-B", "10-40594-002", "ORD-3002", 0, 5, "16754797"],
|
||||
["D4-A", "10-40594-001", "12345", 2, 1, "16754796"],
|
||||
["D4-B", "10-40594-002", "3000092917", 0, 5, "16754797"],
|
||||
]
|
||||
lines = parse_inventory_rows(headers, data)
|
||||
assert len(lines) == 2
|
||||
assert lines[0]["part_number"] == "D4-A"
|
||||
assert lines[0]["aws_part_number"] == "10-40594-001"
|
||||
assert lines[0]["reservation_id"] == "AWS-311"
|
||||
assert lines[0]["reservation_id"] == "12345"
|
||||
assert lines[0]["available_qty"] == 2.0
|
||||
assert lines[0]["odm_id"] == "16754796"
|
||||
assert lines[1]["reservation_id"] == "ORD-3002"
|
||||
assert lines[1]["reservation_id"] == "3000092917"
|
||||
assert lines[1]["available_qty"] == 0.0
|
||||
assert lines[1]["odm_id"] == "16754797"
|
||||
|
||||
@@ -131,12 +131,12 @@ def test_match_aggregates_same_part_number_reservation():
|
||||
|
||||
def test_parse_inventory_text_aws_table(app):
|
||||
with app.app_context():
|
||||
text = "Supplier Sku\tAWS Sku\tReservation Order\tQty\nD4-A\t10-40594-001\tORD-3002\t4"
|
||||
text = "Supplier Sku\tAWS Sku\tReservation Order\tQty\nD4-A\t10-40594-001\t12345\t4"
|
||||
lines, warnings, column_meta = parse_inventory_text(text)
|
||||
assert not warnings or "no inventory" not in warnings[0]
|
||||
assert lines[0]["part_number"] == "D4-A"
|
||||
assert lines[0]["aws_part_number"] == "10-40594-001"
|
||||
assert lines[0]["reservation_id"] == "ORD-3002"
|
||||
assert lines[0]["reservation_id"] == "12345"
|
||||
assert lines[0]["available_qty"] == 4.0
|
||||
assert column_meta["mapping"]["reservation_id"]["source_column"] == "Reservation Order"
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it()
|
||||
assessment = assess_candidate_business_summary({
|
||||
'po_number': '4510038672',
|
||||
'lines': [
|
||||
{'part_number': 'SKU-A', 'qty': 1, 'reservation_id': 'R-100'},
|
||||
{'part_number': 'SKU-A', 'qty': 1, 'reservation_id': '1000140351'},
|
||||
{'part_number': 'SKU-B', 'qty': 2},
|
||||
],
|
||||
})
|
||||
@@ -195,7 +195,7 @@ def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, S
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text=(
|
||||
'PO 4510000001 SKU SKU-A QTY 10 RSV R-100 SOURCE AWS Dublin HUB DUB\n'
|
||||
'PO 4510000001 SKU SKU-A QTY 10 RSV 1000140351 SOURCE AWS Dublin HUB DUB\n'
|
||||
'PO 4510000002 SKU SKU-B QTY 20\n'
|
||||
'SKU SKU-STATE SKU SKU-STALE SKU SKU-UI-STATE SKU SKU-OPEN-EXISTING\n'
|
||||
'SKU P123456 SKU IGNORED-SKU QTY 1 QTY 2 QTY 3 QTY 5 QTY 24'
|
||||
@@ -260,6 +260,7 @@ def _persist_test_orders(payload: dict) -> dict:
|
||||
run_id=None,
|
||||
schema_version_id=int(schema.id),
|
||||
extraction_source='test_workflow',
|
||||
frozen_layout_candidates_by_document=payload.get('layout_candidates_by_document'),
|
||||
auto_create_enabled=True,
|
||||
)
|
||||
|
||||
@@ -282,6 +283,36 @@ def _persist_shadow_orders(payload: dict) -> dict:
|
||||
auto_create_enabled=False,
|
||||
)
|
||||
|
||||
|
||||
def test_plain_text_table_issue_reaches_candidate_as_machine_readable_conflict(app):
|
||||
"""无 cell 证据的纯文本表格必须在 Candidate 保留原因码,供现有任务 UI 解释。"""
|
||||
with app.app_context():
|
||||
_user, _session, intake, document, _runtime = _seed_extraction_input()
|
||||
document.extracted_text = 'part_number\tqty\nPART-PLAIN\t3'
|
||||
db.session.commit()
|
||||
fields = _ensure_order_schema()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
order = {
|
||||
'schema_version_id': version.id, 'schema_checksum': version.checksum,
|
||||
'classification': 'shipping_request', 'classification_confidence': 0.99,
|
||||
'source_intake_no': intake.intake_no, 'primary_document_id': document.id,
|
||||
'header_fields': [], 'lines': [{'fields': [{
|
||||
'field_id': fields['qty'], 'observations': [{
|
||||
'value': 3, 'document_id': document.id,
|
||||
'quote': 'qty\nPART-PLAIN\t3', 'confidence': 0.9,
|
||||
}],
|
||||
}]}], 'conflicts': [],
|
||||
}
|
||||
|
||||
_persist_test_orders({'input_snapshot_hash': f'test-{intake.id}-{document.id}', 'orders': [order]})
|
||||
|
||||
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=intake.id).one()
|
||||
assert candidate.validation_status == 'needs_review'
|
||||
assert any(
|
||||
item.get('reason') == 'plain_text_table_has_no_cell_evidence'
|
||||
for item in candidate.conflicts_json
|
||||
)
|
||||
|
||||
def _order(
|
||||
*,
|
||||
intake_no: str,
|
||||
@@ -308,7 +339,7 @@ def _order(
|
||||
if include_process_fields:
|
||||
line_fields.extend([
|
||||
{'field_id': fields['reservation_id'], 'observations': [
|
||||
{'value': 'R-100', 'quote': 'R-100', 'document_id': document_id, 'confidence': confidence},
|
||||
{'value': '1000140351', 'quote': '1000140351', 'document_id': document_id, 'confidence': confidence},
|
||||
]},
|
||||
{'field_id': fields['inventory_source_hint'], 'observations': [
|
||||
{'value': 'AWS Dublin', 'quote': 'AWS Dublin', 'document_id': document_id, 'confidence': confidence},
|
||||
@@ -413,8 +444,8 @@ def _attach_existing_task_dynamic_order(task: ShippingTask) -> None:
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def test_order_field_display_uses_locked_schema_sequence(app):
|
||||
"""对话字段顺序必须来自任务锁定 Schema,且通用上下文不能混入订单信息。"""
|
||||
def test_order_field_display_uses_current_catalog_sequence(app):
|
||||
"""对话字段顺序使用当前字段目录,锁定 Schema 仍负责字段定义和分类。"""
|
||||
with app.app_context():
|
||||
_ensure_order_schema()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
@@ -436,7 +467,7 @@ def test_order_field_display_uses_locked_schema_sequence(app):
|
||||
|
||||
assert [item['field_code'] for item in display['header_fields']] == ['po_number']
|
||||
assert [item['field_code'] for item in display['line_fields']][:3] == [
|
||||
'qty', 'part_number', 'reservation_id',
|
||||
'part_number', 'qty', 'reservation_id',
|
||||
]
|
||||
|
||||
|
||||
@@ -484,7 +515,7 @@ def _add_extraction_intake(
|
||||
content_hash=f'order-extraction-document-{suffix.lower()}',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text=f'SKU SKU-{normalized} QTY 1 RSV R-100',
|
||||
extracted_text=f'SKU SKU-{normalized} QTY 1 RSV 1000140351',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.commit()
|
||||
@@ -574,7 +605,7 @@ def test_persist_order_extraction_result_supports_multiple_orders_partial_succes
|
||||
'task_id': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {
|
||||
'reservation_id': 'R-100',
|
||||
'reservation_id': '1000140351',
|
||||
},
|
||||
'comment': '用户通过自然对话补齐流程字段',
|
||||
})
|
||||
@@ -910,13 +941,13 @@ def test_order_extraction_does_not_auto_create_with_unverified_reservation_evide
|
||||
|
||||
|
||||
def test_order_extraction_backend_blocks_reservation_source_conflict(app):
|
||||
"""即使 LLM 未声明冲突,后端也必须用明确表格列证据阻断不一致的 Reservation。"""
|
||||
"""即使 LLM 未声明冲突,accepted cell 证据也必须阻断不一致的 Reservation。"""
|
||||
with app.app_context():
|
||||
user, _session, intake, document, runtime_context = _seed_extraction_input()
|
||||
document.extracted_text = (
|
||||
"Part Number\tReservation ID\tQty\n"
|
||||
"SKU-A\tR-200\t10\n"
|
||||
"LLM candidate quote R-100"
|
||||
"SKU-A\t1000140352\t10\n"
|
||||
"LLM candidate quote 1000140351"
|
||||
)
|
||||
db.session.commit()
|
||||
context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context})
|
||||
@@ -932,6 +963,24 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
|
||||
result = _persist_test_orders({
|
||||
'agent_runtime_context': runtime_context,
|
||||
'input_snapshot_hash': context_result['input_snapshot_hash'],
|
||||
'layout_candidates_by_document': {int(document.id): [{
|
||||
'page_no': 1, 'table_id': 'reservation-table',
|
||||
'mapping_status': 'accepted', 'issues': [],
|
||||
'rows': [{'row_index': 1, 'role': 'data', 'fields': [
|
||||
{
|
||||
'field_id': _ensure_order_schema()['part_number'],
|
||||
'value': 'SKU-A', 'quote': 'SKU-A', 'column_index': 0,
|
||||
'cell_id': 'part-cell',
|
||||
'evidence_ref': f'layout:{document.id}:p1:reservation-table:part-cell',
|
||||
},
|
||||
{
|
||||
'field_id': _ensure_order_schema()['reservation_id'],
|
||||
'value': '1000140352', 'quote': '1000140352', 'column_index': 1,
|
||||
'cell_id': 'reservation-cell',
|
||||
'evidence_ref': f'layout:{document.id}:p1:reservation-table:reservation-cell',
|
||||
},
|
||||
]}],
|
||||
}]},
|
||||
'orders': [order],
|
||||
})
|
||||
|
||||
@@ -945,7 +994,7 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
|
||||
item for item in adjudication['observations']
|
||||
if item['field_id'] == _ensure_order_schema()['reservation_id']
|
||||
]
|
||||
assert {item['source_type'] for item in reservation_observations} == {'backend_table', 'attachment_text'}
|
||||
assert {item['source_type'] for item in reservation_observations} == {'attachment_table', 'attachment_text'}
|
||||
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
|
||||
|
||||
|
||||
@@ -1178,7 +1227,7 @@ def test_order_extraction_requires_verified_dynamic_reservation_observation(app)
|
||||
qty=10,
|
||||
include_process_fields=True,
|
||||
)
|
||||
_set_dynamic_line_field(order, 'reservation_id', '1000140351', quote='1000140351')
|
||||
_set_dynamic_line_field(order, 'reservation_id', '1000140352', quote='1000140352')
|
||||
|
||||
result = _persist_test_orders({
|
||||
'agent_runtime_context': runtime_context,
|
||||
|
||||
@@ -25,14 +25,16 @@ def test_normalize_reservation_id_string():
|
||||
assert normalize_reservation_id("1000140351") == "1000140351"
|
||||
|
||||
|
||||
def test_reservation_contract_rejects_internal_hex_but_keeps_business_ids():
|
||||
"""硬契约应拒绝内部 hex 主键,同时兼容已有字母型业务 Reservation ID。"""
|
||||
def test_reservation_contract_only_accepts_five_or_ten_digits():
|
||||
"""硬契约只接受 5 位或 10 位纯数字 Reservation ID。"""
|
||||
assert not is_valid_reservation_id("1f1a682dfdc446a393415dee93eb36ce")
|
||||
assert validated_reservation_id("1f1a682dfdc446a393415dee93eb36ce") == ""
|
||||
assert is_valid_reservation_id("12345")
|
||||
assert is_valid_reservation_id("3000092917")
|
||||
assert is_valid_reservation_id("AWS-311")
|
||||
assert is_valid_reservation_id("R-1")
|
||||
assert not is_valid_reservation_id("AWS-311", numeric_only=True)
|
||||
assert not is_valid_reservation_id("123456")
|
||||
assert not is_valid_reservation_id("AWS-311")
|
||||
assert not is_valid_reservation_id("R-1")
|
||||
assert not is_valid_reservation_id("12345678901", numeric_only=True)
|
||||
|
||||
|
||||
def test_reservation_gate_blocks_empty_and_malformed_order_lines():
|
||||
|
||||
@@ -488,11 +488,11 @@ def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1)
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "inventory_ready"
|
||||
task.review_status = None
|
||||
task.pending_human_reason = "inv_unavail"
|
||||
task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "R-1", "available_qty": 3}]
|
||||
task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "12345", "available_qty": 3}]
|
||||
task.match_status = "fulfillable"
|
||||
task.shortage_json = {"lines": []}
|
||||
task.line_results_json = [{"part_number": "OLD", "status": "ok"}]
|
||||
@@ -570,7 +570,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1)
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "waiting_inventory"
|
||||
task.pending_human_reason = PH_RPA_PENDING
|
||||
task.step_payload_json = {
|
||||
@@ -634,7 +634,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1)
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "waiting_inventory"
|
||||
task.pending_human_reason = PH_RPA_EXHAUSTED
|
||||
task.step_payload_json = {
|
||||
@@ -718,7 +718,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
|
||||
with app.app_context():
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
assert task is not None
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='R-1', quantity=1)
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
|
||||
task.process_status = "waiting_inventory"
|
||||
task.pending_human_reason = PH_RPA_PENDING
|
||||
task.step_payload_json = {
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_document_profile_service.py
|
||||
|
||||
用途:验证订单文档 Profile 的 Schema 字段绑定、发布生命周期、并发锁和管理 API 权限。
|
||||
依赖:全局 Flask 测试库、订单 Schema/Profile 模型与服务。
|
||||
逻辑:构造不可变 Schema 后保存模板级特例;发布新版本退役旧版,非法字段和并发覆盖必须阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
FileAsset,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as service
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
|
||||
def _schema_version() -> ShippingOrderSchemaVersion:
|
||||
"""创建含模板所需客户料号、内部料号和数量字段的发布 Schema。"""
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
checksum='a' * 64,
|
||||
published_at=datetime.utcnow(),
|
||||
definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'customer-field', 'field_code': 'customer_part_number',
|
||||
'scope': 'line', 'value_type': 'string', 'enabled': True,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-field', 'field_code': 'part_number',
|
||||
'scope': 'line', 'value_type': 'string', 'enabled': True,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty-field', 'field_code': 'qty',
|
||||
'scope': 'line', 'value_type': 'decimal', 'enabled': True,
|
||||
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
|
||||
},
|
||||
]},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.commit()
|
||||
return version
|
||||
|
||||
|
||||
def _data(schema_id: int, *, fingerprint: str = 'b' * 64) -> dict:
|
||||
"""构造已确认模板 `Part Number/Vendor Item#` 的 Profile 请求。"""
|
||||
return {
|
||||
'profile_code': 'PO_312207',
|
||||
'display_name': 'PO 312207 template',
|
||||
'schema_version_id': schema_id,
|
||||
'definition': {
|
||||
'structure_fingerprint': fingerprint,
|
||||
'header_row_index': 0,
|
||||
'data_start_row_index': 1,
|
||||
'drop_zero_qty': True,
|
||||
'column_rules': [
|
||||
{
|
||||
'column_index': 1,
|
||||
'extractor_key': 'direct',
|
||||
'target_field_codes': ['customer_part_number'],
|
||||
},
|
||||
{
|
||||
'column_index': 2,
|
||||
'extractor_key': 'direct',
|
||||
'target_field_codes': ['part_number'],
|
||||
},
|
||||
{
|
||||
'column_index': 3,
|
||||
'extractor_key': 'direct',
|
||||
'target_field_codes': ['qty'],
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_profile_publish_freezes_field_ids_and_retires_previous_version(app):
|
||||
"""模板级语义必须冻结稳定字段 ID;新发布版本原子退役旧发布版本。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
first = service.save_draft(_data(schema.id), actor_id=None)
|
||||
published = service.publish(
|
||||
first['id'], actor_id=None, expected_lock_version=first['lock_version'],
|
||||
)
|
||||
|
||||
rules = published['definition']['column_rules']
|
||||
assert rules[0]['target_fields'] == [{
|
||||
'field_id': 'customer-field', 'field_code': 'customer_part_number',
|
||||
}]
|
||||
assert rules[1]['target_fields'] == [{
|
||||
'field_id': 'part-field', 'field_code': 'part_number',
|
||||
}]
|
||||
assert len(published['checksum']) == 64
|
||||
|
||||
draft = service.clone_draft(published['id'], actor_id=None)
|
||||
update = _data(schema.id, fingerprint='c' * 64)
|
||||
update['expected_lock_version'] = draft['lock_version']
|
||||
saved = service.save_draft(update, actor_id=None, profile_id=draft['id'])
|
||||
replacement = service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
|
||||
)
|
||||
|
||||
assert replacement['version'] == 2
|
||||
assert db.session.get(ShippingOrderDocumentProfile, published['id']).status == 'retired'
|
||||
assert ShippingOrderDocumentProfile.query.filter_by(
|
||||
profile_code='PO_312207', status='published',
|
||||
).one().id == replacement['id']
|
||||
|
||||
|
||||
def test_profile_rejects_unknown_field_and_stale_lock(app):
|
||||
"""Profile 不得引用未绑定 Schema 字段,草稿并发更新不得后写覆盖。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
invalid = _data(schema.id)
|
||||
invalid['definition']['column_rules'][0]['target_field_codes'] = ['unknown_field']
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.save_draft(invalid, actor_id=None)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
|
||||
draft = service.save_draft(_data(schema.id), actor_id=None)
|
||||
stale = _data(schema.id, fingerprint='d' * 64)
|
||||
stale['expected_lock_version'] = draft['lock_version'] + 1
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.save_draft(stale, actor_id=None, profile_id=draft['id'])
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT'
|
||||
|
||||
duplicate = _data(schema.id)
|
||||
duplicate['profile_code'] = 'PO_DUPLICATE_TARGET'
|
||||
duplicate['definition']['column_rules'][1]['target_field_codes'] = ['customer_part_number']
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.save_draft(duplicate, actor_id=None)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_profile_admin_api_requires_admin_and_uses_standard_errors(app):
|
||||
"""普通用户不能维护 Profile;管理员错误使用统一业务 envelope。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
schema_id = schema.id
|
||||
db.session.add_all([
|
||||
User(username='profile-admin', email='profile-admin@example.com', role='admin', status='active'),
|
||||
User(username='profile-user', email='profile-user@example.com', role='user', status='active'),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
client = app.test_client()
|
||||
denied = client.post(
|
||||
'/api/admin/shipping-notice/order-document-profiles',
|
||||
json=_data(schema_id),
|
||||
headers={'X-Username': 'profile-user', 'X-Role': 'user'},
|
||||
)
|
||||
assert denied.status_code == 403
|
||||
|
||||
created = client.post(
|
||||
'/api/admin/shipping-notice/order-document-profiles',
|
||||
json=_data(schema_id),
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert created.status_code == 201
|
||||
payload = parse_api_data(created.get_json())
|
||||
assert payload['profile_code'] == 'PO_312207'
|
||||
|
||||
conflict = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}",
|
||||
json={**_data(schema_id), 'expected_lock_version': payload['lock_version'] + 1},
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert conflict.status_code == 409
|
||||
assert parse_api_error(conflict.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT'
|
||||
|
||||
|
||||
def test_profile_sample_api_supports_secure_preview_create_and_version_update(app):
|
||||
"""样本 API 必须鉴权、隐藏 HTML、服务端计算指纹,并支持新版本按乐观锁重配。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
user = User(username='sample-owner', email='sample-owner@example.com', role='admin', status='active')
|
||||
regular_user = User(
|
||||
username='sample-user', email='sample-user@example.com', role='user', status='active',
|
||||
)
|
||||
db.session.add_all([user, regular_user])
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no='FA-PROFILE-SAMPLE', owner_user_id=user.id, original_filename='sample.pdf',
|
||||
storage_provider='minio', storage_bucket='test', storage_key='sample.pdf',
|
||||
content_hash='c' * 64, file_size=100, mime_type='application/pdf',
|
||||
upload_status='ready', lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-PROFILE-SAMPLE', asset_id=asset.id, user_id=user.id,
|
||||
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
html = (
|
||||
'<table><tr><th>Part Number</th><th>Vendor Item#</th><th>Qty</th></tr>'
|
||||
'<tr><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>3</td></tr></table>'
|
||||
)
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id, asset_id=asset.id, document_type='attachment',
|
||||
attachment_key='sample.pdf', filename='sample.pdf', content_hash='c' * 64,
|
||||
classification='order_notice', parse_status='parsed', extracted_text='sample',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru', 'provider_version': '3.1.14', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html}],
|
||||
})
|
||||
db.session.commit()
|
||||
document_id = document.id
|
||||
schema_id = schema.id
|
||||
|
||||
client = app.test_client()
|
||||
user_headers = {'X-Username': 'sample-user', 'X-Role': 'user'}
|
||||
admin_headers = {'X-Username': 'sample-owner', 'X-Role': 'admin'}
|
||||
denied = client.get(
|
||||
'/api/admin/shipping-notice/order-document-profile-samples', headers=user_headers,
|
||||
)
|
||||
assert denied.status_code == 403
|
||||
|
||||
samples_response = client.get(
|
||||
'/api/admin/shipping-notice/order-document-profile-samples', headers=admin_headers,
|
||||
)
|
||||
assert samples_response.status_code == 200
|
||||
samples = parse_api_data(samples_response.get_json())
|
||||
assert samples[0]['document_id'] == document_id
|
||||
|
||||
preview_response = client.get(
|
||||
f'/api/admin/shipping-notice/order-document-profile-samples/{document_id}/tables',
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert preview_response.status_code == 200
|
||||
preview = parse_api_data(preview_response.get_json())
|
||||
assert preview['tables'][0]['rows'][0] == ['Part Number', 'Vendor Item#', 'Qty']
|
||||
assert 'html' not in preview['tables'][0]
|
||||
assert 'bbox' not in preview['tables'][0]
|
||||
|
||||
sample_payload = {
|
||||
'profile_code': 'SAMPLE_TEMPLATE', 'display_name': 'Sample template',
|
||||
'schema_version_id': schema_id, 'document_id': document_id, 'table_id': 'table-1',
|
||||
'header_row_index': 0, 'data_start_row_index': 1, 'drop_zero_qty': True,
|
||||
'column_rules': [
|
||||
{'column_index': 0, 'extractor_key': 'direct', 'target_field_codes': ['customer_part_number']},
|
||||
{'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['part_number']},
|
||||
{'column_index': 2, 'extractor_key': 'direct', 'target_field_codes': ['qty']},
|
||||
],
|
||||
'structure_fingerprint': 'browser-forged-value',
|
||||
}
|
||||
created = client.post(
|
||||
'/api/admin/shipping-notice/order-document-profiles/from-sample',
|
||||
json=sample_payload, headers=admin_headers,
|
||||
)
|
||||
assert created.status_code == 201
|
||||
draft = parse_api_data(created.get_json())
|
||||
assert draft['structure_fingerprint'] != 'browser-forged-value'
|
||||
assert draft['definition']['structure_fingerprint'] == draft['structure_fingerprint']
|
||||
|
||||
published_response = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{draft['id']}/publish",
|
||||
json={'expected_lock_version': draft['lock_version']}, headers=admin_headers,
|
||||
)
|
||||
published = parse_api_data(published_response.get_json())
|
||||
clone_response = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{published['id']}/clone",
|
||||
headers=admin_headers,
|
||||
)
|
||||
clone = parse_api_data(clone_response.get_json())
|
||||
|
||||
stale = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{clone['id']}/from-sample",
|
||||
json={**sample_payload, 'expected_lock_version': clone['lock_version'] + 1},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert stale.status_code == 409
|
||||
assert parse_api_error(stale.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT'
|
||||
|
||||
updated_response = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{clone['id']}/from-sample",
|
||||
json={
|
||||
**sample_payload,
|
||||
'display_name': 'Sample template v2',
|
||||
'change_note': 'Reconfirmed against MinerU sample',
|
||||
'expected_lock_version': clone['lock_version'],
|
||||
},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert updated_response.status_code == 200
|
||||
updated = parse_api_data(updated_response.get_json())
|
||||
assert updated['id'] == clone['id']
|
||||
assert updated['display_name'] == 'Sample template v2'
|
||||
assert updated['change_note'] == 'Reconfirmed against MinerU sample'
|
||||
assert updated['lock_version'] == clone['lock_version'] + 1
|
||||
@@ -0,0 +1,120 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_dify_guide.py
|
||||
|
||||
用途:验证订单抽取 Dify 配置指南中的校验 Code 节点可执行且保持业务错误契约。
|
||||
依赖:订单抽取 Workflow 指南、标准 json/pathlib。
|
||||
逻辑:直接加载指南中的 Python 节点脚本,确保单文档字段错位被丢弃而非阻断跨文档聚合。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _validation_main():
|
||||
"""
|
||||
从 Dify 配置指南提取并编译订单校验节点的 main 函数。
|
||||
|
||||
Returns:
|
||||
callable: 与 Dify `VALIDATE_AND_NORMALIZE_ORDERS` 节点一致的入口函数。
|
||||
"""
|
||||
guide = Path(__file__).parents[2] / 'docs' / 'features' / 'shipping-notice' / 'order-extraction-workflow-dify-guide.md'
|
||||
source = guide.read_text(encoding='utf-8')
|
||||
marker = 'def _field_map(schema):'
|
||||
marker_index = source.index(marker)
|
||||
block_start = source.rfind('```python', 0, marker_index) + len('```python\n')
|
||||
block_end = source.index('\n```', marker_index)
|
||||
namespace: dict[str, object] = {}
|
||||
exec(source[block_start:block_end], namespace)
|
||||
return namespace['main']
|
||||
|
||||
|
||||
def _contract() -> dict:
|
||||
"""构造包含可选单价和必填需求数量的最小冻结 Schema 契约。"""
|
||||
return {
|
||||
'schema_version_id': 1,
|
||||
'checksum': 'checksum',
|
||||
'fields': [
|
||||
{
|
||||
'field_id': 'po-id', 'field_code': 'po_number', 'display_name': '采购订单号',
|
||||
'scope': 'header', 'value_type': 'string', 'collection_mode': 'llm_extraction',
|
||||
'required': True, 'validator_keys': ['non_empty'],
|
||||
},
|
||||
{
|
||||
'field_id': 'unit-price-id', 'field_code': 'unit_price', 'display_name': '单价',
|
||||
'scope': 'line', 'value_type': 'decimal', 'collection_mode': 'llm_extraction',
|
||||
'required': False, 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty-id', 'field_code': 'qty', 'display_name': '需求数量',
|
||||
'scope': 'line', 'value_type': 'decimal', 'collection_mode': 'llm_extraction',
|
||||
'required': True, 'validator_keys': ['positive_decimal'],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _order(fields: list[dict]) -> dict:
|
||||
"""构造只含一条订单行的最小模型输出。"""
|
||||
return {
|
||||
'orders': [{
|
||||
'schema_version_id': 1, 'schema_checksum': 'checksum',
|
||||
'classification': 'shipping_request', 'classification_confidence': 0.98,
|
||||
'source_intake_no': 'SNI-TEST', 'primary_document_id': 1,
|
||||
'header_fields': [], 'lines': [{'fields': fields}], 'conflicts': [],
|
||||
}],
|
||||
}
|
||||
|
||||
|
||||
def _observation(field_id: str, value: object) -> dict:
|
||||
"""构造带当前 Document 逐字证据的字段 Observation。"""
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'observations': [{'value': value, 'document_id': 1, 'quote': str(value), 'confidence': 0.98}],
|
||||
}
|
||||
|
||||
|
||||
def test_dify_validation_drops_optional_numeric_field_type_mismatch():
|
||||
"""可选单价错填料号时应忽略该字段,保留必填需求数量并通过校验。"""
|
||||
main = _validation_main()
|
||||
result = main(
|
||||
json.dumps(_order([
|
||||
_observation('unit-price-id', 'D4-A08AR12000002'),
|
||||
_observation('qty-id', 30),
|
||||
])),
|
||||
json.dumps(_contract()), 'SNI-TEST', 1,
|
||||
)
|
||||
|
||||
assert result['validation_ok'] is True
|
||||
fields = json.loads(result['orders'])[0]['lines'][0]['fields']
|
||||
assert [item['field_id'] for item in fields] == ['qty-id']
|
||||
|
||||
|
||||
def test_dify_validation_drops_required_field_type_mismatch_for_partial_unit():
|
||||
"""单文档的必填 Qty 类型错误只丢弃该字段,完整性由 HXOPS 跨文档判断。"""
|
||||
main = _validation_main()
|
||||
result = main(
|
||||
json.dumps(_order([_observation('qty-id', 'thirty')])),
|
||||
json.dumps(_contract()), 'SNI-TEST', 1,
|
||||
)
|
||||
|
||||
assert result['validation_ok'] is True
|
||||
normalized = json.loads(result['orders'])
|
||||
assert normalized[0]['lines'] == []
|
||||
assert result['validation_error'] == ''
|
||||
|
||||
|
||||
def test_dify_validation_accepts_email_header_fragment_without_order_lines():
|
||||
"""EML 只提供 PO 等 Header 证据时必须成功,等待 PDF Unit 补充订单行。"""
|
||||
main = _validation_main()
|
||||
payload = _order([])
|
||||
payload['orders'][0]['header_fields'] = [_observation('po-id', '4518738152')]
|
||||
payload['orders'][0]['lines'] = []
|
||||
|
||||
result = main(json.dumps(payload), json.dumps(_contract()), 'SNI-TEST', 1)
|
||||
|
||||
assert result['validation_ok'] is True
|
||||
normalized = json.loads(result['orders'])[0]
|
||||
assert normalized['lines'] == []
|
||||
assert normalized['header_fields'][0]['field_id'] == 'po-id'
|
||||
@@ -0,0 +1,315 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_quality_gate.py
|
||||
|
||||
用途:验证 L7 订单抽取双人影子标签、指标、双角色批准和 Runtime Binding 自动建单门禁。
|
||||
依赖:质量服务、Agent Runtime Binding、订单抽取 Run 测试夹具。
|
||||
逻辑:构造 100 个匿名一致样本达标批次,并覆盖分歧、权限边界和批准引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers.shipping_order_extraction import run_shipping_order_extraction
|
||||
from app.jobs.queue import claim_next_job
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent,
|
||||
ShippingOrderExtractionQualityBatch,
|
||||
ShippingOrderExtractionQualityLabel,
|
||||
ShippingOrderExtractionRun,
|
||||
User,
|
||||
)
|
||||
from app.services.agent_runtime_binding_service import save_runtime_binding
|
||||
from app.services.shipping_notice.order_extraction_quality_service import (
|
||||
approve_quality_batch,
|
||||
list_approved_quality_batches,
|
||||
quality_metrics,
|
||||
require_approved_quality_batch,
|
||||
save_quality_label,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.conftest import parse_api_data
|
||||
|
||||
|
||||
def _quality_batch(owner: Agent, schema_version_id: int, creator: User) -> ShippingOrderExtractionQualityBatch:
|
||||
"""建立 collecting 批次,供服务级测试批量注入匿名标签。"""
|
||||
batch = ShippingOrderExtractionQualityBatch(
|
||||
batch_no=f'SOQ-TEST-{owner.id}', owner_agent_id=owner.id,
|
||||
schema_version_id=schema_version_id,
|
||||
threshold_version='l7.v1', status='collecting', created_by_id=creator.id,
|
||||
)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
return batch
|
||||
|
||||
|
||||
def _add_agreed_samples(
|
||||
batch: ShippingOrderExtractionQualityBatch, runs: list[ShippingOrderExtractionRun],
|
||||
first: User, second: User,
|
||||
) -> None:
|
||||
"""为每个 Run 写入两份完全一致且无错误的匿名标签。"""
|
||||
for run in runs:
|
||||
for reviewer in (first, second):
|
||||
db.session.add(ShippingOrderExtractionQualityLabel(
|
||||
batch_id=batch.id, run_id=run.id, reviewer_id=reviewer.id,
|
||||
core_expected_count=4, core_extracted_count=4, core_correct_count=4,
|
||||
wrong_merge=False, wrong_split=False, wrong_auto_create=False,
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def test_quality_metrics_require_two_matching_reviews(app):
|
||||
"""单人和分歧标签不计样本;100 个一致样本才通过固定阈值。"""
|
||||
with app.app_context():
|
||||
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-METRICS')
|
||||
second = User(username='quality-second', email='quality-second@example.com', role='admin', password_hash='x')
|
||||
db.session.add(second)
|
||||
db.session.flush()
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
runs = []
|
||||
for index in range(100):
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'SNER-QUALITY-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
|
||||
conversation_id=f'quality-{index}', schema_version_id=batch.schema_version_id,
|
||||
input_snapshot_hash=f'{index:064x}'[-64:], input_snapshot_json={},
|
||||
idempotency_key=f'{index + 1000:064x}'[-64:], status='completed', phase='completed',
|
||||
provider_config_json={'auto_create_enabled': False},
|
||||
)
|
||||
db.session.add(run)
|
||||
runs.append(run)
|
||||
db.session.flush()
|
||||
_add_agreed_samples(batch, runs, user, second)
|
||||
|
||||
metrics = quality_metrics(batch)
|
||||
|
||||
assert metrics['eligible'] is True
|
||||
assert metrics['agreed_sample_count'] == 100
|
||||
assert metrics['precision'] == 1.0
|
||||
assert metrics['recall'] == 1.0
|
||||
|
||||
|
||||
def test_quality_label_rejects_wrong_owner_or_auto_create_run(app):
|
||||
"""标签只能引用同 Owner/Schema 的终态 unit.v3 影子 Run,不能标生产自动建单结果。"""
|
||||
with app.app_context():
|
||||
user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-LABEL')
|
||||
user.role = 'admin'
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no='SNER-QUALITY-INVALID', user_id=user.id, owner_agent_id=owner.id,
|
||||
conversation_id=session.session_id, schema_version_id=batch.schema_version_id,
|
||||
input_snapshot_hash='a' * 64, input_snapshot_json={}, idempotency_key='b' * 64,
|
||||
status='completed', phase='completed',
|
||||
provider_config_json={'auto_create_enabled': True},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
save_quality_label(
|
||||
batch_id=batch.id, run_no=run.run_no, actor_id=user.id,
|
||||
payload={'core_expected_count': 4, 'core_extracted_count': 4, 'core_correct_count': 4},
|
||||
)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_RUN_INVALID'
|
||||
|
||||
|
||||
def test_approved_quality_batch_is_required_for_auto_create_binding(app):
|
||||
"""unit.v3 自动建单必须引用同 Owner、当前阈值、双人批准且仍达标的批次。"""
|
||||
with app.app_context():
|
||||
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-BINDING')
|
||||
business = User(username='quality-business', email='quality-business@example.com', role='admin', password_hash='x')
|
||||
technical = User(username='quality-technical', email='quality-technical@example.com', role='admin', password_hash='x')
|
||||
db.session.add_all([business, technical])
|
||||
db.session.flush()
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
runs = []
|
||||
for index in range(100):
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'SNER-APPROVE-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
|
||||
conversation_id=f'approve-{index}', schema_version_id=batch.schema_version_id,
|
||||
input_snapshot_hash=f'{index + 2000:064x}'[-64:], input_snapshot_json={},
|
||||
idempotency_key=f'{index + 3000:064x}'[-64:], status='completed', phase='completed',
|
||||
provider_config_json={'auto_create_enabled': False},
|
||||
)
|
||||
db.session.add(run)
|
||||
runs.append(run)
|
||||
db.session.flush()
|
||||
_add_agreed_samples(batch, runs, business, technical)
|
||||
batch.status = 'ready'
|
||||
db.session.flush()
|
||||
approve_quality_batch(batch_id=batch.id, role='business', actor_id=business.id)
|
||||
approve_quality_batch(batch_id=batch.id, role='technical', actor_id=technical.id)
|
||||
provider = Agent.query.filter_by(exposure_mode='internal').first()
|
||||
|
||||
approved = require_approved_quality_batch(
|
||||
batch_id=batch.id, owner_agent_id=owner.id, schema_version_id=batch.schema_version_id,
|
||||
)
|
||||
binding = save_runtime_binding(
|
||||
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider.id, enabled=True, quality_batch_id=batch.id,
|
||||
config={'auto_create_enabled': True},
|
||||
)
|
||||
|
||||
assert approved.status == 'approved'
|
||||
assert binding.quality_batch_id == batch.id
|
||||
|
||||
|
||||
def test_same_admin_cannot_approve_both_roles(app):
|
||||
"""业务和技术批准必须由不同管理员完成。"""
|
||||
with app.app_context():
|
||||
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-APPROVERS')
|
||||
user.role = 'admin'
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
batch.status = 'ready'
|
||||
batch.business_approved_by_id = user.id
|
||||
batch.business_approved_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
|
||||
with pytest.raises(ConflictError):
|
||||
require_approved_quality_batch(
|
||||
batch_id=batch.id, owner_agent_id=owner.id, schema_version_id=batch.schema_version_id,
|
||||
)
|
||||
with pytest.raises(ConflictError):
|
||||
approve_quality_batch(batch_id=batch.id, role='technical', actor_id=user.id)
|
||||
|
||||
|
||||
def test_first_approval_freezes_labels_and_schema_mismatch_blocks_release(app):
|
||||
"""任一角色批准后标签不可变化,且旧 Schema 批次不能给新 Schema 的执行放行。"""
|
||||
with app.app_context():
|
||||
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-FREEZE')
|
||||
user.role = 'admin'
|
||||
second = User(username='quality-freeze-second', email='quality-freeze-second@example.com', role='admin', password_hash='x')
|
||||
db.session.add(second)
|
||||
db.session.flush()
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
runs = []
|
||||
for index in range(100):
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'SNER-FREEZE-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
|
||||
conversation_id=f'freeze-{index}', schema_version_id=batch.schema_version_id,
|
||||
input_snapshot_hash=f'{index + 4000:064x}'[-64:], input_snapshot_json={},
|
||||
idempotency_key=f'{index + 5000:064x}'[-64:], status='completed', phase='completed',
|
||||
provider_config_json={'auto_create_enabled': False},
|
||||
)
|
||||
db.session.add(run)
|
||||
runs.append(run)
|
||||
db.session.flush()
|
||||
_add_agreed_samples(batch, runs, user, second)
|
||||
batch.status = 'ready'
|
||||
db.session.flush()
|
||||
approve_quality_batch(batch_id=batch.id, role='business', actor_id=user.id)
|
||||
|
||||
with pytest.raises(ConflictError) as frozen:
|
||||
save_quality_label(
|
||||
batch_id=batch.id, run_no=runs[0].run_no, actor_id=second.id,
|
||||
payload={'core_expected_count': 5, 'core_extracted_count': 5, 'core_correct_count': 5},
|
||||
)
|
||||
with pytest.raises(ConflictError):
|
||||
require_approved_quality_batch(
|
||||
batch_id=batch.id, owner_agent_id=owner.id,
|
||||
schema_version_id=batch.schema_version_id + 1,
|
||||
)
|
||||
|
||||
assert frozen.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_IMMUTABLE'
|
||||
|
||||
|
||||
def test_approved_batch_is_listed_and_frozen_on_run(app):
|
||||
"""管理端候选只含当前 Schema 已批准批次,启用后 Run 必须冻结相同批次。"""
|
||||
with app.app_context():
|
||||
user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-RUN')
|
||||
business = User(username='quality-run-business', email='quality-run-business@example.com', role='admin', password_hash='x')
|
||||
technical = User(username='quality-run-technical', email='quality-run-technical@example.com', role='admin', password_hash='x')
|
||||
db.session.add_all([business, technical])
|
||||
db.session.flush()
|
||||
batch = _quality_batch(owner, 1, user)
|
||||
runs = []
|
||||
for index in range(100):
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'SNER-RUN-GATE-{index:03d}', user_id=user.id, owner_agent_id=owner.id,
|
||||
conversation_id=f'run-gate-{index}', schema_version_id=batch.schema_version_id,
|
||||
input_snapshot_hash=f'{index + 6000:064x}'[-64:], input_snapshot_json={},
|
||||
idempotency_key=f'{index + 7000:064x}'[-64:], status='completed', phase='completed',
|
||||
provider_config_json={'auto_create_enabled': False},
|
||||
)
|
||||
db.session.add(run)
|
||||
runs.append(run)
|
||||
db.session.flush()
|
||||
_add_agreed_samples(batch, runs, business, technical)
|
||||
batch.status = 'ready'
|
||||
db.session.flush()
|
||||
approve_quality_batch(batch_id=batch.id, role='business', actor_id=business.id)
|
||||
approve_quality_batch(batch_id=batch.id, role='technical', actor_id=technical.id)
|
||||
binding = Agent.query.filter_by(exposure_mode='internal').first()
|
||||
save_runtime_binding(
|
||||
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
|
||||
provider_agent_id=binding.id, enabled=True, quality_batch_id=batch.id,
|
||||
config={'auto_create_enabled': True},
|
||||
)
|
||||
|
||||
listed = list_approved_quality_batches(owner_agent_id=owner.id)
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=owner.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
|
||||
assert reused is False
|
||||
assert [item['id'] for item in listed] == [batch.id]
|
||||
assert run.quality_batch_id == batch.id
|
||||
assert run.provider_config_json['auto_create_enabled'] is True
|
||||
|
||||
db.session.commit()
|
||||
batch.threshold_version = 'obsolete-threshold'
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='quality-gate-worker',
|
||||
)
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.refresh(run)
|
||||
assert run.status == 'failed'
|
||||
assert run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_GATE_BLOCKED'
|
||||
|
||||
|
||||
def test_quality_batch_admin_api_is_protected_and_returns_safe_summary(app, client):
|
||||
"""质量批次列表仅管理员可读,且响应不暴露 Run、字段值、引文或单条标签。"""
|
||||
with app.app_context():
|
||||
user, owner, _session, _intake, _document = _seed_run_input(suffix='QUALITY-API')
|
||||
user.role = 'admin'
|
||||
db.session.flush()
|
||||
token = issue_local_access_token(user)
|
||||
db.session.commit()
|
||||
owner_id = owner.id
|
||||
admin_username = user.username
|
||||
|
||||
forbidden = client.get(
|
||||
f'/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id={owner_id}',
|
||||
headers={'X-Username': 'missing-quality-user', 'X-Role': 'user'},
|
||||
)
|
||||
auth = {'Authorization': f'Bearer {token}'}
|
||||
created = client.post(
|
||||
'/api/admin/shipping-notice/order-extraction-quality-batches',
|
||||
json={'owner_agent_id': owner_id, 'schema_version_id': 1},
|
||||
headers=auth,
|
||||
)
|
||||
listed = client.get(
|
||||
f'/api/admin/shipping-notice/order-extraction-quality-batches?owner_agent_id={owner_id}',
|
||||
headers=auth,
|
||||
)
|
||||
|
||||
assert forbidden.status_code in {401, 403}
|
||||
assert created.status_code == 201
|
||||
created_data = parse_api_data(created.get_json())
|
||||
assert created_data['status'] == 'collecting'
|
||||
assert listed.status_code == 200
|
||||
assert parse_api_data(listed.get_json()) == []
|
||||
serialized = str(created.get_json()).lower()
|
||||
assert all(key not in serialized for key in ('document', 'quote', 'orders', 'evidence_ref', 'cell_id', 'labels'))
|
||||
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_quality_migration.py
|
||||
|
||||
用途:验证 L7 质量批次/标签和 Runtime Binding 引用迁移可完整往返。
|
||||
依赖:Alembic Operations、SQLite 内存数据库、a71f8091a2b7 迁移。
|
||||
逻辑:构造最小父表,升级检查表/列/索引,降级确认完全移除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_extraction_quality_migration_round_trip(monkeypatch):
|
||||
"""质量表和 Binding 外键必须可独立升级、写入并完整降级。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a71f8091a2b7_add_order_extraction_quality_gate',
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
for name in ('agents', 'users', 'shipping_order_schema_versions', 'shipping_order_extraction_runs'):
|
||||
sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'agent_runtime_bindings', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('owner_agent_id', sa.Integer()),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_order_extraction_quality_batches' in inspector.get_table_names()
|
||||
assert 'shipping_order_extraction_quality_labels' in inspector.get_table_names()
|
||||
assert 'quality_batch_id' in {
|
||||
item['name'] for item in inspector.get_columns('agent_runtime_bindings')
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_order_extraction_quality_batches' not in inspector.get_table_names()
|
||||
assert 'shipping_order_extraction_quality_labels' not in inspector.get_table_names()
|
||||
assert 'quality_batch_id' not in {
|
||||
item['name'] for item in inspector.get_columns('agent_runtime_bindings')
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_run_quality_migration.py
|
||||
|
||||
用途:验证订单抽取 Run 冻结质量批次引用的迁移可完整往返。
|
||||
依赖:Alembic Operations、SQLite 内存数据库、a72f8091a2b8 迁移。
|
||||
逻辑:构造最小父表,升级检查外键列与索引,降级确认引用被移除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_extraction_run_quality_migration_round_trip(monkeypatch):
|
||||
"""Run 质量批次外键必须可独立升级、写入并完整降级。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a72f8091a2b8_freeze_quality_batch_on_order_extraction_run',
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'shipping_order_extraction_quality_batches', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_extraction_runs', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'quality_batch_id' in {
|
||||
item['name'] for item in inspector.get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
assert 'ix_shipping_order_extraction_runs_quality_batch' in {
|
||||
item['name'] for item in inspector.get_indexes('shipping_order_extraction_runs')
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'quality_batch_id' not in {
|
||||
item['name'] for item in inspector.get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
|
||||
|
||||
def test_quality_binding_migration_round_trip(monkeypatch):
|
||||
"""Binding 与 Run 的质量批次引用必须一起升级和完整降级。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a77f8091a2c3_add_order_extraction_quality_binding',
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'shipping_order_extraction_quality_batches', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'):
|
||||
sa.Table(table_name, metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'):
|
||||
assert 'quality_batch_id' in {
|
||||
item['name'] for item in inspector.get_columns(table_name)
|
||||
}
|
||||
assert f'ix_{table_name}_quality_batch_id' in {
|
||||
item['name'] for item in inspector.get_indexes(table_name)
|
||||
}
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
for table_name in ('agent_runtime_bindings', 'shipping_order_extraction_runs'):
|
||||
assert 'quality_batch_id' not in {
|
||||
item['name'] for item in inspector.get_columns(table_name)
|
||||
}
|
||||
@@ -24,12 +24,15 @@ from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingNoticeCandidate,
|
||||
Job,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderExtractionDiagnosticAudit,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
@@ -37,7 +40,9 @@ from app.models import (
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
mark_order_extraction_run_seen,
|
||||
reparse_order_extraction_run,
|
||||
retry_order_extraction_run,
|
||||
serialize_order_extraction_message_state,
|
||||
serialize_order_extraction_run,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
@@ -166,6 +171,7 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app):
|
||||
assert intake.order_extraction_status == 'extracting'
|
||||
assert run.input_snapshot_json['schema']['checksum'] == 'a' * 64
|
||||
assert run.input_snapshot_json['schema']['extraction_contract']['fields'][0]['field_id'] == 'qty-id'
|
||||
assert run.input_snapshot_json['snapshot_version'] == 3
|
||||
assert run.input_snapshot_json['intakes'][0]['documents'][0]['document_id'] == document.id
|
||||
assert run.input_snapshot_json['intakes'][0]['documents'][0]['extracted_text'] == 'PO 451883815A QTY 30 EA'
|
||||
# 确定性上下文保留在HXOPS冻结快照;Workflow编译时才从documents强制剔除。
|
||||
@@ -175,6 +181,7 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app):
|
||||
plan = ShippingOrderExtractionPlan.query.filter_by(run_id=run.id).one()
|
||||
assert plan.plan_version == 'shipping_order_extraction.plan.v1'
|
||||
assert len(plan.plan_version) == 33
|
||||
|
||||
assert plan.input_snapshot_hash == run.input_snapshot_hash
|
||||
assert plan.status == 'planned'
|
||||
assert plan.unit_count == 1
|
||||
@@ -199,6 +206,102 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app):
|
||||
assert ShippingOrderExtractionUnit.query.count() == 1
|
||||
|
||||
|
||||
def test_run_v3_freezes_layout_schema_candidate_without_exposing_it_to_dify(app):
|
||||
"""Run v3 应冻结真实 layout cell 映射,但 Workflow Manifest 必须完全剥离内部证据。"""
|
||||
from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from app.services.shipping_notice.order_extraction_workflow import build_order_extraction_workflow_inputs
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='B')
|
||||
document.content_hash = 'b' * 64
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
schema.definition_json = {'fields': [{
|
||||
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
|
||||
'value_type': 'decimal', 'enabled': True, 'required': True,
|
||||
'aliases': ['Qty'], 'normalizer_key': 'decimal',
|
||||
'validator_keys': ['positive_decimal'],
|
||||
}]}
|
||||
layout = build_html_layout_candidate(
|
||||
document_id=document.id, content_hash=document.content_hash,
|
||||
tables=['<table><tr><th>Qty</th></tr><tr><td>30</td></tr></table>'],
|
||||
)
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'eml-html-dom', 'backend': 'html', 'status': 'needs_review',
|
||||
'tables': [], 'layout_candidate': layout.model_dump(mode='json'), 'issues': [],
|
||||
})
|
||||
db.session.commit()
|
||||
|
||||
run, _reused = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
frozen_document = run.input_snapshot_json['intakes'][0]['documents'][0]
|
||||
candidates = frozen_document['layout_schema_candidates']
|
||||
assert run.input_snapshot_json['snapshot_version'] == 3
|
||||
assert candidates[0]['mapping_status'] == 'candidate'
|
||||
assert candidates[0]['rows'][0]['fields'][0]['cell_id']
|
||||
assert 'layout_table_not_accepted' in candidates[0]['issues']
|
||||
|
||||
manifest = build_order_extraction_workflow_inputs(
|
||||
run, unit=run.extraction_plan.units[0],
|
||||
)['execution_manifest']
|
||||
assert 'layout_schema_candidates' not in manifest
|
||||
assert 'layout_candidate' not in manifest
|
||||
|
||||
|
||||
def test_create_run_freezes_published_order_document_profile_definition(app):
|
||||
"""Run 必须复制完整 published Profile;创建后修改数据库行不得污染已排队快照。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='PROFILE')
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='PO_312207',
|
||||
display_name='PO template',
|
||||
version=1,
|
||||
status='published',
|
||||
schema_version_id=schema.id,
|
||||
structure_fingerprint='b' * 64,
|
||||
definition_json={
|
||||
'contract_version': 'shipping_order_document_profile.v1',
|
||||
'structure_fingerprint': 'b' * 64,
|
||||
'header_row_index': 0,
|
||||
'data_start_row_index': 1,
|
||||
'row_structure': 'preserved',
|
||||
'drop_zero_qty': True,
|
||||
'column_rules': [],
|
||||
},
|
||||
checksum='c' * 64,
|
||||
published_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.commit()
|
||||
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
assert reused is False
|
||||
frozen = run.input_snapshot_json['order_document_profiles']
|
||||
assert frozen == [{
|
||||
'profile_id': profile.id,
|
||||
'profile_code': 'PO_312207',
|
||||
'version': 1,
|
||||
'checksum': 'c' * 64,
|
||||
'schema_version_id': schema.id,
|
||||
'structure_fingerprint': 'b' * 64,
|
||||
'definition': profile.definition_json,
|
||||
}]
|
||||
profile.definition_json = {**profile.definition_json, 'drop_zero_qty': False}
|
||||
db.session.commit()
|
||||
assert run.input_snapshot_json['order_document_profiles'][0]['definition']['drop_zero_qty'] is True
|
||||
|
||||
|
||||
def test_run_plan_creates_email_relation_and_attachment_units_in_frozen_order(app):
|
||||
"""邮件正文和附件必须成为彼此隔离、顺序稳定的计划单元。"""
|
||||
with app.app_context():
|
||||
@@ -580,6 +683,30 @@ def test_run_progress_health_is_computed_server_side(app):
|
||||
assert serialize_order_extraction_run(run)['progress']['health'] == 'normal'
|
||||
|
||||
|
||||
def test_user_run_summary_never_exposes_worker_error_text(app):
|
||||
"""Workspace status cards expose a stable error code, never Provider or Worker details."""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='USER-ERROR-REDACTION')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='running')
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED',
|
||||
error_message='Provider stack trace contains a confidential document fragment',
|
||||
)
|
||||
|
||||
payload = serialize_order_extraction_run(run)
|
||||
assert payload['error'] == {'code': 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED'}
|
||||
assert 'confidential document fragment' not in str(payload)
|
||||
|
||||
message_state = serialize_order_extraction_message_state(run)
|
||||
assert message_state['message'] == ''
|
||||
assert 'confidential document fragment' not in str(message_state)
|
||||
|
||||
|
||||
def test_terminal_run_attention_is_new_only_seen_idempotently_and_resets_on_retry(app):
|
||||
"""终态才生成提醒;确认幂等,失败重试清除旧周期并为下一次终态重新生成提醒。"""
|
||||
with app.app_context():
|
||||
@@ -813,7 +940,8 @@ def test_terminal_transition_updates_persisted_chat_state(app):
|
||||
db.session.refresh(log)
|
||||
assert log.payload['shipping_order_extraction_state']['status'] == 'failed'
|
||||
assert log.payload['shipping_order_extraction_state']['terminal'] is True
|
||||
assert log.payload['shipping_order_extraction_state']['message'] == 'failed once'
|
||||
# The persisted card is user-visible on history replay, so it must not retain worker text.
|
||||
assert log.payload['shipping_order_extraction_state']['message'] == ''
|
||||
|
||||
|
||||
def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, client):
|
||||
@@ -858,7 +986,8 @@ def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, clie
|
||||
state = response.get_json()[-1]['payload']['shipping_order_extraction_state']
|
||||
assert state['status'] == 'failed'
|
||||
assert state['terminal'] is True
|
||||
assert state['message'] == 'failed before card persisted'
|
||||
assert state['message'] == ''
|
||||
assert 'failed before card persisted' not in str(response.get_json())
|
||||
|
||||
|
||||
def test_chat_history_does_not_project_user_run_anchor_as_duplicate_state_card(app, client):
|
||||
@@ -947,6 +1076,70 @@ def test_failed_run_retry_api_returns_queued_run(app, client):
|
||||
assert payload['run']['phase'] == 'manual_retry_queued'
|
||||
|
||||
|
||||
def test_terminal_run_reparse_api_creates_versioned_run_and_hides_cross_user(app, client):
|
||||
"""工作台重新识别 API 只能创建本人终态 Run 的新版本,重复请求复用活跃版本。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-API')
|
||||
source, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(source, target_status='running')
|
||||
transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1})
|
||||
transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1})
|
||||
other = User(username='reparse-api-other', email='reparse-api-other@example.com', password_hash='x')
|
||||
db.session.add(other)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
other_token = issue_local_access_token(other)
|
||||
run_no = source.run_no
|
||||
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse',
|
||||
json={'reason': 'field_mapping_error', 'comment': 'column shifted'},
|
||||
headers={'Authorization': f'Bearer {token}'},
|
||||
)
|
||||
assert response.status_code == 202
|
||||
payload = response.get_json()['data']
|
||||
assert payload['reused'] is False
|
||||
assert payload['run']['reparse']['source_run_no'] == run_no
|
||||
replay = client.post(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse',
|
||||
json={'reason': 'field_mapping_error'}, headers={'Authorization': f'Bearer {token}'},
|
||||
)
|
||||
assert replay.status_code == 202
|
||||
assert replay.get_json()['data']['reused'] is True
|
||||
hidden = client.post(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse',
|
||||
json={'reason': 'other'}, headers={'Authorization': f'Bearer {other_token}'},
|
||||
)
|
||||
assert hidden.status_code == 404
|
||||
|
||||
|
||||
def test_reparse_api_requires_valid_reason_and_json_object(app, client):
|
||||
"""API 不接收自由原因或非对象请求体,避免审计分类失真。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-API-INVALID')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='running')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='failed')
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
run_no = run.run_no
|
||||
invalid = client.post(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse',
|
||||
json={'reason': 'free text'}, headers={'Authorization': f'Bearer {token}'},
|
||||
)
|
||||
assert invalid.status_code == 400
|
||||
assert invalid.get_json()['error']['code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REPARSE_REASON_INVALID'
|
||||
malformed = client.post(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse',
|
||||
json=[], headers={'Authorization': f'Bearer {token}'},
|
||||
)
|
||||
assert malformed.status_code == 400
|
||||
|
||||
|
||||
def test_run_api_rejects_non_object_json(app, client):
|
||||
"""请求体为 JSON 数组时应返回标准 400,而不是调用 `.get` 产生 500。"""
|
||||
with app.app_context():
|
||||
@@ -1090,6 +1283,146 @@ def test_terminal_run_releases_intake_occupancy(app):
|
||||
assert replacement.id != run.id
|
||||
|
||||
|
||||
def test_reparse_creates_new_run_with_lineage_and_current_snapshot(app):
|
||||
"""重新识别必须创建新 Run、冻结当前发布配置,并保存来源谱系和原因。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE')
|
||||
source, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(source, target_status='running')
|
||||
transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1})
|
||||
transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1})
|
||||
db.session.commit()
|
||||
|
||||
replacement, reused = reparse_order_extraction_run(
|
||||
user_id=user.id, run_no=source.run_no, reason='field_mapping_error', comment='column shifted',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
assert reused is False
|
||||
assert replacement.id != source.id
|
||||
assert replacement.reparse_of_run_id == source.id
|
||||
assert replacement.reparse_reason == 'field_mapping_error'
|
||||
assert replacement.reparse_comment == 'column shifted'
|
||||
assert source.superseded_by_run_id == replacement.id
|
||||
assert source.superseded_at is not None
|
||||
assert replacement.provider_result_json is None
|
||||
serialized = serialize_order_extraction_run(replacement)
|
||||
assert serialized['reparse']['difference_summary'] == {
|
||||
'schema_changed': False, 'profile_changed': False, 'layout_changed': False,
|
||||
}
|
||||
assert 'root text' not in str(serialized).lower()
|
||||
replay, replayed = reparse_order_extraction_run(
|
||||
user_id=user.id, run_no=source.run_no, reason='field_mapping_error',
|
||||
)
|
||||
assert replayed is True
|
||||
assert replay.id == replacement.id
|
||||
|
||||
|
||||
def test_reparse_freezes_current_document_schema_and_layout_without_reprocessing_layout(app, monkeypatch):
|
||||
"""重新识别重新冻结当前规则/布局快照,但不得在用户链路直接启动 MinerU/OpenCV。"""
|
||||
from app.services.shipping_notice.document_layout import lifecycle
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REPARSE-SNAPSHOT')
|
||||
source, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(source, target_status='running')
|
||||
transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1})
|
||||
transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1})
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
document.extracted_text = 'PO 451883815 SNAPSHOT QTY 42 EA'
|
||||
schema.definition_json = {**schema.definition_json, 'reparse_marker': 'current-published-rule'}
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
lifecycle, 'schedule_document_layouts',
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError('user reparse must not schedule layout')),
|
||||
)
|
||||
|
||||
replacement, _ = reparse_order_extraction_run(
|
||||
user_id=user.id, run_no=source.run_no, reason='rule_updated',
|
||||
)
|
||||
|
||||
assert replacement.input_snapshot_hash != source.input_snapshot_hash
|
||||
assert replacement.input_snapshot_json['intakes'][0]['documents'][0]['extracted_text'].endswith('42 EA')
|
||||
assert replacement.input_snapshot_json['schema']['definition']['reparse_marker'] == 'current-published-rule'
|
||||
assert replacement.provider_result_json is None
|
||||
|
||||
|
||||
def test_reparse_rejects_non_terminal_run_and_invalid_reason(app):
|
||||
"""运行中 Run 与未受控原因不得创建新版本,避免并发耗费和审计失真。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-INVALID')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
with pytest.raises(ConflictError) as active:
|
||||
reparse_order_extraction_run(user_id=user.id, run_no=run.run_no, reason='other')
|
||||
assert active.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE'
|
||||
transition_order_extraction_run(run, target_status='running')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='failed')
|
||||
with pytest.raises(ValidationError) as reason:
|
||||
reparse_order_extraction_run(user_id=user.id, run_no=run.run_no, reason='free text')
|
||||
assert reason.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REPARSE_REASON_INVALID'
|
||||
|
||||
|
||||
def test_failed_reparse_restores_source_candidate_version(app):
|
||||
"""新版运行期间旧候选必须只读;新版失败后只恢复来源版本的可审核资格。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REPARSE-RESTORE')
|
||||
source, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(source, target_status='running')
|
||||
transition_order_extraction_run(source, target_status='result_persisted', result={'pending_count': 1})
|
||||
transition_order_extraction_run(source, target_status='needs_review', result={'pending_count': 1})
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-REPARSE-RESTORE', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='restore-version', order_extraction_run_id=source.id,
|
||||
selected=True, is_current_version=True, validation_status='ready',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.commit()
|
||||
|
||||
replacement, _ = reparse_order_extraction_run(
|
||||
user_id=user.id, run_no=source.run_no, reason='rule_updated',
|
||||
)
|
||||
db.session.flush()
|
||||
assert candidate.is_current_version is False
|
||||
assert candidate.selected is False
|
||||
assert candidate.selected_before_superseded is True
|
||||
transition_order_extraction_run(replacement, target_status='running')
|
||||
transition_order_extraction_run(replacement, target_status='failed', error_message='provider unavailable')
|
||||
db.session.flush()
|
||||
|
||||
assert candidate.is_current_version is True
|
||||
assert candidate.selected is True
|
||||
assert candidate.selected_before_superseded is None
|
||||
assert source.superseded_by_run_id is None
|
||||
|
||||
|
||||
def test_only_current_version_candidate_can_be_consumed(app):
|
||||
"""旧版本 Candidate 即使被直接提交,也必须被建单入口拒绝。"""
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
|
||||
|
||||
with app.app_context():
|
||||
user, _agent, _session, intake, document = _seed_run_input(suffix='SUPERSEDED')
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-SUPERSEDED', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='old-version', selected=True, is_current_version=False, validation_status='ready',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
create_shipping_batch_from_candidates(
|
||||
user_id=user.id, intake_nos=[intake.intake_no], candidate_nos=[candidate.candidate_no],
|
||||
create_idempotency_key='test-current-version-gate', conversation_id=None,
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.CANDIDATE_NOT_FOUND'
|
||||
|
||||
|
||||
def test_order_extraction_health_reports_backlog_latency_and_safe_errors(app):
|
||||
"""管理员健康汇总应识别积压/失败并只返回安全运行元数据。"""
|
||||
from app.services.shipping_notice.order_extraction_run_service import get_order_extraction_run_health
|
||||
@@ -1181,6 +1514,34 @@ def test_order_extraction_diagnostic_apis_are_admin_only_audited_and_redacted(ap
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
job.error_message = 'secret job error'
|
||||
job.payload_json = {'documents': 'secret document body'}
|
||||
extraction = ShippingOrderExtraction(
|
||||
run_id=run.id, intake_id=intake.id, schema_version_id=run.schema_version_id,
|
||||
input_snapshot_hash='d' * 64, status='needs_review',
|
||||
validation_result_json={
|
||||
'blocked_fields': ['qty'],
|
||||
'deterministic_table_issues': [{
|
||||
'reason': 'layout_table_needs_review', 'document_id': _document.id,
|
||||
'field_codes': ['qty'], 'cell_id': 'must-not-leak-cell',
|
||||
}],
|
||||
},
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingOrderFieldObservation(
|
||||
extraction_id=extraction.id, field_id='qty-id', source_type='attachment_table',
|
||||
extractor='layout_schema_mapping', raw_value_json=30, normalized_value_json=30,
|
||||
evidence_quote='must-not-leak-quote', evidence_ref='layout:secret-cell',
|
||||
evidence_metadata_json={'kind': 'layout_cell', 'cell_id': 'must-not-leak-cell'},
|
||||
confidence='1.0000', evidence_verified=True,
|
||||
),
|
||||
ShippingOrderFieldObservation(
|
||||
extraction_id=extraction.id, field_id='qty-id', source_type='attachment_text',
|
||||
extractor='dify_dynamic_schema', raw_value_json=30, normalized_value_json=30,
|
||||
evidence_quote='must-not-leak-text', evidence_ref=None,
|
||||
confidence='0.9000', evidence_verified=True,
|
||||
),
|
||||
])
|
||||
job_id = job.id
|
||||
admin = User(username='diagnostic-admin', email='diagnostic-admin@example.com', role='admin', password_hash='x')
|
||||
normal = User(username='diagnostic-normal', email='diagnostic-normal@example.com', role='user', password_hash='x')
|
||||
@@ -1206,6 +1567,12 @@ def test_order_extraction_diagnostic_apis_are_admin_only_audited_and_redacted(ap
|
||||
payload = detail.get_json()['data']
|
||||
assert payload['run']['error_code'] == 'UPSTREAM.TIMEOUT'
|
||||
assert payload['job_attempts'][0]['job_id'] == job_id
|
||||
assert payload['evidence_gate'] == {
|
||||
'accepted_observation_count': 2,
|
||||
'traceable_observation_count': 1,
|
||||
'traceable_rate': 0.5,
|
||||
'issue_counts': {'layout_table_needs_review': 1},
|
||||
}
|
||||
assert str(payload).lower().count('secret') == 0
|
||||
with app.app_context():
|
||||
assert ShippingOrderExtractionDiagnosticAudit.query.filter_by(admin_user_id=admin.id).count() == 2
|
||||
@@ -0,0 +1,54 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_layout_evidence_migration.py
|
||||
|
||||
用途:验证 L6 Observation 版面证据迁移可独立升级和降级。
|
||||
依赖:Alembic Operations、SQLite 内存库、a70f8091a2b6 迁移。
|
||||
逻辑:构造上一 revision 最小 Observation 表,检查新增列及无损降级。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_layout_evidence_migration_round_trip(monkeypatch):
|
||||
"""新增列必须可写结构化证据,降级后旧 Observation 数据仍保留。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a70f8091a2b6_add_order_observation_layout_evidence',
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
observations = sa.Table(
|
||||
'shipping_order_field_observations', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('field_id', sa.String(36), nullable=False),
|
||||
sa.Column('normalized_value_json', sa.JSON()),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
connection.execute(observations.insert().values(
|
||||
id=1, field_id='qty-id', normalized_value_json=30,
|
||||
))
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
|
||||
migration.upgrade()
|
||||
columns = {item['name'] for item in sa.inspect(connection).get_columns(observations.name)}
|
||||
assert {'evidence_ref', 'evidence_metadata_json'} <= columns
|
||||
connection.execute(sa.text(
|
||||
"UPDATE shipping_order_field_observations "
|
||||
"SET evidence_ref = :ref, evidence_metadata_json = :metadata WHERE id = 1",
|
||||
), {'ref': 'layout:1:p1:t1:c1', 'metadata': '{"page_no": 1}'})
|
||||
|
||||
migration.downgrade()
|
||||
columns = {item['name'] for item in sa.inspect(connection).get_columns(observations.name)}
|
||||
assert 'evidence_ref' not in columns
|
||||
assert 'evidence_metadata_json' not in columns
|
||||
assert connection.execute(sa.text(
|
||||
'SELECT field_id FROM shipping_order_field_observations WHERE id = 1',
|
||||
)).scalar_one() == 'qty-id'
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_schema_policy_repair_migration.py
|
||||
|
||||
用途:验证订单 Schema 自动建单策略列的结构漂移修复迁移。
|
||||
依赖:Alembic Operations、SQLite 内存数据库、a76f8091a2c2 迁移。
|
||||
逻辑:覆盖缺列升级、已有列幂等升级和降级,确保不同环境均能安全推进。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def _columns(connection) -> set[str]:
|
||||
"""
|
||||
返回测试库订单 Schema 表的列集合。
|
||||
|
||||
Args:
|
||||
connection: 当前 SQLite 迁移连接。
|
||||
|
||||
Returns:
|
||||
set[str]: 表中实际存在的列名。
|
||||
"""
|
||||
return {
|
||||
item['name'] for item in sa.inspect(connection).get_columns('shipping_order_schemas')
|
||||
}
|
||||
|
||||
|
||||
def test_order_schema_policy_repair_migration_round_trip(monkeypatch):
|
||||
"""缺列环境升级后应补列,重复升级不报错,降级后应移除。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a76f8091a2c2_repair_order_schema_auto_creation_policy',
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'shipping_order_schemas', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('schema_code', sa.String(64), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
monkeypatch.setattr(
|
||||
migration, 'op', Operations(MigrationContext.configure(connection)),
|
||||
)
|
||||
|
||||
migration.upgrade()
|
||||
migration.upgrade()
|
||||
assert 'auto_creation_policy_json' in _columns(connection)
|
||||
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_order_schemas (id, schema_code) VALUES (1, 'SHIPPING_ORDER')",
|
||||
))
|
||||
stored = connection.execute(sa.text(
|
||||
'SELECT auto_creation_policy_json FROM shipping_order_schemas WHERE id = 1',
|
||||
)).scalar_one()
|
||||
assert stored in ({}, '{}')
|
||||
|
||||
migration.downgrade()
|
||||
migration.downgrade()
|
||||
assert 'auto_creation_policy_json' not in _columns(connection)
|
||||
|
||||
|
||||
def test_order_schema_policy_repair_accepts_existing_column(monkeypatch):
|
||||
"""已正确包含目标列的环境执行升级时不得重复添加或改变现有数据。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.a76f8091a2c2_repair_order_schema_auto_creation_policy',
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
table = sa.Table(
|
||||
'shipping_order_schemas', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('auto_creation_policy_json', sa.JSON(), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
connection.execute(table.insert().values(id=1, auto_creation_policy_json={'enabled': True}))
|
||||
monkeypatch.setattr(
|
||||
migration, 'op', Operations(MigrationContext.configure(connection)),
|
||||
)
|
||||
|
||||
migration.upgrade()
|
||||
|
||||
assert connection.execute(sa.select(table.c.auto_creation_policy_json)).scalar_one() == {
|
||||
'enabled': True,
|
||||
}
|
||||
@@ -63,13 +63,36 @@ def _config(field_id: str, name: str, *, value_type: str) -> dict:
|
||||
def _save_and_publish(draft: dict, fields: list[dict]) -> dict:
|
||||
"""按乐观锁契约保存并发布运行时测试使用的 Schema。"""
|
||||
saved = service.save_draft(draft['id'], {
|
||||
'fields': fields, 'expected_lock_version': draft['lock_version'],
|
||||
'fields': fields,
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
return service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
|
||||
)
|
||||
|
||||
|
||||
def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
"""自动建单开关独立于版本;每个关键字段只保存自身的最低置信度。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
part_config = _config(part['id'], '内部料号', value_type='string')
|
||||
part_config.update({'auto_create_key_field': True, 'minimum_confidence': 0.95})
|
||||
qty_config = _config(qty['id'], '数量', value_type='decimal')
|
||||
qty_config.update({'auto_create_key_field': True, 'minimum_confidence': 0.90})
|
||||
|
||||
saved = service.save_draft(draft['id'], {
|
||||
'fields': [part_config, qty_config], 'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
by_code = {item['field_code']: item for item in saved['definition']['fields']}
|
||||
assert by_code['part_number']['minimum_confidence'] == 0.95
|
||||
assert by_code['qty']['minimum_confidence'] == 0.90
|
||||
assert service.get_auto_creation_policy() == {'enabled': False}
|
||||
assert service.save_auto_creation_policy({'enabled': True}, actor_id=None) == {'enabled': True}
|
||||
|
||||
|
||||
def test_schema_save_rejects_normalized_table_alias_collision(app):
|
||||
"""草稿保存阶段即应拒绝不同字段占用同一标准化表头,避免歧义进入发布版本。"""
|
||||
with app.app_context():
|
||||
@@ -92,7 +115,7 @@ def test_schema_save_rejects_normalized_table_alias_collision(app):
|
||||
|
||||
|
||||
def test_retired_run_schema_keeps_its_frozen_table_aliases(app):
|
||||
"""新版本改动别名后,锁定旧版本的 Run 仍必须按旧 definition 解析后端表格。"""
|
||||
"""旧别名仍可识别表格语义,但没有冻结 cell 证据时不得自动补字段。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
@@ -137,9 +160,13 @@ def test_retired_run_schema_keeps_its_frozen_table_aliases(app):
|
||||
actor_id=actor_id, schema_version_id=first['id'],
|
||||
)
|
||||
|
||||
assert result['lines'][0]['part_number'] == 'PART-FROZEN'
|
||||
assert result['lines'][0]['qty'] == '4'
|
||||
assert result['blocked_fields'] == []
|
||||
assert 'part_number' in result['blocked_fields']
|
||||
assert result['extraction'].validation_result_json['deterministic_table_issues'] == [{
|
||||
'document_id': int(documents[1].id),
|
||||
'reason': 'plain_text_table_has_no_cell_evidence',
|
||||
'field_codes': ['part_number', 'qty'],
|
||||
}]
|
||||
|
||||
|
||||
def test_duplicate_table_columns_force_dynamic_run_review(app):
|
||||
@@ -178,11 +205,107 @@ def test_duplicate_table_columns_force_dynamic_run_review(app):
|
||||
assert result['extraction'].status == 'needs_review'
|
||||
assert result['extraction'].validation_result_json['deterministic_table_issues'][0] == {
|
||||
'document_id': int(documents[1].id),
|
||||
'reason': 'ambiguous_table_headers',
|
||||
'reason': 'plain_text_table_has_no_cell_evidence',
|
||||
'field_codes': ['part_number'],
|
||||
}
|
||||
|
||||
|
||||
def test_accepted_layout_cell_persists_traceable_backend_observation(app):
|
||||
"""accepted L4 cell 可补模型缺失字段,且 Observation 必须保存完整稳定证据引用。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [
|
||||
_config(part['id'], '内部料号', value_type='string'),
|
||||
_config(qty['id'], '数量', value_type='decimal'),
|
||||
])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
pdf = documents[1]
|
||||
candidates = {int(pdf.id): [{
|
||||
'page_no': 2, 'table_id': 'table-main', 'mapping_status': 'accepted', 'issues': [],
|
||||
'rows': [{'row_index': 3, 'role': 'data', 'fields': [
|
||||
{
|
||||
'field_id': part['id'], 'value': 'PART-LAYOUT', 'quote': 'PART-LAYOUT',
|
||||
'column_index': 1, 'cell_id': 'cell-part',
|
||||
'evidence_ref': f'layout:{pdf.id}:p2:table-main:cell-part',
|
||||
},
|
||||
{
|
||||
'field_id': qty['id'], 'value': 4, 'quote': '4',
|
||||
'column_index': 2, 'cell_id': 'cell-qty',
|
||||
'evidence_ref': f'layout:{pdf.id}:p2:table-main:cell-qty',
|
||||
},
|
||||
]}],
|
||||
}]}
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [], 'lines': [{'fields': [{
|
||||
'field_id': part['id'], 'observations': [{
|
||||
'value': 'PART-LAYOUT', 'document_id': pdf.id,
|
||||
'quote': 'Part Number PART-100', 'confidence': 0.9,
|
||||
}],
|
||||
}]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='1' * 64, documents=documents, actor_id=actor_id,
|
||||
layout_candidates_by_document=candidates,
|
||||
)
|
||||
|
||||
assert result['blocked_fields'] == []
|
||||
assert result['lines'] == [{'part_number': 'PART-LAYOUT', 'qty': '4'}]
|
||||
observation = next(
|
||||
item for item in result['extraction'].observations
|
||||
if item.field_id == qty['id'] and item.extractor == 'layout_schema_mapping'
|
||||
)
|
||||
assert observation.evidence_verified is True
|
||||
assert observation.evidence_ref == f'layout:{pdf.id}:p2:table-main:cell-qty'
|
||||
assert observation.evidence_metadata_json == {
|
||||
'kind': 'layout_cell', 'page_no': 2, 'table_id': 'table-main',
|
||||
'row_index': 3, 'column_index': 2, 'cell_id': 'cell-qty',
|
||||
}
|
||||
|
||||
|
||||
def test_layout_row_cannot_be_associated_by_qty_across_documents(app):
|
||||
"""相同 Qty 不是业务身份,另一附件的 accepted 行不得据此补入当前订单。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [
|
||||
_config(part['id'], '内部料号', value_type='string'),
|
||||
_config(qty['id'], '数量', value_type='decimal'),
|
||||
])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
body, pdf = documents
|
||||
candidates = {int(pdf.id): [{
|
||||
'page_no': 1, 'table_id': 'other-table', 'mapping_status': 'accepted', 'issues': [],
|
||||
'rows': [{'row_index': 1, 'role': 'data', 'fields': [
|
||||
{'field_id': part['id'], 'value': 'WRONG-PART', 'quote': 'WRONG-PART', 'column_index': 0,
|
||||
'cell_id': 'wrong-part', 'evidence_ref': f'layout:{pdf.id}:p1:other-table:wrong-part'},
|
||||
{'field_id': qty['id'], 'value': 10, 'quote': '10', 'column_index': 1,
|
||||
'cell_id': 'wrong-qty', 'evidence_ref': f'layout:{pdf.id}:p1:other-table:wrong-qty'},
|
||||
]}],
|
||||
}]}
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [], 'lines': [{'fields': [{
|
||||
'field_id': qty['id'], 'observations': [{
|
||||
'value': 10, 'document_id': body.id, 'quote': 'quantity 10', 'confidence': 0.9,
|
||||
}],
|
||||
}]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='2' * 64, documents=documents, actor_id=actor_id,
|
||||
layout_candidates_by_document=candidates,
|
||||
)
|
||||
|
||||
assert 'part_number' not in result['lines'][0]
|
||||
assert 'part_number' in result['blocked_fields']
|
||||
assert not any(item.extractor == 'layout_schema_mapping' for item in result['extraction'].observations)
|
||||
|
||||
|
||||
def _seed_documents() -> tuple[int, list[ShippingNoticeDocument], int]:
|
||||
"""创建同一 Intake 下的邮件正文和 PDF Document,供跨文档证据验证。"""
|
||||
user = User(username='dynamic-runtime', email='dynamic-runtime@example.com', password_hash='x')
|
||||
@@ -615,3 +738,69 @@ def test_dynamic_schema_accepts_equivalent_number_and_date_evidence_formats(app)
|
||||
# 断言格式化差异不会阻断三类字段,但每条证据仍必须引用当前文档中的原文片段。
|
||||
assert result['blocked_fields'] == []
|
||||
assert result['lines'] == [{'qty': '30', 'amount': '28252.8', 'required_date': '2026-06-29'}]
|
||||
|
||||
|
||||
def test_dynamic_schema_verifies_dify_quote_against_frozen_mineru_text(app):
|
||||
"""Dify 使用冻结 MinerU 文本时,旧 PDF 文本不含 quote 也必须接受同源料号和数量证据。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
qty = service.save_field({'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [
|
||||
_config(part['id'], '内部料号', value_type='string'),
|
||||
_config(qty['id'], '数量', value_type='decimal'),
|
||||
])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
document.extracted_text = 'legacy PDF text without the MinerU table'
|
||||
mineru_text = 'Vendor Item#\tB3-A08AR11000001\nQuantity\t7'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [],
|
||||
'lines': [{'fields': [
|
||||
{'field_id': part['id'], 'observations': [{
|
||||
'value': 'B3-A08AR11000001', 'document_id': document.id,
|
||||
'quote': 'Vendor Item#\tB3-A08AR11000001', 'confidence': 0.95,
|
||||
}]},
|
||||
{'field_id': qty['id'], 'observations': [{
|
||||
'value': 7, 'document_id': document.id, 'quote': 'Quantity\t7', 'confidence': 0.99,
|
||||
}]},
|
||||
]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='m' * 64, documents=documents, actor_id=actor_id,
|
||||
frozen_evidence_text_by_document={int(document.id): mineru_text},
|
||||
)
|
||||
|
||||
assert result['blocked_fields'] == []
|
||||
assert result['lines'] == [{'part_number': 'B3-A08AR11000001', 'qty': '7'}]
|
||||
|
||||
|
||||
def test_dynamic_schema_rejects_quote_absent_from_frozen_and_legacy_text(app):
|
||||
"""冻结 MinerU 文本不是宽松白名单;quote 未出现时仍必须拒绝 Observation。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [_config(part['id'], '内部料号', value_type='string')])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
document.extracted_text = 'legacy PDF text'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [],
|
||||
'lines': [{'fields': [{'field_id': part['id'], 'observations': [{
|
||||
'value': 'B3-A08AR11000001', 'document_id': document.id,
|
||||
'quote': 'Vendor Item#\tB3-A08AR11000001', 'confidence': 0.95,
|
||||
}]}]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='n' * 64, documents=documents, actor_id=actor_id,
|
||||
frozen_evidence_text_by_document={int(document.id): 'different MinerU text'},
|
||||
)
|
||||
|
||||
assert result['blocked_fields'] == ['part_number']
|
||||
assert result['lines'] == [{}]
|
||||
@@ -9,7 +9,18 @@ backend/tests/test_shipping_task_parsed_projection.py
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeCandidate, ShippingTask
|
||||
from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.document_candidate_persist import _serialize_candidate_brief
|
||||
from app.services.shipping_notice.query_service import serialize_task_detail
|
||||
|
||||
@@ -17,6 +28,27 @@ from app.services.shipping_notice.query_service import serialize_task_detail
|
||||
def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
|
||||
"""Task Detail 必须稳定顶层返回 lines 门禁与来源 Candidate 证据投影。"""
|
||||
with app.app_context():
|
||||
user = User(username='parsed-projection-user', email='parsed-projection@example.com', password_hash='x')
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Parsed projection')
|
||||
db.session.add_all([user, schema])
|
||||
db.session.flush()
|
||||
fields = {}
|
||||
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'), ('inventory_source_hint', 'string')):
|
||||
field = ShippingOrderField(schema_id=schema.id, field_code=code, scope='line', value_type=value_type)
|
||||
fields[code] = field
|
||||
db.session.add(field)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
definition_json={'fields': [
|
||||
{'field_id': field.id, 'field_code': code, 'scope': 'line'}
|
||||
for code, field in fields.items()
|
||||
]},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='SNC-PARSED-PROJECTION-001',
|
||||
intake_id=1,
|
||||
@@ -38,6 +70,7 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
|
||||
|
||||
task = ShippingTask(
|
||||
task_no='SN-PARSED-PROJECTION-001',
|
||||
user_id=user.id,
|
||||
source_type='manual',
|
||||
process_status='pending_review',
|
||||
po_number='4510038672',
|
||||
@@ -61,6 +94,28 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
|
||||
},
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='p' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for code, value in task.lines_json[0].items():
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=fields[code].id,
|
||||
decision_status='accepted', resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=fields[code].id,
|
||||
decision_id=decision.id, value_text=str(value) if code != 'qty' else None,
|
||||
value_decimal=value if code == 'qty' else None, value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
db.session.commit()
|
||||
|
||||
detail = serialize_task_detail(task)
|
||||
@@ -236,3 +291,8 @@ def test_candidate_update_persists_inventory_source_hint_round_trip(app):
|
||||
db.session.refresh(candidate)
|
||||
persisted = candidate.structured_result_json['business_summary']['lines'][0]
|
||||
assert persisted['inventory_source_hint'] == 'DBS DUB'
|
||||
history = candidate.structured_result_json['manual_review_history']
|
||||
assert history[-1]['action'] == 'business_summary_edited'
|
||||
assert history[-1]['actor_user_id'] == int(user.id)
|
||||
assert history[-1]['before_validation_status'] == 'needs_review'
|
||||
assert history[-1]['after_summary']['lines'][0]['reservation_id'] == '1000140351'
|
||||
+18
-1
@@ -113,6 +113,14 @@
|
||||
- 高置信发货需求只要包含可信内部料号 `part_number` + 正数 Qty 且有原文证据即可自动创建 Batch/Task;Reservation ID 缺失时 Task 必须停在自然对话补字段门禁;`inventory_source_hint` 是可选库存源路由线索,不作为必填门禁。
|
||||
- 低置信、证据不足、阻断冲突或可能修订的 Candidate 保留待处理;同 Intake 已自动建单部分不得导致剩余 Candidate 丢失。
|
||||
- 订单抽取最终必须以持久化 `ShippingOrderExtractionRun` 为业务生命周期真相;Run 冻结用户、入口 Agent、会话、Intake/Document 正文和 published Schema,幂等键由服务端快照计算,不依赖浏览器 request ID。
|
||||
- 订单附件结构化必须支持版本化订单文档 Profile。Profile 绑定一个不可变订单 Schema 版本,以表头网格精确结构指纹选择固定列规则,并把目标字段冻结为稳定 `field_id + field_code`。已发布 Profile 不可原地修改,同模板发布新版本时原子退役旧版本;Run 必须复制完整 published Profile 与 MinerU 紧凑表格快照,不能只保存当前 Profile ID。
|
||||
- 业务管理员必须通过 MinerU 样本表格的结构化页面维护订单文档 Profile:只选择表格、表头/数据行、行结构、Schema 字段和注册解析器,不得编辑 HTML、bbox、JSON、正则、脚本或结构指纹。结构指纹由后端基于持久化样本计算;草稿更新使用乐观锁,同一目标字段不得跨列重复映射;不可变版本可复制为新草稿或退役。
|
||||
- MinerU 按显式环境开关固定使用 `pipeline`,由独立布局 Job 在 Intake 持久化 Document 后异步调用,不得阻塞 Intake 预解析。布局必须按 Document 独立版本化,保存 parser revision、状态、checksum、大小、质量问题和 Worker lease;只有成功版本可成为当前布局,失败/超限/旧 Worker 结果不得覆盖上一次成功版本。多附件受单 Intake 文档预算限制;Provider 失败、超预算、结构不匹配或多表命中时回退现有 Dify/人工复核,不得伪造确定性字段。
|
||||
- 人工单元格真值当前允许延期,不阻塞布局版本/任务生命周期建设;但在真值评测完成前,不得宣称 95% 准确率、把 MinerU/OpenCV/文本对齐候选自动标记为 `accepted`,也不得据此开启错误自动建单风险。
|
||||
- 原生 PDF 可使用 PDFium 字符坐标与 MinerU HTML 生成 `shipping_document_layout.v1` 候选;只允许唯一连续文本或“OpenCV 多参数有框网格 + 原生文本全量一致”两条保守路径。候选必须保持 `needs_review`,扫描 PDF 不得由本阶段伪造 OCR 结果。
|
||||
- 扫描 PDF 的布局 OCR 必须保留 RapidOCR 原始多边形坐标和置信度,并且只有与严格有框网格及全部非空 cell 文本一致时才能生成 OCR cell 候选。EML HTML table 必须经主动内容/属性白名单清理后按 DOM 行列和跨度生成逻辑布局;原始 HTML 不得进入 Intake 摘要、Dify 或日志。两类结果在人工真值完成前均保持 `needs_review`。
|
||||
- 冻结 Schema 映射必须直接消费 layout.v1 的真实 `cell_id/token_ids`,不得从 HTML 再生成第二套证据 ID。表头后置、重复列、零 Qty、类型与安全校验复用同一规则;跨页只接受显式 continuation。needs_review 映射只能冻结为内部 candidate,禁止进入 Dify、自动接受或跳过 Provider。
|
||||
- 精确 Profile 命中后,模板语义优先于全局 Schema 别名。例如确认模板中的 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是合法映射。只有唯一命中表且每个保留行都具备可信 `part_number + qty` 时,后端才可跳过该附件的 LLM;显式 Qty=0 行删除。Reservation 可由邮件或其他附件补充,最终缺失仍须阻断库存匹配和发货 Excel。
|
||||
- 阶段 2 创建 Run 时同步创建 `shipping_order_extraction` Job;Worker 按 Run 冻结快照调用 `shipping.order_extraction` 能力绑定的内部 Provider,并把 Dify 成功结果先于 HXOPS 订单落库独立提交,重试不得重复调用 Dify。
|
||||
- 应用管理必须显式创建 `exposure_mode=internal` 的 Dify Workflow Provider,再由货代 Agent 绑定 `shipping.order_extraction`。业务代码只识别能力编码和数据库外键,禁止写死 App ID、按名称匹配或从环境变量静默回退;Dify 画布由管理员手工配置。
|
||||
- Run 冻结 Provider App ID、Base URL 与执行参数;二者变更后旧 Run 必须失败并重新发起。API Key 不进入快照,允许在不重建 Run 的情况下安全轮换。
|
||||
@@ -121,6 +129,7 @@
|
||||
- 首次发送无需先创建聊天消息:Run 创建事务会创建本地 ChatSession 并原子绑定尚未归属会话的 Intake,前端使用返回的 `conversation_id` 更新路由。
|
||||
- 订单识别状态卡必须可在刷新/重新进入会话后按 Run 列表恢复;活动态只显示不确定进度,不按固定轮询频率重复写 ChatLog,只有业务状态变化才原位持久化。
|
||||
- 订单抽取进度由 HXOPS 服务端消费专用 Workflow 的 Dify SSE 节点事件并自动按节点类型归并;用户默认查看当前脱敏阶段、真实运行时长和最近活动,可展开时间线。无需手工修改 Dify Workflow;不展示模型思考、节点输入输出、伪百分比或内部运行标识。浏览器继续使用自适应短轮询,不建立订单抽取浏览器长 SSE。
|
||||
- 用户状态卡、Run 查询和历史聊天回放只可显示稳定错误码与通用可操作提示;Worker、Provider 或上游异常正文不得进入用户 API、ChatLog 或前端状态。
|
||||
- 新上线 Run 的完成、待确认和失败状态应在用户离开会话后形成会话级待查看提示;进入对应会话且终态卡片成功加载后才清除。管理员在货代管理域只读诊断 Run、Job Attempt 和脱敏节点时间线;不提供管理端强制操作。
|
||||
- Run 失败或取消时 Intake 恢复为可重试失败态;切换会话后的迟到轮询响应不得更新当前页面或重启旧 Run 计时器。
|
||||
- 管理员必须可查询最近 1-168 小时订单抽取 Run 的状态/阶段/错误码分布、失败率、重试数、积压 Run,以及排队、Provider、HXOPS 落库和总耗时;监控视图不得返回文档正文、Provider 配置、原始结果或错误正文。
|
||||
@@ -172,7 +181,7 @@
|
||||
- 库存主匹配键固定为 `(part_number, reservation_id)`;库存 `Supplier Sku` 映射为 `part_number`,`AWS Sku` 仅映射为可选 `aws_part_number`,不得作为默认主匹配料号。
|
||||
- 本次为无生产数据的破坏性字段升级,不保留旧字段兼容层:规范订单行使用 `shipping-task-line-v2`,内容指纹使用 `shipping-content-v4`;后端、Dify 画布、静态 OpenAPI 与前端必须同批切换。
|
||||
- Reservation ID 不绑定单一邮件模板:允许 `Reservation ID / COM ID / Reservation Order / PR Number / External reservation ID` 等业务来源;禁止把 `Allocation ID / Parent allocation ID / Commodity group ID` 当作 Reservation ID。
|
||||
- 32 位十六进制内部主键和 UUID 不得进入库存匹配;数字型及 `AWS-311 / ORD-3002 / R-1` 等字母型业务编号按通用契约兼容,后续可按客户或来源 profile 收紧。
|
||||
- Reservation ID 统一为 5 位或 10 位纯数字;字母型编号、其他长度数字、32 位十六进制内部主键和 UUID 均不得进入订单关联或库存匹配。
|
||||
- 自动纠错必须具备表头列关系和唯一 SKU/APN/MPN 关联证据;拍平文本或多义匹配不得猜测,必须进入人工复核。
|
||||
- 后端必须保留原始候选、修正值、原因与证据;任何 blocking 问题不得被 LLM 高置信度或人工“确认”动作绕过。
|
||||
- 订单持久化:Task 通过 `current_order_extraction_id` 锁定 `ShippingOrderExtraction/Line/Decision/FieldValue` 唯一真相;不保留固定订单表、JSON 快照或兼容回滚。Candidate→既有 Task 仅允许空 FieldValue 安全补齐,双方非空且不同时落字段冲突并阻断库存/匹配/导出;人工改单须带 `expected_order_data_version`。
|
||||
@@ -545,3 +554,11 @@
|
||||
- 聚合/非聚合由 `agents.is_aggregate` 显式配置,切回非聚合时清空成员关系。
|
||||
- 目录 Agent 本身仍配置一套聚合 Dify Chatflow;HXOPS 在发起聊天时向 Dify inputs 注入成员 Agent 元数据。
|
||||
- 本期不在 HXOPS 后端并行调用多个子 Agent,不合并多个 Dify 回答;多路召回与答案融合由聚合 Chatflow 承担。
|
||||
## 2026-07-22 订单抽取唯一 Manifest 与自动建单策略
|
||||
|
||||
- 订单抽取只保留唯一、可冻结的 `execution_manifest`,不提供输入格式切换或回退。
|
||||
- Manifest 仅向模型提供压缩后的结构化字段候选,不传递版面坐标、HTML、token 或内部映射代码;确定性 accepted 字段不可被模型覆盖。
|
||||
- 人工真值暂缓期间,版面候选保持 `needs_review`,质量验收与 95% 准确率目标延期,不得自动 accepted、自动建单或对外宣称达标。
|
||||
- L6 要求所有 accepted Observation 具有稳定证据引用;无 cell 的纯文本表格只能形成复核原因,不能作为已验证后端表格证据。跨文档关联必须使用同 Document 强身份,禁止以 Qty 等常见值串接订单行。
|
||||
- 自动建单配置位于“货代配置 → 订单字段模板”:管理员只维护一个自动建单总开关;每个字段独立标记为建单关键字段并设置自身最低置信度。每个 Run 冻结开关与字段快照;阈值不能绕过必填、证据、冲突、重复和 Reservation 等硬门禁。
|
||||
- 终态且未消费的订单抽取 Run 支持“按当前规则重新识别”:创建新的可审计 Run,重新冻结当前 Schema、执行绑定、文档 Profile 与 ready 布局;旧候选在新版执行期间不可建单,新版失败后恢复旧版。失败 Run 的基础设施重试仍复用原冻结 Run,不得与重新识别混用。
|
||||
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user