feat(shipping-notice): 添加 MinerU 订单附件表格结构化功能,更新环境配置和数据模型以支持新布局解析和文档模板管理
This commit is contained in:
1 parent
c4095b08da
commit
c35223d49d
148 files changed
+15709
-1353
No files matched your search
@@ -5,4 +5,4 @@ backend/app/jobs/handlers/__init__.py
|
||||
逻辑:Wave 2 起在 worker 启动前 import 本包。
|
||||
"""
|
||||
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, shipping_order_extraction, wecom_directory_sync # noqa: F401
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_document_layout, shipping_notice_parse, shipping_notice_run, shipping_order_extraction, wecom_directory_sync # noqa: F401
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_document_layout.py
|
||||
|
||||
用途:独立执行单份 ShippingNoticeDocument 的 MinerU 布局解析任务。
|
||||
依赖:Layout lifecycle/runtime、FileAsset、通用 Job queue。
|
||||
逻辑:按 job attempt 领取版本 lease,读取对象存储调用 MinerU;收口时旧 lease 无权覆盖新版本。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.extensions import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import FileAsset, Job, ShippingDocumentLayoutVersion
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
claim_layout_version,
|
||||
complete_layout_version,
|
||||
sync_layout_after_job_failure,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.runtime import build_mineru_table_snapshot
|
||||
|
||||
|
||||
LAYOUT_JOB_ERROR = 'shipping_document_layout_provider_failed'
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_DOCUMENT_LAYOUT)
|
||||
def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行单文档布局任务;Job 和版本均使用相同 attempt 代次条件收口。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文,用于记录仅运维可见的异常堆栈。
|
||||
payload: 通用队列载荷,只读取 job_id;布局版本 ID 从冻结 Job 载荷读取。
|
||||
|
||||
Returns:
|
||||
None。成功时同时完成布局版本与 Job;失败时按通用重试策略重新排队。
|
||||
"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
return
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
version_id = int((job.payload_json or {}).get('layout_version_id') or 0)
|
||||
version = db.session.get(ShippingDocumentLayoutVersion, version_id) if version_id else None
|
||||
if version is None:
|
||||
fail_job(job.id, error='layout version not found', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
if version.status in {'ready', 'needs_review', 'failed', 'unsupported'}:
|
||||
finish_job(job.id, result={'status': version.status, 'skipped': True}, owned_attempt=owned_attempt)
|
||||
return
|
||||
claimed = claim_layout_version(version.id, job_id=job.id, owned_attempt=owned_attempt)
|
||||
if claimed is None:
|
||||
finish_job(job.id, result={'status': 'stale', 'skipped': True}, owned_attempt=owned_attempt)
|
||||
return
|
||||
version, lease = claimed
|
||||
try:
|
||||
document = version.document
|
||||
asset = db.session.get(FileAsset, int(document.asset_id or 0))
|
||||
if asset is None:
|
||||
raise ValueError('layout document asset is unavailable')
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename=str(document.filename or asset.original_filename or 'document.pdf'),
|
||||
content=read_asset_bytes(asset),
|
||||
document_id=document.id,
|
||||
content_hash=document.content_hash,
|
||||
)
|
||||
if snapshot is None:
|
||||
snapshot = {
|
||||
'snapshot_version': version.contract_version,
|
||||
'provider': version.parser_name, 'backend': version.backend,
|
||||
'status': 'unsupported', 'tables': [],
|
||||
'issues': ['shipping_document_layout_input_unsupported'],
|
||||
}
|
||||
if complete_layout_version(version.id, lease_token=lease, snapshot=snapshot):
|
||||
finish_job(
|
||||
job.id, result={'status': str(snapshot.get('status') or 'failed')},
|
||||
message='文档版面解析完成', owned_attempt=owned_attempt,
|
||||
)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if ctx.logger is not None:
|
||||
ctx.logger.exception(
|
||||
'shipping_document_layout_failed job_id=%s version_id=%s', job.id, version.id,
|
||||
)
|
||||
fail_job(job.id, error=LAYOUT_JOB_ERROR, retryable=True, owned_attempt=owned_attempt)
|
||||
sync_layout_after_job_failure(job.id)
|
||||
raise
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
用途:消费订单抽取领域 Run,调用显式绑定的 Dify Workflow 并持久化订单结果。
|
||||
依赖:Job queue、AgentRuntimeBinding、order_extraction_workflow、Run 状态机。
|
||||
逻辑:Job 只承载执行尝试;Run 是业务真相。结果先完整落库并进入 result_persisted,再收口 completed/needs_review。
|
||||
依赖:Job queue、AgentRuntimeBinding、order_extraction_workflow、Run 状态机、provider_guard。
|
||||
逻辑:Job 只承载执行尝试;Run 是业务真相。线程快照须含 provider_config_json/schema_version_id;
|
||||
仅 Dify 传输类失败累计熔断。结果先完整落库并进入 result_persisted,再收口 completed/needs_review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -50,12 +51,22 @@ from app.services.shipping_notice.order_extraction_provider_guard import (
|
||||
)
|
||||
|
||||
|
||||
# 仅 Dify 传输类失败累计熔断;本地编程错误与 CIRCUIT_OPEN 自身不得拉长冷却窗。
|
||||
_PROVIDER_CIRCUIT_FAILURE_CODES = frozenset({
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED',
|
||||
})
|
||||
|
||||
|
||||
def _execute_dify_unit_with_retry(
|
||||
*, app, run_snapshot: dict, unit_snapshot: dict, provider_snapshot: dict, timeout_seconds: int,
|
||||
max_attempts: int, backoff_ms: int, job_id: int, job_attempt: int,
|
||||
provider_max_concurrency: int, circuit_failure_threshold: int, circuit_cooldown_seconds: int,
|
||||
) -> dict:
|
||||
"""在线程独立应用上下文中用纯快照执行网络调用,并做有限指数退避重试。"""
|
||||
"""在线程独立应用上下文中用纯快照执行网络调用,并做有限指数退避重试。
|
||||
|
||||
核心逻辑:熔断仅统计 Dify 超时/请求失败;本地异常与 CIRCUIT_OPEN 不拉长冷却。
|
||||
"""
|
||||
last_error: Exception | None = None
|
||||
started = time.perf_counter()
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
@@ -84,7 +95,8 @@ def _execute_dify_unit_with_retry(
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
|
||||
if retryable:
|
||||
# [STEP] 仅传输类 Provider 失败累计熔断,避免本地异常或开路自身延长冷却。
|
||||
if isinstance(exc, AppError) and getattr(exc, 'code', None) in _PROVIDER_CIRCUIT_FAILURE_CODES:
|
||||
record_provider_failure(
|
||||
int(provider_snapshot['id']), threshold=circuit_failure_threshold,
|
||||
cooldown_seconds=circuit_cooldown_seconds,
|
||||
@@ -180,7 +192,16 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
run.attempt_count = owned_attempt
|
||||
db.session.commit()
|
||||
|
||||
timeout_seconds = int((run.provider_config_json or {}).get('timeout_seconds') or 900)
|
||||
run_config = run.provider_config_json if isinstance(run.provider_config_json, dict) else {}
|
||||
if bool(run_config.get('auto_create_enabled')):
|
||||
from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch
|
||||
|
||||
require_approved_quality_batch(
|
||||
batch_id=run.quality_batch_id,
|
||||
owner_agent_id=int(run.owner_agent_id),
|
||||
schema_version_id=int(run.schema_version_id),
|
||||
)
|
||||
timeout_seconds = int(run_config.get('timeout_seconds') or 900)
|
||||
saved_provider_result = run.provider_result_json if isinstance(run.provider_result_json, dict) else {}
|
||||
saved_orders = saved_provider_result.get('orders')
|
||||
if isinstance(saved_orders, list) and all(isinstance(item, dict) for item in saved_orders):
|
||||
@@ -243,8 +264,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
with ThreadPoolExecutor(max_workers=min(concurrency, len(dify_units) or 1)) as pool:
|
||||
run_snapshot = {
|
||||
'id': run.id, 'run_no': run.run_no, 'user_id': run.user_id,
|
||||
'schema_version_id': run.schema_version_id,
|
||||
'input_snapshot_hash': run.input_snapshot_hash,
|
||||
'input_snapshot_json': run.input_snapshot_json,
|
||||
'provider_config_json': run.provider_config_json,
|
||||
}
|
||||
provider_snapshot = {
|
||||
'id': provider.id, 'api_base_url': provider.api_base_url,
|
||||
|
||||
@@ -983,6 +983,12 @@ def process_next_job(
|
||||
)
|
||||
|
||||
on_recovered = sync_order_extraction_run_after_job_recovery
|
||||
elif normalized_type == JobType.SHIPPING_DOCUMENT_LAYOUT.value:
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
sync_layout_after_job_recovery,
|
||||
)
|
||||
|
||||
on_recovered = sync_layout_after_job_recovery
|
||||
recover_stale_jobs(
|
||||
domain=domain,
|
||||
timeout_seconds=timeout_seconds,
|
||||
|
||||
@@ -17,6 +17,7 @@ class JobType(StrEnum):
|
||||
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
|
||||
SHIPPING_NOTICE_PARSE = 'shipping_notice_parse'
|
||||
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
||||
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
|
||||
SCHEDULE_RUN = 'schedule_run'
|
||||
FILE_CHECK_RUN = 'file_check_run'
|
||||
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
|
||||
@@ -50,7 +51,10 @@ _HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
|
||||
# worker --queues 参数 → 可消费的 KbJob.job_type 集合
|
||||
QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
|
||||
'shipping': frozenset({'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction'}),
|
||||
'shipping': frozenset({
|
||||
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
||||
'shipping_document_layout',
|
||||
}),
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user