feat(shipping-notice): 收敛复核阶段同源投影与 OT 后履约推进

统一 Case/Progress 阶段 label_key、修复 Job 成功未推进 OT 的可重试失败投影与写路径,并落地 OT 后行级匹配/波次履约与版面诊断开关。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-07 13:11:14 +08:00
1 parent 74270adc22
commit fd6a23f870
100 files changed
+12138 -1017

No files matched your search

@@ -53,6 +53,7 @@ from app.services.shipping_notice.document_layout.text_cell_alignment import (
)
from app.services.shipping_notice.document_layout.native_pdf import (
NativePdfPage,
attach_native_pdf_page_images,
build_native_pdf_layout_candidate,
build_native_pdf_text_table_fallbacks,
extract_native_pdf_pages,
@@ -64,6 +65,8 @@ from app.services.shipping_notice.document_layout.ocr_pdf import (
OcrTableEvidence,
build_ocr_table_evidence,
extract_ocr_lines,
extract_table_crop_ocr_lines,
get_page_ocr_lines,
page_bbox_to_normalized,
)
from app.services.shipping_notice.document_layout.schema_mapping import (
@@ -98,6 +101,7 @@ __all__ = [
'NativePdfPage',
'build_native_pdf_layout_candidate',
'build_native_pdf_text_table_fallbacks',
'attach_native_pdf_page_images',
'extract_native_pdf_pages',
'build_html_layout_candidate',
'OcrCellEvidence',
@@ -105,6 +109,8 @@ __all__ = [
'OcrTableEvidence',
'build_ocr_table_evidence',
'extract_ocr_lines',
'extract_table_crop_ocr_lines',
'get_page_ocr_lines',
'page_bbox_to_normalized',
'layout_table_to_grid',
'map_layout_document_to_schema',
@@ -0,0 +1,295 @@
"""
backend/app/services/shipping_notice/document_layout/layout_diagnostics.py
用途:Layout Job 脱敏阶段计时与计数契约(PR-0~PR-3);仅写入 Job result / worker 日志。
依赖:time.perf_counter;可选读取 ocr_pdf._ocr_engine 的 lru_cache 状态。
逻辑:由 shipping_document_layout handler 初始化;runtime / native_pdf / ocr_pdf / opencv_table 累加;
PR-1 持有页面 OCR 缓存;PR-2 持有 OpenCV geometry 缓存;PR-3 持有表格裁剪 OCR 缓存;
均不进 snapshot、不跨 Job;禁止把 timings/counts 写入 layout snapshot。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from time import perf_counter
from typing import Any
LAYOUT_DIAGNOSTIC_TIMING_KEYS: tuple[str, ...] = (
'queue_wait_ms',
'asset_read_ms',
'xfa_analysis_ms',
'mineru_wait_ms',
'mineru_result_parse_ms',
'native_pdf_extract_ms',
'native_layout_build_ms',
'native_text_alignment_ms',
'opencv_geometry_ms',
'opencv_validation_ms',
'ocr_engine_init_ms',
'ocr_inference_ms',
'layout_assembly_ms',
'layout_serialize_ms',
'coordinate_evidence_ms',
'snapshot_build_ms',
'total_handler_ms',
)
LAYOUT_DIAGNOSTIC_COUNT_KEYS: tuple[str, ...] = (
'page_count',
'mineru_table_count',
'resolved_table_count',
'partial_alignment_table_count',
'opencv_attempt_count',
'opencv_geometry_cache_hit',
'opencv_geometry_cache_miss',
'ocr_attempt_count',
'ocr_call_count',
'ocr_page_count',
'ocr_table_count',
'ocr_page_cache_hit',
'ocr_page_cache_miss',
'ocr_crop_count',
'pdfium_page_image_attach_count',
'native_token_count',
'layout_cell_count',
'ocr_engine_warm',
)
# 页面 OCR 缓存失败哨兵:与空行列表区分,表示引擎不可用。
OCR_PAGE_CACHE_UNAVAILABLE = object()
OCR_TABLE_CROP_CACHE_UNAVAILABLE = object()
def empty_layout_timings() -> dict[str, int]:
"""
构造 PR-0 全量 timing 键,未执行阶段统一为 0。
Returns:
可就地累加的 timing 字典。
"""
return {key: 0 for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS}
def empty_layout_counts() -> dict[str, Any]:
"""
构造 PR-0 全量 count 键;数值计数为 0,`ocr_engine_warm` 默认为 False。
Returns:
可就地累加的 counts 字典。
"""
counts: dict[str, Any] = {
key: 0 for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS if key != 'ocr_engine_warm'
}
counts['ocr_engine_warm'] = False
return counts
def ensure_layout_timings(timings: dict[str, Any] | None) -> dict[str, Any]:
"""
补齐缺失 timing 键为 0,不删除调用方已写入的额外键(如 native_table_detect_ms)。
Args:
timings: 既有 timing 字典;None 时返回新建空字典。
Returns:
保证含全部 PR-0 timing 键的字典。
"""
target = timings if timings is not None else {}
for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS:
if key not in target:
target[key] = 0
return target
def ensure_layout_counts(counts: dict[str, Any] | None) -> dict[str, Any]:
"""
补齐缺失 count 键;`ocr_engine_warm` 缺失时为 False。
Args:
counts: 既有 counts 字典;None 时返回新建空字典。
Returns:
保证含全部 PR-0 count 键的字典。
"""
target = counts if counts is not None else {}
for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS:
if key not in target:
target[key] = False if key == 'ocr_engine_warm' else 0
return target
def ocr_engine_is_warm() -> bool:
"""
判断当前 Worker 进程是否已持有 RapidOCR 引擎实例。
核心逻辑:读取 `_ocr_engine` 的 lru_cache;无真实 cache_info(测试 mock)时视为未 warm,
避免把 mock 调用计入初始化。
Returns:
True 表示进程内已有引擎;False 表示尚未初始化或无法判定。
"""
try:
from app.services.shipping_notice.document_layout.ocr_pdf import _ocr_engine
cache_info = getattr(_ocr_engine, 'cache_info', None)
if not callable(cache_info):
return False
currsize = getattr(cache_info(), 'currsize', None)
return isinstance(currsize, int) and currsize > 0
except Exception:
return False
def freeze_layout_diagnostics(
timings: dict[str, Any] | None,
counts: dict[str, Any] | None,
) -> tuple[dict[str, int], dict[str, Any]]:
"""
在 finish_job 前规范化 result 载荷:timing 全为 int,counts 数值为 int,warm 为 bool。
Args:
timings/counts: Job 内累加后的诊断字典。
Returns:
(timings, counts) 可直接写入 Job result 的副本。
"""
raw_timings = ensure_layout_timings(dict(timings or {}))
raw_counts = ensure_layout_counts(dict(counts or {}))
frozen_timings = {key: int(raw_timings.get(key) or 0) for key in LAYOUT_DIAGNOSTIC_TIMING_KEYS}
# 保留已有额外 timing(如 native_table_detect_ms),但不强制进契约列表。
for key, value in raw_timings.items():
if key not in frozen_timings:
try:
frozen_timings[key] = int(value or 0)
except (TypeError, ValueError):
continue
frozen_counts: dict[str, Any] = {}
for key in LAYOUT_DIAGNOSTIC_COUNT_KEYS:
if key == 'ocr_engine_warm':
frozen_counts[key] = bool(raw_counts.get(key))
else:
frozen_counts[key] = int(raw_counts.get(key) or 0)
return frozen_timings, frozen_counts
@dataclass
class LayoutJobDiagnostics:
"""
单次 Layout Job 内存诊断上下文;生命周期仅限当前 Job。
Attributes:
timings: 阶段耗时(毫秒),允许嵌套墙钟,不可简单求和。
counts: 计数与 ocr_engine_warm 标志。
ocr_pages: 已执行 RapidOCR 的去重页号,用于 ocr_page_count。
ocr_page_cache: PR-1 整页 OCR 结果;键为 (page_no, image_width, image_height)。
ocr_table_crop_cache: PR-3 表格裁剪 OCR 结果;键含页号、圆整 bbox 与图尺寸。
opencv_geometry_cache: PR-2 同表同图 geometry 结果缓存。
"""
timings: dict[str, Any] = field(default_factory=empty_layout_timings)
counts: dict[str, Any] = field(default_factory=empty_layout_counts)
ocr_pages: set[int] = field(default_factory=set)
ocr_page_cache: dict[tuple[int, int, int], Any] = field(default_factory=dict)
ocr_table_crop_cache: dict[tuple[Any, ...], Any] = field(default_factory=dict)
opencv_geometry_cache: dict[tuple[Any, ...], Any] = field(default_factory=dict)
def __post_init__(self) -> None:
"""确保 timings/counts 含全量契约键。"""
ensure_layout_timings(self.timings)
ensure_layout_counts(self.counts)
@staticmethod
def page_ocr_cache_key(page_no: int, image: Any) -> tuple[int, int, int]:
"""
构造 Job 内页面 OCR 缓存键。
Args:
page_no: PDF 页号。
image: 渲染页图;用像素宽高区分不同 render_scale。
Returns:
(page_no, image_width, image_height)。
"""
height, width = image.shape[:2]
return (int(page_no), int(width), int(height))
def add_ms(self, key: str, started: float) -> None:
"""
将 started 至今的墙钟毫秒累加到指定 timing 键。
Args:
key: LAYOUT_DIAGNOSTIC_TIMING_KEYS 中的键或额外诊断键。
started: perf_counter() 起点。
"""
elapsed = round((perf_counter() - started) * 1000)
self.timings[key] = int(self.timings.get(key) or 0) + max(elapsed, 0)
def set_ms(self, key: str, started: float) -> None:
"""
用 started 至今的墙钟毫秒覆盖写入(用于包围计时,如 native_layout_build_ms)。
Args:
key: timing 键。
started: perf_counter() 起点。
"""
self.timings[key] = max(round((perf_counter() - started) * 1000), 0)
def incr(self, key: str, amount: int = 1) -> None:
"""
累加数值型 count。
Args:
key: count 键(不得用于 ocr_engine_warm)。
amount: 增量,默认 1。
"""
if key == 'ocr_engine_warm':
return
self.counts[key] = int(self.counts.get(key) or 0) + int(amount)
def record_ocr_call(self, *, page_no: int | None = None) -> None:
"""
记录一次实际 RapidOCR 推理,并按页去重更新 ocr_page_count。
Args:
page_no: 页面号;缺失时只增加 ocr_call_count。
"""
self.incr('ocr_call_count')
if page_no is None:
return
page = int(page_no)
if page in self.ocr_pages:
return
self.ocr_pages.add(page)
self.counts['ocr_page_count'] = len(self.ocr_pages)
def record_layout_document_stats(self, layout: Any) -> None:
"""
从最终 LayoutDocument 回填 resolved/partial/token/cell 计数。
Args:
layout: contracts.LayoutDocument 或兼容对象。
"""
pages = list(getattr(layout, 'pages', None) or [])
if not self.counts.get('page_count'):
self.counts['page_count'] = len(pages)
resolved = 0
native_tokens = 0
cells = 0
for page in pages:
for table in list(getattr(page, 'tables', None) or []):
table_cells = [
cell
for row in list(getattr(table, 'rows', None) or [])
for cell in list(getattr(row, 'cells', None) or [])
]
if table_cells:
resolved += 1
cells += len(table_cells)
for token in list(getattr(page, 'tokens', None) or []):
if str(getattr(token, 'source', '') or '') == 'native_text':
native_tokens += 1
# partial_alignment 由 native_pdf 在方法 issue 处累加;此处只回填终态统计。
self.counts['resolved_table_count'] = resolved
self.counts['native_token_count'] = native_tokens
self.counts['layout_cell_count'] = cells
@@ -2,15 +2,18 @@
backend/app/services/shipping_notice/document_layout/native_pdf.py
用途:用项目既有 PDFium 提取原生 PDF 字符坐标、页面渲染,并组装保守的 layout.v1 表格候选。
依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐和布局契约。
依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐、布局契约、layout_diagnostics。
逻辑:MinerU 提供整表与 HTML;PDFium 提供独立字符/图像证据;阶段 1 优先唯一 glyph
对齐写入真实 cell bbox/token;部分唯一匹配可落盘;整体 layout 仍可 needs_review。
PR-0 可选累加 Job 级脱敏计时/计数,不改变候选算法。
PR-2:`attach_native_pdf_page_images` 在复用开关开启时仅补齐缺图页,禁止二次字符枚举。
"""
from __future__ import annotations
from dataclasses import dataclass
from html import escape
from time import perf_counter
from typing import Any
import numpy as np
@@ -31,9 +34,10 @@ from app.services.shipping_notice.document_layout.contracts import (
stable_layout_id,
)
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
from app.services.shipping_notice.document_layout.layout_diagnostics import LayoutJobDiagnostics
from app.services.shipping_notice.document_layout.mineru import MinerUParseCandidate
from app.services.shipping_notice.document_layout.opencv_table import (
reconstruct_opencv_table_geometry,
cached_reconstruct_opencv_table_geometry,
validate_opencv_cell_text,
)
from app.services.shipping_notice.document_layout.ocr_pdf import build_ocr_table_evidence
@@ -142,6 +146,72 @@ def extract_native_pdf_pages(
return pages
def layout_native_page_reuse_enabled() -> bool:
"""
读取 PR-2 PDFium 页面字符复用 / 按需补图开关。
Returns:
True 时复用前置轻量预读字符并仅补齐页面图,避免二次枚举字符层。
"""
try:
from flask import current_app, has_app_context
if not has_app_context():
return False
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED', False))
except Exception:
return False
def attach_native_pdf_page_images(
content: bytes,
pages: list[NativePdfPage],
*,
render_scale: float = 2.0,
) -> list[NativePdfPage]:
"""
在已有字符页列表上按需补齐渲染图,不重复枚举 PDF 字符层。
核心逻辑:仅打开 PDFium 渲染缺图页面;已有 image 的页原样保留;Job 结束后由调用方释放。
Args:
content: 原始 PDF 字节。
pages: 前置 `render_images=False` 提取的页面。
render_scale: 渲染倍率,须与增强链一致。
Returns:
与输入同序的页面列表;缺图页替换为带 image 的新 NativePdfPage。
Raises:
ValueError: 内容为空、倍率非法或页号越界。
"""
if not content or render_scale <= 0:
raise ValueError('native PDF content and positive render scale are required')
if not pages:
return []
if all(page.image is not None for page in pages):
return list(pages)
pdf = pdfium.PdfDocument(content)
attached: list[NativePdfPage] = []
for page in pages:
if page.image is not None:
attached.append(page)
continue
index = int(page.page_no) - 1
if index < 0 or index >= len(pdf):
raise ValueError('native PDF page_no is out of range for image attach')
image = np.asarray(pdf[index].render(scale=render_scale).to_numpy()).copy()
attached.append(NativePdfPage(
page_no=page.page_no,
width=page.width,
height=page.height,
rotation=page.rotation,
characters=page.characters,
image=image,
))
return attached
def build_native_pdf_text_table_fallbacks(
content: bytes,
*,
@@ -326,6 +396,7 @@ def build_native_pdf_layout_candidate(
content: bytes,
mineru: MinerUParseCandidate,
native_pages: list[NativePdfPage] | None = None,
diagnostics: LayoutJobDiagnostics | None = None,
) -> LayoutDocument:
"""
组合 MinerU HTML 与 PDFium 独立证据,生成始终 needs_review 的 layout.v1 候选。
@@ -336,10 +407,16 @@ def build_native_pdf_layout_candidate(
content: 原始 PDF 字节。
mineru: 同一文件的 MinerU pipeline 候选。
native_pages: 可复用的 PDFium 页面;未传入时由本函数提取。
diagnostics: 可选 Job 级诊断上下文;None 时不做计时/计数。
Returns:
通过完整布局契约校验的候选;没有可证 cell 时保留空表和 blocking issue。
"""
resolved_pages = native_pages if native_pages is not None else extract_native_pdf_pages(content)
if diagnostics is not None:
diagnostics.counts['page_count'] = len(resolved_pages)
diagnostics.counts['mineru_table_count'] = sum(
len(page.tables) for page in mineru.pages
)
mineru_pages = {item.page_no: item for item in mineru.pages}
issues: list[LayoutIssue] = [LayoutIssue(
code='document_cell_truth_deferred', severity='blocking',
@@ -353,7 +430,10 @@ def build_native_pdf_layout_candidate(
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,
native=native,
grid=grid,
table_bbox=table_candidate.bbox,
diagnostics=diagnostics,
)
except Exception:
issues.append(LayoutIssue(
@@ -361,6 +441,8 @@ def build_native_pdf_layout_candidate(
table_id=table_candidate.candidate_id,
))
continue
if diagnostics is not None and 'native_pdf_cells_from_partial_unique_text' in method_issues:
diagnostics.incr('partial_alignment_table_count')
for code in method_issues:
issues.append(LayoutIssue(
code=code, severity='blocking', page_no=native.page_no,
@@ -369,6 +451,7 @@ def build_native_pdf_layout_candidate(
if not cells:
continue
try:
assembly_started = perf_counter()
layout_table = _layout_table(
native=native,
grid=grid,
@@ -378,6 +461,8 @@ def build_native_pdf_layout_candidate(
cells=cells,
page_tokens=page_tokens,
)
if diagnostics is not None:
diagnostics.add_ms('layout_assembly_ms', assembly_started)
except Exception:
issues.append(LayoutIssue(
code='native_pdf_layout_table_invalid', severity='blocking',
@@ -389,15 +474,19 @@ def build_native_pdf_layout_candidate(
issues.append(LayoutIssue(
code='native_pdf_table_cells_unresolved', severity='blocking', page_no=native.page_no,
))
assembly_started = perf_counter()
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 diagnostics is not None:
diagnostics.add_ms('layout_assembly_ms', assembly_started)
if not any(page.tables for page in pages):
issues.append(LayoutIssue(code='native_pdf_no_resolved_tables', severity='blocking'))
return LayoutDocument(
assembly_started = perf_counter()
layout = LayoutDocument(
document_id=document_id,
content_hash=content_hash,
parser=LayoutParserInfo(
@@ -407,6 +496,10 @@ def build_native_pdf_layout_candidate(
pages=pages,
quality=LayoutQuality(status='needs_review', confidence=0, issues=issues),
)
if diagnostics is not None:
diagnostics.add_ms('layout_assembly_ms', assembly_started)
diagnostics.record_layout_document_stats(layout)
return layout
def _cells_from_text_alignment(
@@ -430,17 +523,29 @@ def _cells_from_text_alignment(
def _candidate_cells(
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox,
*,
native: NativePdfPage,
grid: HtmlGrid,
table_bbox: LayoutBBox,
diagnostics: LayoutJobDiagnostics | None = None,
) -> tuple[dict[str, dict[str, Any]], list[str]]:
"""
优先唯一文本对齐;完整失败时有框表才走 OpenCV;快速路径允许部分唯一匹配落盘。
核心逻辑:禁止在多候选重复文本上猜第 N 个;OpenCV 全表失败时回退已对齐的部分 native cell。
PR-0:在既有分支累加 alignment/OpenCV/OCR 诊断,不改变返回的 cells 与 issues。
Args:
native/grid/table_bbox: 既有表格候选输入。
diagnostics: 可选 Job 级诊断上下文。
"""
alignment_started = perf_counter()
alignment = align_html_cells_from_positioned_text(
grid, characters=native.characters, table_bbox=table_bbox,
page_width=native.width, page_height=native.height,
)
if diagnostics is not None:
diagnostics.add_ms('native_text_alignment_ms', alignment_started)
text_cells = _cells_from_text_alignment(native=native, alignment=alignment)
if alignment.complete and text_cells:
return text_cells, ['native_pdf_cells_from_unique_text_candidate']
@@ -451,20 +556,30 @@ def _candidate_cells(
list(alignment.issues) + ['native_pdf_cells_from_partial_unique_text'],
))
return {}, sorted(set(alignment.issues + ['native_pdf_render_deferred']))
geometry = reconstruct_opencv_table_geometry(
geometry_started = perf_counter()
geometry = cached_reconstruct_opencv_table_geometry(
native.image, page_width=native.width, page_height=native.height,
table_bbox=table_bbox, grid=grid,
diagnostics=diagnostics, page_no=native.page_no,
)
if diagnostics is not None:
diagnostics.add_ms('opencv_geometry_ms', geometry_started)
diagnostics.incr('opencv_attempt_count')
validation_started = perf_counter()
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 diagnostics is not None:
diagnostics.add_ms('opencv_validation_ms', validation_started)
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,
diagnostics=diagnostics,
page_no=native.page_no,
)
if not ocr.ready:
if text_cells:
@@ -2,22 +2,29 @@
backend/app/services/shipping_notice/document_layout/ocr_pdf.py
用途:保留 RapidOCR 文本行多边形坐标,并为扫描 PDF 表格提供严格 cell 候选(阶段 2)。
依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约;高亮质量对齐 field_highlight_contract。
依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约、layout_diagnostics、Flask 配置;高亮质量对齐 field_highlight_contract。
逻辑:OCR 只提供独立文本坐标与 candidate 级高亮;必须与多参数有框网格及全部非空 cell
文本一致才输出;OCR 结果不得自动升为 verified。
文本一致才输出;OCR 结果不得自动升为 verified。PR-0 可选写入 Job 级脱敏计时/计数;
PR-1 经 get_page_ocr_lines 在同 Job 内复用整页 OCR(含失败结果);
PR-3 表格 cell 路径可裁剪 OCR(安全边距),订单级 page_glyphs 仍走整页。
"""
from __future__ import annotations
from functools import lru_cache
from time import perf_counter
from typing import Any, Literal
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.layout_diagnostics import (
OCR_PAGE_CACHE_UNAVAILABLE,
LayoutJobDiagnostics,
)
from app.services.shipping_notice.document_layout.opencv_table import (
reconstruct_opencv_table_geometry,
cached_reconstruct_opencv_table_geometry,
validate_opencv_cell_text,
)
@@ -76,17 +83,33 @@ def _ocr_engine() -> Any:
def extract_ocr_lines(
image: Any, *, page_width: float, page_height: float, minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
image: Any,
*,
page_width: float,
page_height: float,
minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
diagnostics: LayoutJobDiagnostics | None = None,
page_no: int | None = None,
image_origin_x: float = 0.0,
image_origin_y: float = 0.0,
full_image_width: int | None = None,
full_image_height: int | None = None,
) -> list[OcrLine]:
"""
将 RapidOCR 图像像素多边形映射为 PDF 页面坐标。
核心逻辑:像素坐标 → 页面坐标(按渲染宽高比例);低置信度行丢弃;保留 polygon 供审计。
PR-0:可选拆分引擎初始化与推理墙钟,不改变行过滤与坐标映射结果。
PR-3:裁剪 OCR 时通过 origin + full_image_* 把 crop 像素加回整页再映射。
Args:
image: PDFium 渲染的页面 ndarray。
image: PDFium 渲染的页面或表格裁剪 ndarray。
page_width/page_height: PDF 页面单位尺寸。
minimum_confidence: OCR 行最低可信度;低于阈值完全丢弃。
diagnostics: 可选 Job 级诊断上下文;None 时不做计时/计数。
page_no: 可选页号,用于 ocr_page_count 去重。
image_origin_x/image_origin_y: 裁剪图在整页渲染图中的像素原点。
full_image_width/full_image_height: 整页渲染尺寸;裁剪路径必填。
Returns:
保持 OCR 返回顺序的文本行坐标。
@@ -96,7 +119,30 @@ def extract_ocr_lines(
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)
ref_width = int(full_image_width) if full_image_width is not None else int(width)
ref_height = int(full_image_height) if full_image_height is not None else int(height)
if ref_width <= 0 or ref_height <= 0:
raise ValueError('OCR full image dimensions must be positive')
# [STEP 1] 拆分引擎获取与推理,避免把模型加载混进 ocr_inference_ms。
cache_info = getattr(_ocr_engine, 'cache_info', None)
warm_before = False
has_real_cache = False
if callable(cache_info):
try:
currsize = getattr(cache_info(), 'currsize', None)
has_real_cache = isinstance(currsize, int)
warm_before = has_real_cache and currsize > 0
except Exception:
has_real_cache = False
init_started = perf_counter()
engine = _ocr_engine()
if diagnostics is not None and has_real_cache and not warm_before:
diagnostics.add_ms('ocr_engine_init_ms', init_started)
infer_started = perf_counter()
result, _elapsed = engine(image)
if diagnostics is not None:
diagnostics.add_ms('ocr_inference_ms', infer_started)
diagnostics.record_ocr_call(page_no=page_no)
lines: list[OcrLine] = []
for index, item in enumerate(result or []):
if len(item) < 3:
@@ -110,14 +156,14 @@ def extract_ocr_lines(
continue
try:
points = [[float(point[0]), float(point[1])] for point in polygon]
xs = [point[0] for point in points]
ys = [point[1] for point in points]
# 像素 → 页面坐标;不做额外平移猜测
xs = [point[0] + float(image_origin_x) for point in points]
ys = [point[1] + float(image_origin_y) for point in points]
# 像素 → 页面坐标;裁剪路径使用整页尺寸做比例换算
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,
x0=min(xs) * page_width / ref_width,
y0=min(ys) * page_height / ref_height,
x1=max(xs) * page_width / ref_width,
y1=max(ys) * page_height / ref_height,
)
if bbox.x1 > page_width or bbox.y1 > page_height:
continue
@@ -126,15 +172,223 @@ def extract_ocr_lines(
bbox=bbox,
confidence=confidence,
line_id=f'ocr-line-{index}',
polygon=points,
image_width=int(width),
image_height=int(height),
polygon=[[x, y] for x, y in zip(xs, ys)],
image_width=ref_width,
image_height=ref_height,
))
except (TypeError, ValueError, IndexError):
continue
return lines
def layout_ocr_page_cache_enabled() -> bool:
"""
读取 PR-1 页面 OCR 缓存开关。
核心逻辑:优先 Flask config;无应用上下文时默认关闭,避免测试/脚本意外复用。
Returns:
True 表示同 Job 内复用整页 OcrLine 结果。
"""
try:
from flask import current_app, has_app_context
if not has_app_context():
return False
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED', False))
except Exception:
return False
def layout_ocr_crop_enabled() -> bool:
"""
读取 PR-3 表格裁剪 OCR 开关。
Returns:
True 时表格 cell 候选优先裁剪识别;订单级 page_glyphs 仍用整页 OCR。
"""
try:
from flask import current_app, has_app_context
if not has_app_context():
return False
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED', False))
except Exception:
return False
def _ocr_crop_margin_ratio() -> float:
"""读取表格裁剪安全边距比例,默认 3%,夹在 [0.02, 0.05]。"""
default = 0.03
try:
from flask import current_app, has_app_context
if not has_app_context():
return default
raw = float(current_app.config.get('SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO', default))
except Exception:
return default
return min(max(raw, 0.02), 0.05)
def _expanded_table_bbox(
table_bbox: LayoutBBox, *, page_width: float, page_height: float, margin_ratio: float,
) -> LayoutBBox:
"""按页面尺寸扩展表格 bbox 安全边距,并裁剪到页面范围。"""
pad_x = page_width * margin_ratio
pad_y = page_height * margin_ratio
return LayoutBBox(
x0=max(0.0, float(table_bbox.x0) - pad_x),
y0=max(0.0, float(table_bbox.y0) - pad_y),
x1=min(page_width, float(table_bbox.x1) + pad_x),
y1=min(page_height, float(table_bbox.y1) + pad_y),
)
def extract_table_crop_ocr_lines(
image: Any,
*,
page_width: float,
page_height: float,
table_bbox: LayoutBBox,
minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
diagnostics: LayoutJobDiagnostics | None = None,
page_no: int | None = None,
use_cache: bool | None = None,
) -> list[OcrLine]:
"""
对表格区域(含安全边距)裁剪后 OCR,坐标映射回整页页面单位。
核心逻辑:仅服务表格 cell 候选;失败结果按表 bbox 缓存。订单级字段仍应走整页 OCR。
Args:
image: 整页渲染图。
page_width/page_height/table_bbox: 页面与表格坐标。
diagnostics/page_no/use_cache: 诊断与缓存控制。
Returns:
映射回整页的 OcrLine 列表。
"""
from app.services.shipping_notice.document_layout.layout_diagnostics import (
OCR_TABLE_CROP_CACHE_UNAVAILABLE,
)
cache_on = layout_ocr_crop_enabled() if use_cache is None else bool(use_cache)
margin = _ocr_crop_margin_ratio()
expanded = _expanded_table_bbox(
table_bbox, page_width=page_width, page_height=page_height, margin_ratio=margin,
)
full_height, full_width = image.shape[:2]
x0 = max(0, int(expanded.x0 * full_width / page_width))
y0 = max(0, int(expanded.y0 * full_height / page_height))
x1 = min(full_width, max(x0 + 1, int(expanded.x1 * full_width / page_width + 0.999)))
y1 = min(full_height, max(y0 + 1, int(expanded.y1 * full_height / page_height + 0.999)))
cache_key = None
if cache_on and diagnostics is not None and page_no is not None:
cache_key = (
int(page_no), round(expanded.x0, 2), round(expanded.y0, 2),
round(expanded.x1, 2), round(expanded.y1, 2), int(full_width), int(full_height),
)
if cache_key in diagnostics.ocr_table_crop_cache:
diagnostics.incr('ocr_page_cache_hit')
cached = diagnostics.ocr_table_crop_cache[cache_key]
if cached is OCR_TABLE_CROP_CACHE_UNAVAILABLE:
raise RuntimeError('ocr_engine_unavailable')
return list(cached)
diagnostics.incr('ocr_page_cache_miss')
crop = image[y0:y1, x0:x1]
if crop.size == 0:
raise ValueError('OCR table crop is empty')
if diagnostics is not None:
diagnostics.incr('ocr_crop_count')
try:
lines = extract_ocr_lines(
crop,
page_width=page_width,
page_height=page_height,
minimum_confidence=minimum_confidence,
diagnostics=diagnostics,
page_no=page_no,
image_origin_x=float(x0),
image_origin_y=float(y0),
full_image_width=int(full_width),
full_image_height=int(full_height),
)
except Exception:
if cache_key is not None and diagnostics is not None:
diagnostics.ocr_table_crop_cache[cache_key] = OCR_TABLE_CROP_CACHE_UNAVAILABLE
raise
if cache_key is not None and diagnostics is not None:
diagnostics.ocr_table_crop_cache[cache_key] = list(lines)
return lines
def get_page_ocr_lines(
image: Any,
*,
page_width: float,
page_height: float,
minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
diagnostics: LayoutJobDiagnostics | None = None,
page_no: int | None = None,
use_cache: bool | None = None,
) -> list[OcrLine]:
"""
获取整页 OCR 行;PR-1 可在同 Job 内按页缓存(含失败结果)。
核心逻辑:缓存键为 (page_no, image_width, image_height);命中则不再调用 RapidOCR;
引擎不可用缓存为哨兵并再次抛出受控异常,供调用方映射 ocr_engine_unavailable。
Args:
image/page_width/page_height/minimum_confidence: 同 extract_ocr_lines。
diagnostics: Job 诊断上下文;提供时才可写入/读取页面缓存。
page_no: 页号;缺失时不做页面缓存(仍可直接推理)。
use_cache: 显式覆盖开关;None 时读取配置。
Returns:
OCR 行列表(可能为空)。
Raises:
Exception: 与 extract_ocr_lines 相同;缓存命中 unavailable 时抛 RuntimeError。
"""
cache_on = layout_ocr_page_cache_enabled() if use_cache is None else bool(use_cache)
cache_key = None
if (
cache_on
and diagnostics is not None
and page_no is not None
and image is not None
):
cache_key = LayoutJobDiagnostics.page_ocr_cache_key(int(page_no), image)
if cache_key in diagnostics.ocr_page_cache:
diagnostics.incr('ocr_page_cache_hit')
cached = diagnostics.ocr_page_cache[cache_key]
if cached is OCR_PAGE_CACHE_UNAVAILABLE:
raise RuntimeError('ocr_engine_unavailable')
return list(cached)
if cache_key is not None and diagnostics is not None:
diagnostics.incr('ocr_page_cache_miss')
try:
lines = extract_ocr_lines(
image,
page_width=page_width,
page_height=page_height,
minimum_confidence=minimum_confidence,
diagnostics=diagnostics,
page_no=page_no,
)
except Exception:
if cache_key is not None and diagnostics is not None:
diagnostics.ocr_page_cache[cache_key] = OCR_PAGE_CACHE_UNAVAILABLE
raise
if cache_key is not None and diagnostics is not None:
# 失败空结果也缓存,避免同页多表重复打引擎。
diagnostics.ocr_page_cache[cache_key] = list(lines)
return lines
def page_bbox_to_normalized(bbox: LayoutBBox, *, page_width: float, page_height: float) -> LayoutBBox:
"""
将页面坐标转为 0..1 归一化 bbox,供 PDF.js viewport 绘制。
@@ -163,17 +417,54 @@ def page_bbox_to_normalized(bbox: LayoutBBox, *, page_width: float, page_height:
def build_ocr_table_evidence(
*, image: Any, page_width: float, page_height: float,
table_bbox: LayoutBBox, grid: HtmlGrid,
*,
image: Any,
page_width: float,
page_height: float,
table_bbox: LayoutBBox,
grid: HtmlGrid,
diagnostics: LayoutJobDiagnostics | None = None,
page_no: int | None = None,
ocr_lines: list[OcrLine] | None = None,
) -> OcrTableEvidence:
"""
对扫描表执行 OCR 行坐标、OpenCV 网格和全部非空 cell 文本三重门禁。
核心逻辑:通过后 cell.status 固定为 candidate;置信度不足/多候选/文本不一致不准入。
PR-0:进入本函数即计 ocr_attempt/ocr_table;OpenCV 子耗时累加到 diagnostics。
PR-1:ocr_lines 已提供时不再推理;否则经 get_page_ocr_lines 走页面缓存。
PR-3:开启裁剪 OCR 且未预传 ocr_lines 时,对表格区域裁剪识别(订单级仍用整页)。
Args:
image/page_width/page_height/table_bbox/grid: 既有扫描表门禁输入。
diagnostics: 可选 Job 级诊断上下文。
page_no: 可选页号,传给页面 OCR 缓存与去重计数。
ocr_lines: 可选预计算整页 OCR 行;提供时跳过推理。
"""
if diagnostics is not None:
diagnostics.incr('ocr_attempt_count')
diagnostics.incr('ocr_table_count')
try:
height, width = image.shape[:2]
lines = extract_ocr_lines(image, page_width=page_width, page_height=page_height)
if ocr_lines is not None:
lines = list(ocr_lines)
elif layout_ocr_crop_enabled():
lines = extract_table_crop_ocr_lines(
image,
page_width=page_width,
page_height=page_height,
table_bbox=table_bbox,
diagnostics=diagnostics,
page_no=page_no,
)
else:
lines = get_page_ocr_lines(
image,
page_width=page_width,
page_height=page_height,
diagnostics=diagnostics,
page_no=page_no,
)
except Exception:
return OcrTableEvidence(ready=False, issues=['ocr_engine_unavailable'])
if not lines:
@@ -183,16 +474,24 @@ def build_ocr_table_evidence(
image_width=int(width) if width else None,
image_height=int(height) if height else None,
)
geometry = reconstruct_opencv_table_geometry(
geometry_started = perf_counter()
geometry = cached_reconstruct_opencv_table_geometry(
image, page_width=page_width, page_height=page_height,
table_bbox=table_bbox, grid=grid,
diagnostics=diagnostics, page_no=page_no,
)
if diagnostics is not None:
diagnostics.add_ms('opencv_geometry_ms', geometry_started)
diagnostics.incr('opencv_attempt_count')
validation_started = perf_counter()
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 diagnostics is not None:
diagnostics.add_ms('opencv_validation_ms', validation_started)
if not validation.accepted:
return OcrTableEvidence(
ready=False,
@@ -2,9 +2,11 @@
backend/app/services/shipping_notice/document_layout/opencv_table.py
用途:在 MinerU 整表区域内用 OpenCV 恢复严格有框表网格,生成待评测的 HTML cell 几何候选。
依赖:opencv-python-headless、numpy、document_layout.html_table/contracts。
依赖:opencv-python-headless、numpy、document_layout.html_table/contracts、layout_diagnostics。
逻辑:多组形态学参数独立检测 cell 轮廓;仅当至少两组结果与 HTML 网格完全一致且边界
共识稳定时输出 ready;还必须经独立 PDF 文本验收,不得仅凭几何轮廓接受 cell(阶段 3)。
PR-2:`cached_reconstruct_opencv_table_geometry` 在同 Job 内按页/表/网格签名缓存
(含失败),不减少多配置共识组数、不改变门禁。
"""
from __future__ import annotations
@@ -115,6 +117,13 @@ def reconstruct_opencv_table_geometry(
"""
if cv2 is None:
return _not_ready(grid, 'opencv_unavailable')
# 快速退出:无效网格/空图/非法 bbox,避免无意义的多配置扫描。
if grid.row_count <= 0 or grid.column_count <= 0:
return _not_ready(grid, 'opencv_table_grid_not_detected')
if float(table_bbox.x1) <= float(table_bbox.x0) or float(table_bbox.y1) <= float(table_bbox.y0):
return _not_ready(grid, 'opencv_table_crop_invalid')
if page_image is None or getattr(page_image, 'size', 0) <= 0:
return _not_ready(grid, 'opencv_unavailable')
if min_consensus < 2 or len(configs) < min_consensus:
raise ValueError('OpenCV grid reconstruction requires at least two configurations')
image = _grayscale_page(page_image)
@@ -164,6 +173,64 @@ def reconstruct_opencv_table_geometry(
)
def cached_reconstruct_opencv_table_geometry(
page_image: np.ndarray,
*,
page_width: float,
page_height: float,
table_bbox: LayoutBBox,
grid: HtmlGrid,
diagnostics: Any | None = None,
page_no: int | None = None,
configs: tuple[OpenCVGridConfig, ...] = DEFAULT_GRID_CONFIGS,
min_consensus: int = 2,
boundary_tolerance_pixels: int = 8,
) -> OpenCVTableGeometryResult:
"""
同 Job 内复用相同 page/table/grid 的 OpenCV geometry 结果(含失败)。
核心逻辑:缓存键含页号、圆整 bbox、行列数与 rowspan/colspan 签名;不改变多配置共识门禁。
Args:
同 reconstruct_opencv_table_geometry,另加 diagnostics/page_no。
Returns:
OpenCVTableGeometryResult;命中缓存时直接返回同一对象。
"""
if diagnostics is None:
return reconstruct_opencv_table_geometry(
page_image, page_width=page_width, page_height=page_height,
table_bbox=table_bbox, grid=grid, configs=configs,
min_consensus=min_consensus,
boundary_tolerance_pixels=boundary_tolerance_pixels,
)
height, width = page_image.shape[:2]
span_sig = tuple(
(int(cell.row_index), int(cell.column_index), int(cell.row_span), int(cell.column_span))
for cell in grid.cells
)
cache_key = (
int(page_no or 0),
round(float(table_bbox.x0), 2), round(float(table_bbox.y0), 2),
round(float(table_bbox.x1), 2), round(float(table_bbox.y1), 2),
int(grid.row_count), int(grid.column_count), span_sig,
int(width), int(height), int(min_consensus), int(boundary_tolerance_pixels),
)
cached = diagnostics.opencv_geometry_cache.get(cache_key)
if cached is not None:
diagnostics.incr('opencv_geometry_cache_hit')
return cached
diagnostics.incr('opencv_geometry_cache_miss')
result = reconstruct_opencv_table_geometry(
page_image, page_width=page_width, page_height=page_height,
table_bbox=table_bbox, grid=grid, configs=configs,
min_consensus=min_consensus,
boundary_tolerance_pixels=boundary_tolerance_pixels,
)
diagnostics.opencv_geometry_cache[cache_key] = result
return result
def validate_opencv_cell_text(
geometry: OpenCVTableGeometryResult,
*,
@@ -2,9 +2,10 @@
backend/app/services/shipping_notice/document_layout/runtime.py
用途:在独立布局 Job 中调用 MinerU,并生成可持久化的紧凑文本、表格及原生 PDF 候选快照。
依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf。
依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf、layout_diagnostics。
逻辑:保存受字符预算限制的分页文本块、整表 HTML 和保守 layout.v1 候选;阶段 1 在
layout_candidate 写入真实 cell bbox 后回填 capability.cell_bbox_count,禁止长期假报 0。
PR-0 将细分 timings/counts 写入传入诊断字典,永不进入持久化快照。
"""
from __future__ import annotations
@@ -17,6 +18,11 @@ from typing import Any
from flask import current_app
from app.core.errors import AppError
from app.services.shipping_notice.document_layout.layout_diagnostics import (
LayoutJobDiagnostics,
ensure_layout_counts,
ensure_layout_timings,
)
from app.services.shipping_notice.document_layout.mineru import (
MINERU_SUPPORTED_EXTENSIONS,
MinerUClient,
@@ -97,6 +103,7 @@ def build_mineru_table_snapshot(
document_id: int | None = None,
content_hash: str | None = None,
timings: dict[str, int] | None = None,
counts: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
"""
为一个受支持附件生成紧凑 MinerU 文本与表格快照。
@@ -109,9 +116,11 @@ def build_mineru_table_snapshot(
content: 原始文件字节;不写数据库和日志。
document_id/content_hash: PDF 的版本化 Document 身份;两者齐全时生成 layout.v1 候选。
timings: 可选运维耗时字典;只写阶段毫秒数,不进入持久化快照。
counts: 可选运维计数字典;与 timings 平级写入 Job result,不进入快照。
Returns:
关闭/不支持时返回 None;成功或 Provider 降级均返回受控的版本化状态对象。
"""
diagnostics = _diagnostics_from_maps(timings=timings, counts=counts)
extension = Path(str(filename or '')).suffix.lower()
if not mineru_layout_capture_enabled(filename) or not content:
return None
@@ -123,6 +132,7 @@ def build_mineru_table_snapshot(
timings=timings,
)
if xfa_snapshot is not None:
_record_xfa_page_count(xfa_snapshot, diagnostics=diagnostics)
return xfa_snapshot
native_pages: list[Any] | None = None
if extension == '.pdf' and document_id and content_hash:
@@ -131,7 +141,10 @@ def build_mineru_table_snapshot(
native_started = perf_counter()
native_pages = extract_native_pdf_pages(content, render_images=False)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('native_pdf_extract_ms', native_started)
diagnostics.counts['page_count'] = len(native_pages)
elif timings is not None:
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
except Exception:
native_pages = None
@@ -139,7 +152,7 @@ def build_mineru_table_snapshot(
if not base_url:
fallback = _native_pdf_fallback_snapshot(
content=content, document_id=document_id, content_hash=content_hash,
native_pages=native_pages, timings=timings,
native_pages=native_pages, timings=timings, diagnostics=diagnostics,
provider_issue='mineru_base_url_missing',
)
if fallback is not None:
@@ -175,7 +188,7 @@ def build_mineru_table_snapshot(
except AppError as exc:
fallback = _native_pdf_fallback_snapshot(
content=content, document_id=document_id, content_hash=content_hash,
native_pages=native_pages, timings=timings,
native_pages=native_pages, timings=timings, diagnostics=diagnostics,
provider_issue=str(exc.code),
)
if fallback is not None:
@@ -191,7 +204,7 @@ def build_mineru_table_snapshot(
except (TypeError, ValueError):
fallback = _native_pdf_fallback_snapshot(
content=content, document_id=document_id, content_hash=content_hash,
native_pages=native_pages, timings=timings,
native_pages=native_pages, timings=timings, diagnostics=diagnostics,
provider_issue='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
)
if fallback is not None:
@@ -268,16 +281,34 @@ def build_mineru_table_snapshot(
if extension == '.pdf' and document_id and content_hash:
try:
from app.services.shipping_notice.document_layout.native_pdf import (
attach_native_pdf_page_images,
build_native_pdf_layout_candidate,
build_native_pdf_text_table_fallbacks,
extract_native_pdf_pages,
layout_native_page_reuse_enabled,
)
# MinerU 成功后进入坐标增强链;此时按需补齐页面图,供严格 OpenCV/OCR 门禁使用。
# 前置轻量预读只缓存字符,不得因为已有无图页面而跳过必要的增强证据。
# PR-2:开启复用时保留前置字符预读,仅渲染缺图页,禁止二次字符枚举。
native_started = perf_counter()
native_pages = extract_native_pdf_pages(content)
if timings is not None:
reuse = layout_native_page_reuse_enabled() and native_pages is not None
if reuse:
attached = 0
before = list(native_pages)
native_pages = attach_native_pdf_page_images(content, before)
attached = sum(
1 for old, new in zip(before, native_pages)
if old.image is None and new.image is not None
)
if diagnostics is not None:
diagnostics.incr('pdfium_page_image_attach_count', attached)
else:
native_pages = extract_native_pdf_pages(content)
if diagnostics is not None:
# 第二次提取/补图覆盖前置轻量预读耗时(既有语义:增强链提取为准)。
diagnostics.set_ms('native_pdf_extract_ms', native_started)
diagnostics.counts['page_count'] = len(native_pages)
elif timings is not None:
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
layout_source_candidate = candidate
@@ -308,23 +339,33 @@ def build_mineru_table_snapshot(
'native_pdf_text_table_fallback_used',
})
if diagnostics is not None:
diagnostics.counts['mineru_table_count'] = len(tables)
layout_started = perf_counter()
layout = build_native_pdf_layout_candidate(
document_id=int(document_id), content_hash=str(content_hash),
content=content, mineru=layout_source_candidate, native_pages=native_pages,
diagnostics=diagnostics,
)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('native_layout_build_ms', layout_started)
elif timings is not None:
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
serialize_started = perf_counter()
snapshot['layout_candidate'] = layout.model_dump(mode='json')
if diagnostics is not None:
diagnostics.set_ms('layout_serialize_ms', serialize_started)
snapshot['capability'] = _capability_with_layout_cells(
snapshot.get('capability'), layout_payload=snapshot['layout_candidate'],
)
# 冻结表格与整页字符坐标:明细重建只消费前者,订单级字段只能消费后者。
evidence_started = perf_counter()
snapshot['coordinate_evidence'] = _table_coordinate_evidence(
pages=native_pages, tables=tables,
pages=native_pages, tables=tables, diagnostics=diagnostics,
)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('coordinate_evidence_ms', evidence_started)
elif timings is not None:
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
except Exception:
snapshot['issues'] = sorted(set(
@@ -337,10 +378,67 @@ def build_mineru_table_snapshot(
return snapshot
def _diagnostics_from_maps(
*,
timings: dict[str, Any] | None,
counts: dict[str, Any] | None,
) -> LayoutJobDiagnostics | None:
"""
将 handler 传入的 timings/counts 字典包装为共享诊断上下文。
核心逻辑:任一侧非 None 即启用诊断,并保证契约键齐全;两边引用同一字典以便就地累加。
Args:
timings/counts: Job handler 持有的可变字典。
Returns:
LayoutJobDiagnostics;两者皆缺失时返回 None。
"""
if timings is None and counts is None:
return None
ensured_timings = ensure_layout_timings(timings if timings is not None else {})
ensured_counts = ensure_layout_counts(counts if counts is not None else {})
if timings is not None and timings is not ensured_timings:
timings.update(ensured_timings)
if counts is not None and counts is not ensured_counts:
counts.update(ensured_counts)
return LayoutJobDiagnostics(
timings=timings if timings is not None else ensured_timings,
counts=counts if counts is not None else ensured_counts,
)
def _record_xfa_page_count(
snapshot: dict[str, Any],
*,
diagnostics: LayoutJobDiagnostics | None,
) -> None:
"""
XFA 早退路径仅回填可安全取得的 page_count,不引入 OCR/OpenCV 逻辑。
Args:
snapshot: XFA layout 快照。
diagnostics: 可选诊断上下文。
"""
if diagnostics is None:
return
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
page_count = capability.get('page_count')
if page_count is None:
pages = snapshot.get('pages')
if isinstance(pages, list):
page_count = len(pages)
try:
diagnostics.counts['page_count'] = int(page_count or 0)
except (TypeError, ValueError):
diagnostics.counts['page_count'] = 0
def _native_pdf_fallback_snapshot(
*, content: bytes, document_id: int | None, content_hash: str | None,
native_pages: list[Any] | None, timings: dict[str, int] | None,
provider_issue: str,
diagnostics: LayoutJobDiagnostics | None = None,
) -> dict[str, Any] | None:
"""
在 MinerU 不可用时,用严格原生文字表格证据生成降级布局快照。
@@ -355,6 +453,7 @@ def _native_pdf_fallback_snapshot(
native_pages: MinerU 调用前已轻量预读的 PDFium 页面;缺失时禁止降级。
timings: 可选运维阶段耗时,不进入快照。
provider_issue: 触发降级的 MinerU 稳定问题码。
diagnostics: 可选 Job 级诊断上下文。
Returns:
证据充分时返回带 Provider 失败原因的 ready 降级快照;否则返回 None。
@@ -369,7 +468,11 @@ def _native_pdf_fallback_snapshot(
fallback_started = perf_counter()
tables = build_native_pdf_text_table_fallbacks(content, native_pages=native_pages)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('native_table_detect_ms', fallback_started)
diagnostics.counts['page_count'] = len(native_pages)
diagnostics.counts['mineru_table_count'] = len(tables)
elif timings is not None:
timings['native_table_detect_ms'] = round((perf_counter() - fallback_started) * 1000)
if not tables:
return None
@@ -382,10 +485,16 @@ def _native_pdf_fallback_snapshot(
layout = build_native_pdf_layout_candidate(
document_id=int(document_id), content_hash=str(content_hash),
content=content, mineru=candidate, native_pages=native_pages,
diagnostics=diagnostics,
)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('native_layout_build_ms', layout_started)
elif timings is not None:
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
serialize_started = perf_counter()
layout_payload_preview = layout.model_dump(mode='json')
if diagnostics is not None:
diagnostics.set_ms('layout_serialize_ms', serialize_started)
capability = _capability_with_layout_cells(
candidate.capability.model_dump(mode='json'),
layout_payload=layout_payload_preview,
@@ -395,8 +504,11 @@ def _native_pdf_fallback_snapshot(
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
evidence = _table_coordinate_evidence(
pages=native_pages, tables=tables, include_page_glyphs=False,
diagnostics=diagnostics,
)
if timings is not None:
if diagnostics is not None:
diagnostics.set_ms('coordinate_evidence_ms', evidence_started)
elif timings is not None:
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
@@ -454,7 +566,11 @@ def _native_pdf_candidate_from_tables(
def _table_coordinate_evidence(
*, pages: list[Any], tables: list[dict[str, Any]], include_page_glyphs: bool = True,
*,
pages: list[Any],
tables: list[dict[str, Any]],
include_page_glyphs: bool = True,
diagnostics: LayoutJobDiagnostics | None = None,
) -> dict[str, Any]:
"""
从已提取页面保存表内及整页字符证据,避免同一 PDF 重复解析和渲染。
@@ -463,6 +579,7 @@ def _table_coordinate_evidence(
pages: 本轮已提取的 NativePdfPage 列表。
tables: MinerU 或原生文字回退生成的表格摘要。
include_page_glyphs: 是否保留表格外整页字符证据;fallback 只保留表内证据。
diagnostics: 可选 Job 级诊断;页级 OCR 计入 ocr_*(嵌套于 coordinate_evidence_ms)。
Returns:
供明细重建与订单字段重放的坐标证据。
"""
@@ -498,9 +615,16 @@ def _table_coordinate_evidence(
# Only scanned pages without a usable native text layer trigger OCR. OCR failure
# intentionally leaves this page without order-field evidence rather than guessing.
try:
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
from app.services.shipping_notice.document_layout.ocr_pdf import get_page_ocr_lines
ocr_lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
# PR-1:与 layout 构建共享同一页面 OCR 缓存,禁止同页整页重复推理。
ocr_lines = get_page_ocr_lines(
page.image,
page_width=page.width,
page_height=page.height,
diagnostics=diagnostics,
page_no=int(page_no),
)
ocr_glyphs = _ocr_page_characters(ocr_lines)
except Exception:
ocr_glyphs = []