fix(shipping-notice): 版面配额延后排程并修复预算续抽与表头对齐
This commit is contained in:
1 parent
6052c46d88
commit
6e1159a08b
12 files changed
+744
-163
No files matched your search
@@ -7,6 +7,7 @@ backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行;有 ready PDF 即按 Unit 抽取并下游推进,
|
||||
兄弟文件 layout pending 时 Job 以 partial_units_done 回到 waiting_layout;
|
||||
运行时预算耗尽且仍有 pending Unit 时入队续抽,禁止终态 partially_completed;
|
||||
每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记;
|
||||
不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
|
||||
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
|
||||
@@ -41,6 +42,7 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
_enqueue_ready_order_extraction_job,
|
||||
begin_input_freeze,
|
||||
complete_input_freeze,
|
||||
mark_order_extraction_persistence_started,
|
||||
@@ -50,6 +52,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
materialize_order_extraction_run_inputs,
|
||||
ensure_workflow_items_for_run,
|
||||
progress_ready_extraction_unit,
|
||||
revive_layout_prerequisite_failed_units,
|
||||
schedule_order_extraction_layouts,
|
||||
synchronize_order_extraction_expansion_snapshot,
|
||||
transition_order_extraction_run,
|
||||
@@ -774,6 +777,8 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
if code == 'layout_pending'
|
||||
}
|
||||
ready_document_ids = order_extraction_ready_document_ids(run)
|
||||
# 版面已就绪时复活此前因 layout 前置失败的 Unit,避免永久 failed。
|
||||
revive_layout_prerequisite_failed_units(run)
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing')
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
@@ -1170,6 +1175,50 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
# [STEP] 运行时预算耗尽且仍有 pending Unit:保留已抽成果,入队续抽,禁止终态 partially_completed。
|
||||
units = ShippingOrderProcessingUnit.query.filter_by(plan_id=plan.id).order_by(
|
||||
ShippingOrderProcessingUnit.position.asc(),
|
||||
).all()
|
||||
pending_left = any(str(unit.status or '') == 'pending' for unit in units)
|
||||
if runtime_budget_stopped and pending_left:
|
||||
record_run_progress(
|
||||
run=run,
|
||||
event_code='budget_stopped',
|
||||
reason_code='budget_runtime_limit',
|
||||
summary={
|
||||
**_selection_progress_summary(run),
|
||||
'max_runtime_seconds': max_runtime_seconds,
|
||||
'pending_unit_count': sum(
|
||||
1 for unit in units if str(unit.status or '') == 'pending'
|
||||
),
|
||||
'merged_unit_count': len(pending_merge_unit_ids),
|
||||
},
|
||||
job_id=job.id,
|
||||
commit=False,
|
||||
)
|
||||
continue_job_id = _enqueue_ready_order_extraction_job(
|
||||
run, message='运行时预算已用尽,继续识别剩余附件',
|
||||
)
|
||||
run.current_job_id = continue_job_id
|
||||
run.phase = 'waiting_layout'
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'budget_stopped': True,
|
||||
'waiting_continue': True,
|
||||
'handoff_status': 'runtime_budget_continue',
|
||||
'merged_unit_count': len(pending_merge_unit_ids),
|
||||
'pending_unit_count': sum(
|
||||
1 for unit in units if str(unit.status or '') == 'pending'
|
||||
),
|
||||
'continue_job_id': int(continue_job_id),
|
||||
},
|
||||
message='运行时预算已用尽,已排队继续识别剩余附件',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
orders = persisted_orders + merged_orders
|
||||
execution = {
|
||||
'mode': 'deterministic',
|
||||
|
||||
@@ -866,10 +866,29 @@ def schedule_layout_version(
|
||||
return version
|
||||
|
||||
|
||||
def _document_has_active_or_current_layout(document: ShippingOrderDocument) -> bool:
|
||||
"""
|
||||
判断文档是否已有进行中或可用的版面,从而本轮不必再占配额新建。
|
||||
|
||||
核心逻辑:queued/running 算进行中;current 指向 ready/needs_review 算可用。
|
||||
历史 unsupported(含预算跳过审计)不算可用,允许后续波次重新排程。
|
||||
"""
|
||||
for item in list(getattr(document, 'layout_versions', None) or []):
|
||||
if str(item.status or '') in {'queued', 'running'}:
|
||||
return True
|
||||
current = getattr(document, 'current_layout_version', None)
|
||||
return current is not None and str(current.status or '') in CURRENT_LAYOUT_STATUSES
|
||||
|
||||
|
||||
def schedule_document_layouts(
|
||||
documents: list[ShippingOrderDocument], *, created_by_id: int | None = None,
|
||||
) -> list[ShippingDocumentLayoutVersion]:
|
||||
"""在 Document 持久化事务内为支持附件建立独立布局版本,超量文档保留 skipped 审计。"""
|
||||
"""
|
||||
在 Document 持久化事务内为支持附件建立独立布局版本。
|
||||
|
||||
核心逻辑:只对尚无进行中/可用版面的 PDF 占配额;本轮最多新建 max_documents 个 Job。
|
||||
超出配额的文档本轮不排程、不写 unsupported 伪终态,留给后续 schedule 调用继续排。
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS
|
||||
@@ -882,30 +901,9 @@ def schedule_document_layouts(
|
||||
if item.asset_id is not None
|
||||
and Path(str(item.filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS
|
||||
]
|
||||
needing = [item for item in eligible if not _document_has_active_or_current_layout(item)]
|
||||
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
|
||||
for document in needing[:max_documents]:
|
||||
version = schedule_layout_version(document, created_by_id=created_by_id)
|
||||
if version is not None:
|
||||
result.append(version)
|
||||
|
||||
@@ -7,7 +7,8 @@ services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
|
||||
主表优先按签名表头原子亲和度选择(避免 MinerU 抬头 KV 小表抢主表),并列再比表区重叠;
|
||||
无 hard_valid 时仅当全部候选均坐标结构不可用才抬升 evidence_insufficient;
|
||||
身份表头只读「签名 header_bbox 按主表顶边 deltaY 对齐」后的窗口,禁止表顶宽带兜底;
|
||||
身份表头按各 table_patterns.header_bbox 对齐到对应表区后只读窗口(正确页码),
|
||||
禁止表顶宽带兜底;多 pattern 观测结果并集与签名身份 token 口径一致;
|
||||
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
|
||||
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
|
||||
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
|
||||
@@ -1352,7 +1353,7 @@ def _observe_layout_features(
|
||||
)
|
||||
|
||||
header_tokens, column_centers, column_width_ratios = _observe_primary_table_header(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
primary_bbox=primary_bbox, signature=signature,
|
||||
)
|
||||
static_text_centers = _observe_static_text_centers(
|
||||
@@ -1722,53 +1723,71 @@ _HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
|
||||
def _signature_table_bbox_median(signature: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取签名首个可用 table_patterns.bbox.median(归一化四点)。"""
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
|
||||
if not isinstance(bbox, dict):
|
||||
continue
|
||||
median = bbox.get('median')
|
||||
if isinstance(median, list) and len(median) == 4:
|
||||
try:
|
||||
return [float(item) for item in median]
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
median = _pattern_table_bbox_median(pattern if isinstance(pattern, dict) else None)
|
||||
if median is not None:
|
||||
return median
|
||||
return None
|
||||
|
||||
|
||||
def _align_signature_header_bbox_to_primary(
|
||||
def _pattern_header_bbox(pattern: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取单个 table_pattern 的 header_bbox。"""
|
||||
if not isinstance(pattern, dict):
|
||||
return None
|
||||
value = pattern.get('header_bbox')
|
||||
if isinstance(value, list) and len(value) == 4:
|
||||
try:
|
||||
return [float(item) for item in value]
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _pattern_table_bbox_median(pattern: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取单个 table_pattern.bbox.median。"""
|
||||
if not isinstance(pattern, dict):
|
||||
return None
|
||||
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
|
||||
if not isinstance(bbox, dict):
|
||||
return None
|
||||
median = bbox.get('median')
|
||||
if isinstance(median, list) and len(median) == 4:
|
||||
try:
|
||||
return [float(item) for item in median]
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _align_header_bbox_to_table(
|
||||
*,
|
||||
signature: dict[str, Any] | None,
|
||||
primary_bbox: list[float],
|
||||
header_bbox: list[float],
|
||||
signature_table_y0: float | None,
|
||||
table_bbox: list[float],
|
||||
) -> list[float] | None:
|
||||
"""
|
||||
将签名冻结的表头框按当前主表顶边做整体 deltaY 对齐。
|
||||
将签名表头框按目标表顶边做整体 deltaY 对齐并夹在表内。
|
||||
|
||||
核心逻辑:x/高度保持签名 header_bbox;只用 primary_bbox.y0 - signature_table.y0
|
||||
平移;再把 y 夹在主表竖向范围内,避免落到明细数据行。无 header_bbox 时返回 None。
|
||||
核心逻辑:x/高度保持 header_bbox;deltaY = table.y0 - signature_table.y0。
|
||||
"""
|
||||
if not isinstance(primary_bbox, list) or len(primary_bbox) != 4:
|
||||
if not isinstance(table_bbox, list) or len(table_bbox) != 4:
|
||||
return None
|
||||
header_bbox = _signature_header_bbox(signature)
|
||||
if header_bbox is None:
|
||||
if not isinstance(header_bbox, list) or len(header_bbox) != 4:
|
||||
return None
|
||||
table_median = _signature_table_bbox_median(signature)
|
||||
try:
|
||||
hx0, hy0, hx1, hy1 = (float(header_bbox[i]) for i in range(4))
|
||||
py0, py1 = float(primary_bbox[1]), float(primary_bbox[3])
|
||||
py0, py1 = float(table_bbox[1]), float(table_bbox[3])
|
||||
except (TypeError, ValueError, IndexError):
|
||||
return None
|
||||
if hy1 <= hy0 or py1 <= py0:
|
||||
return None
|
||||
delta_y = 0.0
|
||||
if table_median is not None:
|
||||
if signature_table_y0 is not None:
|
||||
try:
|
||||
delta_y = py0 - float(table_median[1])
|
||||
except (TypeError, ValueError, IndexError):
|
||||
delta_y = py0 - float(signature_table_y0)
|
||||
except (TypeError, ValueError):
|
||||
delta_y = 0.0
|
||||
aligned_y0 = hy0 + delta_y
|
||||
aligned_y1 = hy1 + delta_y
|
||||
# [STEP] 夹在主表内;保持最小可读高度。
|
||||
height = max(0.02, aligned_y1 - aligned_y0)
|
||||
clipped_y0 = min(max(aligned_y0, py0), max(py0, py1 - height))
|
||||
clipped_y1 = min(clipped_y0 + height, py1)
|
||||
@@ -1777,51 +1796,106 @@ def _align_signature_header_bbox_to_primary(
|
||||
return [hx0, clipped_y0, hx1, clipped_y1]
|
||||
|
||||
|
||||
def _observe_primary_table_header(
|
||||
def _align_signature_header_bbox_to_primary(
|
||||
*,
|
||||
glyph_tables: dict[str, Any],
|
||||
page_glyphs: dict[str, Any],
|
||||
pages: dict[str, Any],
|
||||
primary_bbox: list[float] | None,
|
||||
signature: dict[str, Any] | None,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""
|
||||
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
|
||||
|
||||
核心逻辑:有签名 header_bbox 时按主表顶边 deltaY 对齐后只读该窗口;无签名表头框
|
||||
时才用主表顶 18% 保守带(与签名生成兜底一致)。禁止固定带失准后改走表顶多行
|
||||
宽带搜索,避免印刷括号注记污染身份原子。
|
||||
"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return [], [], []
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
|
||||
if not isinstance(glyphs, list):
|
||||
glyphs = []
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
glyphs.extend(table_glyphs)
|
||||
page = pages.get('1') or pages.get(1)
|
||||
if not isinstance(glyphs, list) or not glyphs or not isinstance(page, dict):
|
||||
return [], [], []
|
||||
aligned = _align_signature_header_bbox_to_primary(
|
||||
signature=signature, primary_bbox=primary_bbox,
|
||||
primary_bbox: list[float],
|
||||
) -> list[float] | None:
|
||||
"""兼容入口:用签名首个 header_bbox / table median 对齐到主表。"""
|
||||
header_bbox = _signature_header_bbox(signature)
|
||||
if header_bbox is None:
|
||||
return None
|
||||
table_median = _signature_table_bbox_median(signature)
|
||||
signature_table_y0 = float(table_median[1]) if table_median is not None else None
|
||||
return _align_header_bbox_to_table(
|
||||
header_bbox=header_bbox,
|
||||
signature_table_y0=signature_table_y0,
|
||||
table_bbox=primary_bbox,
|
||||
)
|
||||
if aligned is not None:
|
||||
region = {
|
||||
'x0': float(aligned[0]), 'y0': float(aligned[1]),
|
||||
'x1': float(aligned[2]), 'y1': float(aligned[3]),
|
||||
}
|
||||
else:
|
||||
region = {
|
||||
'x0': float(primary_bbox[0]),
|
||||
'y0': float(primary_bbox[1]),
|
||||
'x1': float(primary_bbox[2]),
|
||||
'y1': float(primary_bbox[1]) + max(
|
||||
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _normalized_layout_tables(
|
||||
*,
|
||||
tables: list[dict[str, Any]],
|
||||
pages: dict[str, Any],
|
||||
) -> list[tuple[list[float], Any, dict[str, Any]]]:
|
||||
"""将 layout.tables 规范为 (归一化 bbox, page_no, page)。"""
|
||||
normalized: list[tuple[list[float], Any, dict[str, Any]]] = []
|
||||
for table in tables:
|
||||
page_no = table.get('page_no') or 1
|
||||
page = pages.get(str(page_no)) or pages.get(page_no)
|
||||
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
|
||||
if not isinstance(page, dict) or not isinstance(bbox, dict):
|
||||
continue
|
||||
try:
|
||||
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if raw[2] <= raw[0] or raw[3] <= raw[1] or width <= 0 or height <= 0:
|
||||
continue
|
||||
norm = raw if max(raw) <= 1 else [
|
||||
raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height,
|
||||
]
|
||||
normalized.append((norm, page_no, page))
|
||||
return normalized
|
||||
|
||||
|
||||
def _best_table_for_pattern_bbox(
|
||||
*,
|
||||
pattern_bbox: list[float] | None,
|
||||
normalized_tables: list[tuple[list[float], Any, dict[str, Any]]],
|
||||
fallback: list[float] | None,
|
||||
) -> tuple[list[float], Any, dict[str, Any]] | None:
|
||||
"""按与 pattern.bbox.median 的 IoU 选运行时表;无重叠时回退 fallback 及其最近页。"""
|
||||
if pattern_bbox is not None and normalized_tables:
|
||||
best: tuple[float, list[float], Any, dict[str, Any]] | None = None
|
||||
for bbox, page_no, page in normalized_tables:
|
||||
overlap = _bbox_overlap(pattern_bbox, bbox)
|
||||
if best is None or overlap > best[0]:
|
||||
best = (overlap, bbox, page_no, page)
|
||||
if best is not None and best[0] > 0:
|
||||
return best[1], best[2], best[3]
|
||||
if fallback is None or len(fallback) != 4 or not normalized_tables:
|
||||
return None
|
||||
nearest = max(
|
||||
normalized_tables,
|
||||
key=lambda item: _bbox_overlap(fallback, item[0]),
|
||||
)
|
||||
return fallback, nearest[1], nearest[2]
|
||||
|
||||
|
||||
def _glyphs_for_page(
|
||||
*,
|
||||
page_no: Any,
|
||||
page_glyphs: dict[str, Any],
|
||||
glyph_tables: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按页取 glyphs;缺页时回退全部 table glyphs。"""
|
||||
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no)
|
||||
if isinstance(glyphs, list) and glyphs:
|
||||
return glyphs
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
|
||||
if isinstance(glyphs, list) and glyphs:
|
||||
return glyphs
|
||||
merged: list[dict[str, Any]] = []
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
merged.extend(table_glyphs)
|
||||
return merged
|
||||
|
||||
|
||||
def _observe_header_region(
|
||||
*,
|
||||
region: dict[str, float],
|
||||
page: dict[str, Any],
|
||||
glyphs: list[dict[str, Any]],
|
||||
table_bbox: list[float],
|
||||
merge_wrap: bool,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""在指定页的相对区域内读取表头 token/列中心/宽度比。"""
|
||||
width = float(page.get('width') or 0)
|
||||
if width <= 0:
|
||||
if width <= 0 or not glyphs:
|
||||
return [], [], []
|
||||
header_glyphs = _glyphs_in_relative_region(glyphs, page=page, region=region)
|
||||
spans = [
|
||||
@@ -1830,11 +1904,11 @@ def _observe_primary_table_header(
|
||||
][:32]
|
||||
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
|
||||
band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
|
||||
table_span = max(float(primary_bbox[2]) - float(primary_bbox[0]), 0.0001)
|
||||
table_span = max(float(table_bbox[2]) - float(table_bbox[0]), 0.0001)
|
||||
band_widths = [
|
||||
round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans
|
||||
]
|
||||
if _signature_single_logical_header(signature):
|
||||
if merge_wrap:
|
||||
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
|
||||
band_tokens, band_centers, band_widths,
|
||||
)
|
||||
@@ -1846,6 +1920,97 @@ def _observe_primary_table_header(
|
||||
return band_tokens, band_centers, band_widths
|
||||
|
||||
|
||||
def _observe_primary_table_header(
|
||||
*,
|
||||
tables: list[dict[str, Any]],
|
||||
glyph_tables: dict[str, Any],
|
||||
page_glyphs: dict[str, Any],
|
||||
pages: dict[str, Any],
|
||||
primary_bbox: list[float] | None,
|
||||
signature: dict[str, Any] | None,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""
|
||||
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
|
||||
|
||||
核心逻辑:对每个带 header_bbox 的 table_pattern,选 IoU 最大的运行时表,按该表
|
||||
所在页做 deltaY 对齐后只读窗口;多 pattern 的 token 并集对应签名身份并集。无
|
||||
header_bbox 时才用主表顶 18% 保守带。禁止表顶多行宽带搜索。
|
||||
"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return [], [], []
|
||||
|
||||
patterns = [
|
||||
item for item in (signature or {}).get('table_patterns') or []
|
||||
if isinstance(item, dict) and _pattern_header_bbox(item) is not None
|
||||
]
|
||||
normalized_tables = _normalized_layout_tables(tables=tables, pages=pages)
|
||||
observed_tokens: list[str] = []
|
||||
observed_centers: list[float] = []
|
||||
observed_widths: list[float] = []
|
||||
|
||||
if patterns:
|
||||
for pattern in patterns:
|
||||
header_bbox = _pattern_header_bbox(pattern)
|
||||
if header_bbox is None:
|
||||
continue
|
||||
pattern_median = _pattern_table_bbox_median(pattern)
|
||||
matched = _best_table_for_pattern_bbox(
|
||||
pattern_bbox=pattern_median,
|
||||
normalized_tables=normalized_tables,
|
||||
fallback=primary_bbox,
|
||||
)
|
||||
if matched is None:
|
||||
continue
|
||||
table_bbox, page_no, page = matched
|
||||
aligned = _align_header_bbox_to_table(
|
||||
header_bbox=header_bbox,
|
||||
signature_table_y0=(
|
||||
float(pattern_median[1]) if pattern_median is not None else None
|
||||
),
|
||||
table_bbox=table_bbox,
|
||||
)
|
||||
if aligned is None:
|
||||
continue
|
||||
region = {
|
||||
'x0': float(aligned[0]), 'y0': float(aligned[1]),
|
||||
'x1': float(aligned[2]), 'y1': float(aligned[3]),
|
||||
}
|
||||
glyphs = _glyphs_for_page(
|
||||
page_no=page_no, page_glyphs=page_glyphs, glyph_tables=glyph_tables,
|
||||
)
|
||||
tokens, centers, widths = _observe_header_region(
|
||||
region=region, page=page, glyphs=glyphs, table_bbox=table_bbox,
|
||||
merge_wrap=int(pattern.get('header_row_count') or 1) <= 1,
|
||||
)
|
||||
observed_tokens.extend(tokens)
|
||||
observed_centers.extend(centers)
|
||||
observed_widths.extend(widths)
|
||||
if observed_tokens:
|
||||
return observed_tokens, observed_centers, observed_widths
|
||||
|
||||
# 无签名表头框或 pattern 均未读到:主表顶 18% 保守带(与签名生成兜底一致)。
|
||||
page_no, page = _page_for_primary_table_bbox(
|
||||
primary_bbox, tables=tables, pages=pages,
|
||||
)
|
||||
if not isinstance(page, dict):
|
||||
return [], [], []
|
||||
glyphs = _glyphs_for_page(
|
||||
page_no=page_no, page_glyphs=page_glyphs, glyph_tables=glyph_tables,
|
||||
)
|
||||
region = {
|
||||
'x0': float(primary_bbox[0]),
|
||||
'y0': float(primary_bbox[1]),
|
||||
'x1': float(primary_bbox[2]),
|
||||
'y1': float(primary_bbox[1]) + max(
|
||||
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
|
||||
),
|
||||
}
|
||||
return _observe_header_region(
|
||||
region=region, page=page, glyphs=glyphs, table_bbox=primary_bbox,
|
||||
merge_wrap=_signature_single_logical_header(signature),
|
||||
)
|
||||
|
||||
|
||||
def _merge_following_wrap_candidate(
|
||||
*,
|
||||
header: dict[str, Any],
|
||||
|
||||
@@ -1165,12 +1165,28 @@ def order_extraction_layout_prerequisite_issues(run: ShippingOrderProcessingRun)
|
||||
)
|
||||
version = active_versions[0] if active_versions else document.current_layout_version
|
||||
if version is None:
|
||||
issues[int(document.id)] = 'layout_missing'
|
||||
# 有原件但尚未排到版面(配额延后或历史 budget unsupported 未绑 current):
|
||||
# 记 pending 等待后续 schedule,禁止当成 layout_missing 永久 failed。
|
||||
if document.asset_id:
|
||||
issues[int(document.id)] = 'layout_pending'
|
||||
else:
|
||||
issues[int(document.id)] = 'layout_missing'
|
||||
continue
|
||||
if str(version.status or '') in {'queued', 'running'}:
|
||||
issues[int(document.id)] = 'layout_pending'
|
||||
continue
|
||||
if str(version.status or '') != 'ready':
|
||||
issues_list = [
|
||||
str(item) for item in (version.issues_json or []) if str(item or '').strip()
|
||||
]
|
||||
# 历史预算跳过审计:视为延后排程,不进硬失败。
|
||||
if (
|
||||
str(version.status or '') == 'unsupported'
|
||||
and 'mineru_intake_document_budget_exceeded' in issues_list
|
||||
and bool(document.asset_id)
|
||||
):
|
||||
issues[int(document.id)] = 'layout_pending'
|
||||
continue
|
||||
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
|
||||
# PDF 坐标证据可从原始附件按需恢复;压缩导致的 failed/不完整版本不应
|
||||
# 在正式模板匹配前提前阻断,workflow 会在内存中恢复并继续做确定性匹配。
|
||||
@@ -1204,11 +1220,48 @@ def order_extraction_layouts_pending(run: ShippingOrderProcessingRun) -> bool:
|
||||
_EXTRACT_DONE_UNIT_STATUSES = frozenset({
|
||||
'candidate_ready', 'review_required', 'failed', 'cancelled',
|
||||
})
|
||||
_LAYOUT_PREREQUISITE_FAILED_CODE = 'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED'
|
||||
# layout 与 extraction 共 shipping 队列且默认 priority=0;resume 抬高后才能插队,
|
||||
# 否则「单文件版式完成」的 extraction 仍排在剩余 layout FIFO 之后。
|
||||
_ORDER_EXTRACTION_READY_PRIORITY = 10
|
||||
|
||||
|
||||
def revive_layout_prerequisite_failed_units(run: ShippingOrderProcessingRun) -> int:
|
||||
"""
|
||||
版面已就绪时,将 layout 前置失败的 Unit 重置为 pending 以便重抽。
|
||||
|
||||
核心逻辑:仅复活 error_code=LAYOUT_PREREQUISITE_FAILED 且 document 现已 ready 的 Unit;
|
||||
同步清掉 Document 上对应的 failed 投影,避免首屏仍显示解析失败。
|
||||
|
||||
Returns:
|
||||
复活的 Unit 数量。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
ready_ids = order_extraction_ready_document_ids(run)
|
||||
if not ready_ids:
|
||||
return 0
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
if plan is None:
|
||||
return 0
|
||||
revived = 0
|
||||
for unit in ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all():
|
||||
if str(unit.status or '') != 'failed':
|
||||
continue
|
||||
if str(unit.error_code or '') != _LAYOUT_PREREQUISITE_FAILED_CODE:
|
||||
continue
|
||||
if int(unit.document_id or 0) not in ready_ids:
|
||||
continue
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
document = db.session.get(ShippingOrderDocument, int(unit.document_id))
|
||||
if document is not None and str(document.order_extraction_status or '') == 'failed':
|
||||
document.order_extraction_status = 'not_started'
|
||||
document.order_extraction_error_code = None
|
||||
document.order_extraction_error_message = None
|
||||
revived += 1
|
||||
return revived
|
||||
|
||||
|
||||
def _enqueue_ready_order_extraction_job(
|
||||
run: ShippingOrderProcessingRun, *, message: str,
|
||||
) -> int:
|
||||
@@ -1265,9 +1318,10 @@ def order_extraction_has_extractable_ready_work(run: ShippingOrderProcessingRun)
|
||||
"""
|
||||
判断是否存在「版式已就绪、Unit 尚未收口」的可抽取工作。
|
||||
|
||||
核心逻辑:有 ready PDF 且(尚无 Plan / Plan 为空 → 需要建计划抽取;或存在对应
|
||||
Unit 未到 candidate_ready/review_required/failed/cancelled)。
|
||||
核心逻辑:先尝试复活 layout 前置失败 Unit;有 ready PDF 且(尚无 Plan / Plan 为空 →
|
||||
需要建计划抽取;或存在对应 Unit 未到 candidate_ready/review_required/failed/cancelled)。
|
||||
"""
|
||||
revive_layout_prerequisite_failed_units(run)
|
||||
ready_ids = order_extraction_ready_document_ids(run)
|
||||
if not ready_ids:
|
||||
return False
|
||||
@@ -1334,13 +1388,11 @@ def schedule_order_extraction_layouts(
|
||||
"""
|
||||
发送后为本 Run 已选附件创建版面任务,并返回是否需要等待其完成。
|
||||
|
||||
核心逻辑:调用 schedule_document_layouts;用返回值与库查询确认每份 PDF 已有布局版本,
|
||||
避免 ORM 关系未刷新导致误报「未创建版面 Job」。
|
||||
核心逻辑:调用 schedule_document_layouts;配额延后的 PDF 本轮可不排程,返回 True 继续等待;
|
||||
已有 queued/running/ready 的不重复占用配额。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
documents = _run_layout_documents(run)
|
||||
scheduled = schedule_document_layouts(documents, created_by_id=created_by_id)
|
||||
# [STEP] 以本轮排程结果与库内版本为准,禁止依赖可能未 refresh 的 layout_versions 关系。
|
||||
@@ -1374,7 +1426,7 @@ def schedule_order_extraction_layouts(
|
||||
for document in documents
|
||||
if document.current_layout_version_id is not None
|
||||
}
|
||||
# 排程函数不能再静默跳过订单 PDF;否则后续路由只能看到空表格并误判业务失败。
|
||||
# 配额延后的 PDF 本轮可不排程;保留 pending,禁止当成排程失败抬 ValidationError。
|
||||
missing = [
|
||||
document_id for document_id in pdf_document_ids
|
||||
if (
|
||||
@@ -1384,11 +1436,7 @@ def schedule_order_extraction_layouts(
|
||||
)
|
||||
]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
'Order PDF layout job was not created',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_SCHEDULING_FAILED',
|
||||
details={'document_ids': missing},
|
||||
)
|
||||
return True
|
||||
return order_extraction_layouts_pending(run)
|
||||
|
||||
|
||||
@@ -1460,6 +1508,44 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED', commit=False,
|
||||
)
|
||||
resumed += 1
|
||||
continue
|
||||
# 无版面 pending、无可抽/可复活工作:收口卡住的 waiting_layout,避免永久 processing。
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
units = (
|
||||
ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all()
|
||||
if plan is not None else []
|
||||
)
|
||||
if not units or any(
|
||||
str(unit.status or '') not in _EXTRACT_DONE_UNIT_STATUSES for unit in units
|
||||
):
|
||||
continue
|
||||
deterministic = sum(1 for unit in units if str(unit.status or '') == 'candidate_ready')
|
||||
failed = sum(1 for unit in units if str(unit.status or '') == 'failed')
|
||||
review = sum(1 for unit in units if str(unit.status or '') == 'review_required')
|
||||
if deterministic == 0 and failed > 0 and review == 0:
|
||||
final_status = 'failed'
|
||||
elif deterministic == 0 and review > 0 and failed == 0:
|
||||
final_status = 'review_required'
|
||||
elif review > 0 or failed > 0 or deterministic < len(units):
|
||||
final_status = 'partially_completed'
|
||||
else:
|
||||
final_status = 'completed'
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase=final_status)
|
||||
transition_order_extraction_run(run, target_status=final_status, phase=final_status)
|
||||
record_run_progress(
|
||||
run=run,
|
||||
event_code='run_completed',
|
||||
summary={
|
||||
'document_id': int(document_id),
|
||||
'handoff_status': 'waiting_layout_closed',
|
||||
'deterministic_unit_count': deterministic,
|
||||
'failed_unit_count': failed,
|
||||
'review_required_unit_count': review,
|
||||
},
|
||||
commit=False,
|
||||
)
|
||||
resumed += 1
|
||||
if resumed:
|
||||
db.session.commit()
|
||||
return resumed
|
||||
|
||||
Reference in new issue
Block a user