fix(shipping-notice): 版面配额延后排程并修复预算续抽与表头对齐

This commit is contained in:
hugo committed 2026-09-10 22:19:41 +08:00
1 parent 6052c46d88
commit 6e1159a08b
12 files changed
+744 -163

No files matched your search

@@ -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],