feat(shipping-notice): 添加 MinerU 订单附件表格结构化功能,更新环境配置和数据模型以支持新布局解析和文档模板管理

This commit is contained in:
hugo committed 2026-07-22 18:52:43 +08:00
1 parent c4095b08da
commit c35223d49d
148 files changed
+15709 -1353

No files matched your search

+2
View File
@@ -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 会话过滤。"""
+31
View File
@@ -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 可提取正文
+1 -1
View File
@@ -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,
+6
View File
@@ -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,
+5 -1
View File
@@ -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',
}),
}
+10
View File
@@ -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',
+4 -1
View File
@@ -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)
+17
View File
@@ -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)
+31 -1
View File
@@ -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,
)
+5 -1
View File
@@ -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: