feat(shipping-notice): 新增发货通知自动上传功能与候选资格评估

- 在环境配置中新增 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 选项,默认关闭,需显式开启以支持自动上传。
- 引入新的 pytest.ini 文件,增加测试标记以支持自动化测试。
- 删除不再使用的 seed_shipping_notice_agents.py 文件,简化代码库。
- 更新相关 API,增强发货通知与候选资格评估功能,支持多种筛选条件。
- 增强文档与代码注释,反映新的业务逻辑与功能要求。
This commit is contained in:
hugo committed 2026-08-02 19:26:35 +08:00
1 parent cef3d5b26a
commit 3a9fbac2fc
226 files changed
+25010 -2098

No files matched your search

@@ -64,6 +64,7 @@ from app.services.shipping_notice.document_layout.ocr_pdf import (
OcrTableEvidence,
build_ocr_table_evidence,
extract_ocr_lines,
page_bbox_to_normalized,
)
from app.services.shipping_notice.document_layout.schema_mapping import (
layout_table_to_grid,
@@ -104,6 +105,7 @@ __all__ = [
'OcrTableEvidence',
'build_ocr_table_evidence',
'extract_ocr_lines',
'page_bbox_to_normalized',
'layout_table_to_grid',
'map_layout_document_to_schema',
'align_html_cells_from_positioned_text',
@@ -0,0 +1,110 @@
"""
backend/app/services/shipping_notice/document_layout/cell_coordinate_status.py
用途:阶段 3 — 按 cell 来源分级坐标质量,供 Schema 映射与复核高亮投影共用。
依赖:field_highlight_contract 冻结枚举(逻辑对齐,不反向依赖布局解析)。
逻辑:原生唯一 glyph → verified 候选;OCR/OpenCV → candidate;仅 HTML 行列 → unavailable;
禁止跨页合并 bbox(由调用方保证单页绑定)。
"""
from __future__ import annotations
from typing import Any, Literal
CellCoordinateStatus = Literal['verified', 'candidate', 'unavailable', 'invalid']
# 高风险字段:坐标错绑代价最高,OpenCV/OCR 路径必须文本独立验收(由上游保证)。
HIGH_RISK_FIELD_CODES: frozenset[str] = frozenset({
'part_number',
'customer_part_number',
'qty',
'reservation_id',
})
def classify_cell_coordinate_status(
*,
source: str | None,
has_bbox: bool,
has_token_ids: bool,
confidence: float | None = None,
field_code: str | None = None,
) -> dict[str, Any]:
"""
按来源与证据完备性裁决 cell/字段坐标状态。
Args:
source: native_text / native_glyph / ocr / html / opencv 等。
has_bbox: 是否已有可绘制几何。
has_token_ids: 是否绑定 token/glyph。
confidence: 可选置信度。
field_code: 可选字段码;高风险字段在证据不足时更严。
Returns:
highlight_quality / coordinate_status / highlight_source / coordinate_issue_codes。
"""
normalized_source = str(source or '').strip().lower()
conf = float(confidence if confidence is not None else 0)
high_risk = str(field_code or '').strip() in HIGH_RISK_FIELD_CODES
if normalized_source in {'html', 'html_only'} or (not has_bbox and not has_token_ids):
return {
'highlight_quality': 'unavailable',
'coordinate_status': 'unavailable',
'highlight_source': 'unknown' if not normalized_source else 'machine_extraction',
'coordinate_issue_codes': ['html_only_no_pdf_bbox'] if normalized_source.startswith('html') or not has_bbox else ['cell_token_unbound'],
}
if not has_bbox:
return {
'highlight_quality': 'unavailable',
'coordinate_status': 'unavailable',
'highlight_source': 'native_glyph' if 'native' in normalized_source else 'ocr' if 'ocr' in normalized_source else 'machine_extraction',
'coordinate_issue_codes': ['coordinate_missing'],
}
if normalized_source in {'native_text', 'native_glyph', 'pdfium'} and has_token_ids and conf >= 1.0:
return {
'highlight_quality': 'verified',
'coordinate_status': 'verified',
'highlight_source': 'native_glyph',
'coordinate_issue_codes': [],
}
if 'ocr' in normalized_source:
if conf < 0.8:
return {
'highlight_quality': 'unavailable',
'coordinate_status': 'unavailable',
'highlight_source': 'ocr',
'coordinate_issue_codes': ['ocr_confidence_insufficient'],
}
return {
'highlight_quality': 'candidate',
'coordinate_status': 'candidate',
'highlight_source': 'ocr',
'coordinate_issue_codes': [],
}
# OpenCV 几何共识 + 文本验收后仍只给 candidate;高风险缺 token 直接不可用
if 'opencv' in normalized_source or (normalized_source == 'native_text' and not has_token_ids):
if high_risk and not has_token_ids:
return {
'highlight_quality': 'unavailable',
'coordinate_status': 'unavailable',
'highlight_source': 'pdf_coordinate',
'coordinate_issue_codes': ['cell_token_unbound'],
}
return {
'highlight_quality': 'candidate',
'coordinate_status': 'candidate',
'highlight_source': 'pdf_coordinate',
'coordinate_issue_codes': [],
}
return {
'highlight_quality': 'candidate' if has_bbox else 'unavailable',
'coordinate_status': 'candidate' if has_bbox else 'unavailable',
'highlight_source': 'pdf_coordinate',
'coordinate_issue_codes': [] if has_bbox else ['coordinate_missing'],
}
@@ -2,8 +2,10 @@
backend/app/services/shipping_notice/document_layout/contracts.py
用途:定义解析器无关的 shipping_document_layout.v1 契约、稳定标识和完整性校验。
依赖:Pydantic 2、标准库 hashlib/json/unicodedata。
逻辑:PDF/OCR/HTML 解析器先构造 LayoutDocument;持久化、Schema 映射和评测只接受通过本模块校验的结果。
依赖:Pydantic 2、标准库 hashlib/json/unicodedata;字段高亮质量枚举与
field_highlight_contract 对齐(本模块只声明可挂载到 LayoutCell 的状态字面量)。
逻辑:PDF/OCR/HTML 解析器先构造 LayoutDocument;持久化、Schema 映射和评测只接受通过
本模块校验的结果;复核高亮投影消费 cell/token 坐标,但不在本契约内裁决绘制质量。
"""
from __future__ import annotations
@@ -18,6 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
LAYOUT_SCHEMA_VERSION = 'shipping_document_layout.v1'
# 与 field_highlight_contract.HIGHLIGHT_QUALITY_VALUES 对齐;Cell 可选挂载,禁止自创同义状态。
LAYOUT_COORDINATE_STATUS = Literal['verified', 'candidate', 'unavailable', 'invalid']
_ID_PART_RE = re.compile(r'[^a-z0-9._-]+')
@@ -114,6 +118,8 @@ class LayoutCell(LayoutContractModel):
source: Literal['native_text', 'ocr', 'html']
confidence: float = Field(ge=0, le=1)
role: Literal['header', 'data', 'summary', 'deleted', 'footer', 'unknown']
# coordinate_status 不挂载到 Cell 模型,避免改变冻结布局 checksum;
# 运行时分级见 cell_coordinate_status.classify_cell_coordinate_status(阶段 3)。
@model_validator(mode='after')
def validate_text_and_tokens(self) -> 'LayoutCell':
@@ -171,6 +171,48 @@ def canonical_layout_payload(payload: dict[str, Any]) -> tuple[str, int]:
return hashlib.sha256(encoded).hexdigest(), len(encoded)
def _fit_layout_payload_to_budget(
payload: dict[str, Any], *, max_bytes: int,
) -> tuple[dict[str, Any] | None, list[str], int]:
"""按证据优先级压缩布局快照,避免可重建证据阻断业务表保存。
核心逻辑:表格 HTML/结构是模板建模的核心;整页 glyph、文本块和页面尺寸
属于可选证据。压缩过程只删除可重建字段,并返回最终大小与诊断码。
"""
candidate = json.loads(json.dumps(payload, ensure_ascii=True))
issues: list[str] = []
_, size = canonical_layout_payload(candidate)
if size <= max_bytes:
return candidate, issues, size
evidence = candidate.get('coordinate_evidence')
if isinstance(evidence, dict):
if evidence.pop('page_glyphs', None) is not None:
issues.append('shipping_document_layout_page_glyphs_compacted')
if evidence.pop('pages', None) is not None:
issues.append('shipping_document_layout_page_metadata_compacted')
_, size = canonical_layout_payload(candidate)
if size <= max_bytes:
return candidate, issues, size
if candidate.pop('text_blocks', None) is not None:
issues.append('shipping_document_layout_text_blocks_compacted')
_, size = canonical_layout_payload(candidate)
if size <= max_bytes:
return candidate, issues, size
layout_candidate = candidate.get('layout_candidate')
if isinstance(layout_candidate, dict):
if layout_candidate.pop('page_glyphs', None) is not None:
issues.append('shipping_document_layout_candidate_glyphs_compacted')
if layout_candidate.pop('pages', None) is not None:
issues.append('shipping_document_layout_candidate_page_metadata_compacted')
_, size = canonical_layout_payload(candidate)
if size <= max_bytes:
return candidate, issues, size
return None, issues + ['shipping_document_layout_snapshot_size_exceeded'], size
def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any] | None:
"""读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。"""
version = document.current_layout_version
@@ -196,7 +238,14 @@ def record_inline_layout_snapshot(
"""
payload = dict(snapshot)
parser_key = str(parser_key or current_layout_parser_key())
checksum, payload_size = canonical_layout_payload(payload)
max_bytes = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
)), 1)
fitted_payload, compact_issues, payload_size = _fit_layout_payload_to_budget(
payload, max_bytes=max_bytes,
)
stored_for_identity = fitted_payload if fitted_payload is not None else payload
checksum, _ = canonical_layout_payload(stored_for_identity)
source_hash = str(document.content_hash or '').strip().lower()
if len(source_hash) != 64:
source_hash = hashlib.sha256(
@@ -226,15 +275,10 @@ def record_inline_layout_snapshot(
status = provider_status if provider_status in {
'ready', 'needs_review', 'failed', 'unsupported',
} else 'failed'
max_bytes = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
)), 1)
issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)})
stored_payload: dict[str, Any] | None = payload
if payload_size > max_bytes:
issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)} | set(compact_issues))
stored_payload: dict[str, Any] | None = fitted_payload
if stored_payload is None:
status = 'failed'
stored_payload = None
issues.append('shipping_document_layout_snapshot_size_exceeded')
version = ShippingDocumentLayoutVersion(
document_id=int(document.id),
version=version_no,
@@ -536,18 +580,20 @@ def complete_layout_version(
if version is None or version.status != 'running' or version.lease_token != lease_token:
db.session.rollback()
return False
checksum, payload_size = canonical_layout_payload(snapshot)
max_bytes = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
)), 1)
issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)})
fitted_snapshot, compact_issues, payload_size = _fit_layout_payload_to_budget(
snapshot, max_bytes=max_bytes,
)
stored_for_identity = fitted_snapshot if fitted_snapshot is not None else snapshot
checksum, _ = canonical_layout_payload(stored_for_identity)
issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)} | set(compact_issues))
provider_status = str(snapshot.get('status') or 'failed')
status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed'
stored_payload: dict[str, Any] | None = dict(snapshot)
if payload_size > max_bytes:
stored_payload: dict[str, Any] | None = fitted_snapshot
if stored_payload is None:
status = 'failed'
stored_payload = None
issues.append('shipping_document_layout_snapshot_size_exceeded')
now = datetime.utcnow()
version.status = status
version.parser_version = str(snapshot.get('provider_version') or '')[:64] or None
@@ -3,7 +3,8 @@ backend/app/services/shipping_notice/document_layout/native_pdf.py
用途:用项目既有 PDFium 提取原生 PDF 字符坐标、页面渲染,并组装保守的 layout.v1 表格候选。
依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐和布局契约。
逻辑:MinerU 提供整表与 HTML;PDFium提供独立字符/图像证据;只有严格匹配的 cell 才写入候选,整体仍固定 needs_review。
逻辑:MinerU 提供整表与 HTML;PDFium 提供独立字符/图像证据;阶段 1 优先唯一 glyph
对齐写入真实 cell bbox/token;部分唯一匹配可落盘;整体 layout 仍可 needs_review。
"""
from __future__ import annotations
@@ -100,6 +101,7 @@ def extract_native_pdf_pages(
if right <= left or top <= bottom:
continue
try:
# 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。
characters.append(PositionedCharacter(
text=text,
bbox=LayoutBBox(
@@ -109,6 +111,7 @@ def extract_native_pdf_pages(
))
except ValueError:
continue
characters = _assign_page_line_ids(characters, page_no=page_index + 1)
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
pages.append(NativePdfPage(
page_no=page_index + 1,
@@ -391,28 +394,47 @@ def build_native_pdf_layout_candidate(
)
def _cells_from_text_alignment(
*, native: NativePdfPage, alignment: Any,
) -> dict[str, dict[str, Any]]:
"""将唯一 glyph 对齐结果转为 cell 证据;保留 status 供高亮契约投影。"""
return {
item.cell_id: {
'bbox': item.bbox,
'tokens': [
_native_layout_token(native=native, glyph_index=index, content_hash='pending')
for index in item.glyph_indices
],
'source': 'native_text',
'confidence': 1.0 if item.status == 'verified' else 0.8,
'highlight_quality': item.status,
'line_id': item.line_id,
}
for item in alignment.cells
}
def _candidate_cells(
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox,
) -> tuple[dict[str, dict[str, Any]], list[str]]:
"""优先唯一文本对齐,失败后仅对严格有框表使用 OpenCV 双门禁。"""
"""
优先唯一文本对齐;完整失败时有框表才走 OpenCV;快速路径允许部分唯一匹配落盘。
核心逻辑:禁止在多候选重复文本上猜第 N 个;OpenCV 全表失败时回退已对齐的部分 native cell。
"""
alignment = align_html_cells_from_positioned_text(
grid, characters=native.characters, table_bbox=table_bbox,
page_width=native.width, page_height=native.height,
)
if alignment.complete:
return {
item.cell_id: {
'bbox': item.bbox,
'tokens': [
_native_layout_token(native=native, glyph_index=index, content_hash='pending')
for index in item.glyph_indices
],
'source': 'native_text', 'confidence': 1,
}
for item in alignment.cells
}, ['native_pdf_cells_from_unique_text_candidate']
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']
if native.image is None:
# 快速路径只允许原生文字的严格唯一对齐;不足时由调用方回退完整 MinerU/图像链路。
# 快速路径:部分唯一匹配仍可写入,供复核高亮;不足时由调用方回退 MinerU/图像链路。
if text_cells:
return text_cells, sorted(set(
list(alignment.issues) + ['native_pdf_cells_from_partial_unique_text'],
))
return {}, sorted(set(alignment.issues + ['native_pdf_render_deferred']))
geometry = reconstruct_opencv_table_geometry(
native.image, page_width=native.width, page_height=native.height,
@@ -430,6 +452,11 @@ def _candidate_cells(
table_bbox=table_bbox, grid=grid,
)
if not ocr.ready:
if text_cells:
return text_cells, sorted(set(
alignment.issues + geometry.issues + validation.issues + ocr.issues
+ ['native_pdf_cells_from_partial_unique_text'],
))
return {}, sorted(set(
alignment.issues + geometry.issues + validation.issues + ocr.issues,
))
@@ -447,6 +474,7 @@ def _candidate_cells(
'confidence': min(
(ocr_lines[index].confidence for index in item.line_indices), default=0,
),
'highlight_quality': 'candidate',
}
for item in ocr.cells
}, ['ocr_pdf_cells_from_grid_candidate']
@@ -455,6 +483,10 @@ def _candidate_cells(
indices = _glyph_indices_within(native.characters, item.bbox)
expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id)
if expected.text.strip() and not indices:
if text_cells:
return text_cells, sorted(set(
alignment.issues + ['native_pdf_opencv_cell_tokens_missing', 'native_pdf_cells_from_partial_unique_text'],
))
return {}, ['native_pdf_opencv_cell_tokens_missing']
cells[item.cell_id] = {
'bbox': item.bbox,
@@ -462,13 +494,16 @@ def _candidate_cells(
_native_layout_token(native=native, glyph_index=index, content_hash='pending')
for index in indices
],
'source': 'native_text', 'confidence': 1,
'source': 'native_text',
# OpenCV 路径置信度不满 1.0,防止被分级为 verified(阶段 3)。
'confidence': 0.95,
'highlight_quality': 'candidate',
}
return cells, ['native_pdf_cells_from_opencv_candidate']
def _native_layout_token(*, native: NativePdfPage, glyph_index: int, content_hash: str) -> LayoutToken:
"""把表格区域内单个 PDF glyph 转为稳定、可引用的 LayoutToken。"""
"""把表格区域内单个 PDF glyph 转为稳定、可引用的 LayoutToken(含视觉行 ID)。"""
glyph = native.characters[glyph_index]
return LayoutToken(
token_id=stable_layout_id('token', content_hash, native.page_no, glyph_index),
@@ -476,7 +511,7 @@ def _native_layout_token(*, native: NativePdfPage, glyph_index: int, content_has
normalized_text=normalize_layout_text(glyph.text),
bbox=glyph.bbox,
normalized_bbox=_normalized_bbox(glyph.bbox, native.width, native.height),
source='native_text', confidence=1, line_id=None,
source='native_text', confidence=1, line_id=glyph.line_id,
)
@@ -488,7 +523,9 @@ def _ocr_layout_token(*, native: NativePdfPage, line: Any, line_index: int) -> L
normalized_text=normalize_layout_text(line.text),
bbox=line.bbox,
normalized_bbox=_normalized_bbox(line.bbox, native.width, native.height),
source='ocr', confidence=line.confidence, line_id=None,
source='ocr',
confidence=line.confidence,
line_id=str(getattr(line, 'line_id', None) or f'ocr-line-{line_index}'),
)
@@ -496,10 +533,17 @@ def _layout_table(
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox, content_hash: str,
table_index: int, cells: dict[str, dict[str, Any]], page_tokens: dict[str, LayoutToken],
) -> LayoutTable:
"""按 HTML row/column/span 组装具有真实 bbox 和 token 引用的 needs_review 表格。"""
"""
按 HTML row/column/span 组装具有真实 bbox 和 token 引用的表格。
核心逻辑:仅写入已通过唯一对齐/OpenCV 门禁的 cell;缺失坐标的 cell 跳过,禁止均分猜框。
"""
rows: list[LayoutRow] = []
for row_index in range(grid.row_count):
source_cells = [item for item in grid.cells if item.row_index == row_index]
source_cells = [
item for item in grid.cells
if item.row_index == row_index and item.cell_id in cells
]
if not source_cells:
continue
role = 'header' if source_cells and all(item.is_header for item in source_cells) else 'data'
@@ -528,12 +572,14 @@ def _layout_table(
bbox=evidence['bbox'],
normalized_bbox=_normalized_bbox(evidence['bbox'], native.width, native.height),
token_ids=[token.token_id for token in tokens],
source=evidence['source'], confidence=evidence['confidence'], role=role,
source=evidence['source'], confidence=float(evidence['confidence']), role=role,
))
rows.append(LayoutRow(
row_id=stable_layout_id('row', content_hash, native.page_no, table_index, row_index),
row_index=row_index, cells=layout_cells, role=role,
))
if not rows:
raise ValueError('layout table requires at least one resolved cell row')
return LayoutTable(
table_id=stable_layout_id('table', content_hash, native.page_no, table_index),
bbox=table_bbox,
@@ -544,6 +590,44 @@ def _layout_table(
)
def _assign_page_line_ids(
characters: list[PositionedCharacter], *, page_no: int,
) -> list[PositionedCharacter]:
"""
为页面 glyph 分配稳定视觉行 ID,供同行门禁与 token.line_id 使用。
核心逻辑:按 y 中心聚类;不改动原始 bbox。
"""
if not characters:
return characters
ordered = sorted(
enumerate(characters),
key=lambda pair: ((pair[1].bbox.y0 + pair[1].bbox.y1) / 2, pair[1].bbox.x0),
)
assigned: list[PositionedCharacter | None] = [None] * len(characters)
current_line: list[int] = []
current_center: float | None = None
line_seq = 0
for original_index, glyph in ordered:
center_y = (glyph.bbox.y0 + glyph.bbox.y1) / 2
if current_center is None or abs(center_y - current_center) > 3:
if current_line:
line_id = f'p{page_no}-vline-{line_seq}'
line_seq += 1
for index in current_line:
assigned[index] = characters[index].model_copy(update={'line_id': line_id})
current_line = [original_index]
current_center = center_y
else:
current_line.append(original_index)
current_center = (current_center * (len(current_line) - 1) + center_y) / len(current_line)
if current_line:
line_id = f'p{page_no}-vline-{line_seq}'
for index in current_line:
assigned[index] = characters[index].model_copy(update={'line_id': line_id})
return [item if item is not None else characters[index] for index, item in enumerate(assigned)]
def _glyph_indices_within(characters: list[PositionedCharacter], bbox: LayoutBBox) -> list[int]:
"""返回中心点落在 bbox 内的 glyph 索引,保持 PDF 文本顺序。"""
return [
@@ -1,15 +1,16 @@
"""
backend/app/services/shipping_notice/document_layout/ocr_pdf.py
用途:保留 RapidOCR 文本行多边形坐标,并为扫描 PDF 表格提供严格 cell 候选。
依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约。
逻辑:OCR 只提供独立文本坐标;必须与多参数有框网格及全部非空 cell 文本一致才输出,结果仍需人工真值。
用途:保留 RapidOCR 文本行多边形坐标,并为扫描 PDF 表格提供严格 cell 候选(阶段 2)。
依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约;高亮质量对齐 field_highlight_contract。
逻辑:OCR 只提供独立文本坐标与 candidate 级高亮;必须与多参数有框网格及全部非空 cell
文本一致才输出;OCR 结果不得自动升为 verified。
"""
from __future__ import annotations
from functools import lru_cache
from typing import Any
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
@@ -20,6 +21,11 @@ from app.services.shipping_notice.document_layout.opencv_table import (
validate_opencv_cell_text,
)
# 与 field_highlight_contract 对齐。
OCR_CONFIDENCE_FLOOR = 0.8
ISSUE_OCR_CONFIDENCE = 'ocr_confidence_insufficient'
ISSUE_OCR_MULTI = 'ocr_multi_candidate'
class OcrLayoutModel(BaseModel):
"""为 OCR 坐标结果启用严格字段校验。"""
@@ -28,19 +34,26 @@ class OcrLayoutModel(BaseModel):
class OcrLine(OcrLayoutModel):
"""保存一条 RapidOCR 文本行、页面坐标和置信度。"""
"""保存一条 RapidOCR 文本行、像素多边形、页面坐标、置信度与行 ID。"""
text: str = Field(min_length=1)
bbox: LayoutBBox
confidence: float = Field(ge=0, le=1)
line_id: str
polygon: list[list[float]] = Field(default_factory=list)
image_width: int = Field(ge=1)
image_height: int = Field(ge=1)
class OcrCellEvidence(OcrLayoutModel):
"""保存经几何和文本双门禁确认的 OCR cell 候选。"""
"""保存经几何和文本双门禁确认的 OCR cell 候选;质量最高为 candidate。"""
cell_id: str
bbox: LayoutBBox
normalized_bbox: LayoutBBox | None = None
line_indices: list[int] = Field(default_factory=list)
confidence: float = Field(default=0, ge=0, le=1)
status: Literal['candidate', 'unavailable', 'invalid'] = 'candidate'
class OcrTableEvidence(OcrLayoutModel):
@@ -50,6 +63,8 @@ class OcrTableEvidence(OcrLayoutModel):
lines: list[OcrLine] = Field(default_factory=list)
cells: list[OcrCellEvidence] = Field(default_factory=list)
issues: list[str] = Field(default_factory=list)
image_width: int | None = None
image_height: int | None = None
@lru_cache(maxsize=1)
@@ -61,15 +76,18 @@ def _ocr_engine() -> Any:
def extract_ocr_lines(
image: Any, *, page_width: float, page_height: float, minimum_confidence: float = 0.8,
image: Any, *, page_width: float, page_height: float, minimum_confidence: float = OCR_CONFIDENCE_FLOOR,
) -> list[OcrLine]:
"""
将 RapidOCR 图像像素多边形映射为 PDF 页面坐标。
核心逻辑:像素坐标 → 页面坐标(按渲染宽高比例);低置信度行丢弃;保留 polygon 供审计。
Args:
image: PDFium 渲染的页面 ndarray。
page_width/page_height: PDF 页面单位尺寸。
minimum_confidence: OCR 行最低可信度;低于阈值完全丢弃。
Returns:
保持 OCR 返回顺序的文本行坐标。
"""
@@ -80,17 +98,21 @@ def extract_ocr_lines(
raise ValueError('OCR page dimensions must be positive')
result, _elapsed = _ocr_engine()(image)
lines: list[OcrLine] = []
for item in result or []:
for index, item in enumerate(result or []):
if len(item) < 3:
continue
polygon, raw_text, raw_confidence = item[0], item[1], item[2]
text = str(raw_text or '').strip()
confidence = float(raw_confidence or 0)
if not text or not normalize_layout_text(text) or confidence < minimum_confidence:
if not text or not normalize_layout_text(text):
continue
if confidence < minimum_confidence:
continue
try:
xs = [float(point[0]) for point in polygon]
ys = [float(point[1]) for point in polygon]
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]
# 像素 → 页面坐标;不做额外平移猜测
bbox = LayoutBBox(
x0=min(xs) * page_width / width,
y0=min(ys) * page_height / height,
@@ -99,23 +121,68 @@ def extract_ocr_lines(
)
if bbox.x1 > page_width or bbox.y1 > page_height:
continue
lines.append(OcrLine(text=text, bbox=bbox, confidence=confidence))
lines.append(OcrLine(
text=text,
bbox=bbox,
confidence=confidence,
line_id=f'ocr-line-{index}',
polygon=points,
image_width=int(width),
image_height=int(height),
))
except (TypeError, ValueError, IndexError):
continue
return lines
def page_bbox_to_normalized(bbox: LayoutBBox, *, page_width: float, page_height: float) -> LayoutBBox:
"""
将页面坐标转为 0..1 归一化 bbox,供 PDF.js viewport 绘制。
Args:
bbox: 页面单位矩形。
page_width/page_height: 页面尺寸。
Returns:
归一化 LayoutBBox。
Raises:
ValueError: 页面尺寸非法或归一化结果越界。
"""
if page_width <= 0 or page_height <= 0:
raise ValueError('page dimensions must be positive')
normalized = LayoutBBox(
x0=bbox.x0 / page_width,
y0=bbox.y0 / page_height,
x1=bbox.x1 / page_width,
y1=bbox.y1 / page_height,
)
if normalized.x1 > 1 or normalized.y1 > 1 or normalized.x0 < 0 or normalized.y0 < 0:
raise ValueError('normalized OCR bbox must stay within 0..1')
return normalized
def build_ocr_table_evidence(
*, image: Any, page_width: float, page_height: float,
table_bbox: LayoutBBox, grid: HtmlGrid,
) -> OcrTableEvidence:
"""对扫描表执行 OCR 行坐标、OpenCV 网格和全部非空 cell 文本三重门禁。"""
"""
对扫描表执行 OCR 行坐标、OpenCV 网格和全部非空 cell 文本三重门禁。
核心逻辑:通过后 cell.status 固定为 candidate;置信度不足/多候选/文本不一致不准入。
"""
try:
height, width = image.shape[:2]
lines = extract_ocr_lines(image, page_width=page_width, page_height=page_height)
except Exception:
return OcrTableEvidence(ready=False, issues=['ocr_engine_unavailable'])
if not lines:
return OcrTableEvidence(ready=False, issues=['ocr_text_missing'])
return OcrTableEvidence(
ready=False,
issues=['ocr_text_missing', ISSUE_OCR_CONFIDENCE],
image_width=int(width) if width else None,
image_height=int(height) if height else None,
)
geometry = reconstruct_opencv_table_geometry(
image, page_width=page_width, page_height=page_height,
table_bbox=table_bbox, grid=grid,
@@ -128,16 +195,70 @@ def build_ocr_table_evidence(
)
if not validation.accepted:
return OcrTableEvidence(
ready=False, issues=sorted(set(geometry.issues + validation.issues)),
ready=False,
lines=lines,
issues=sorted(set(geometry.issues + validation.issues)),
image_width=int(width),
image_height=int(height),
)
cells = []
cells: list[OcrCellEvidence] = []
issues: set[str] = set()
for item in geometry.cells:
indices = _line_indices_within(lines, item.bbox)
expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id)
if expected.text.strip() and not indices:
return OcrTableEvidence(ready=False, issues=['ocr_cell_tokens_missing'])
cells.append(OcrCellEvidence(cell_id=item.cell_id, bbox=item.bbox, line_indices=indices))
return OcrTableEvidence(ready=True, lines=lines, cells=cells, issues=[])
return OcrTableEvidence(
ready=False, lines=lines, issues=['ocr_cell_tokens_missing'],
image_width=int(width), image_height=int(height),
)
if len(indices) > 1 and _ambiguous_ocr_lines(lines, indices, expected.text):
issues.add(ISSUE_OCR_MULTI)
continue
confidences = [lines[index].confidence for index in indices] or [0.0]
confidence = min(confidences)
if confidence < OCR_CONFIDENCE_FLOOR:
issues.add(ISSUE_OCR_CONFIDENCE)
continue
try:
normalized = page_bbox_to_normalized(item.bbox, page_width=page_width, page_height=page_height)
except ValueError:
issues.add('coordinate_bbox_invalid')
continue
cells.append(OcrCellEvidence(
cell_id=item.cell_id,
bbox=item.bbox,
normalized_bbox=normalized,
line_indices=indices,
confidence=confidence,
status='candidate',
))
if not cells:
return OcrTableEvidence(
ready=False, lines=lines, issues=sorted(issues or {'ocr_cells_unavailable'}),
image_width=int(width), image_height=int(height),
)
# 非空 cell 必须全部拿到 OCR 候选,否则不宣称 ready
required = {cell.cell_id for cell in grid.cells if cell.text.strip()}
if required - {cell.cell_id for cell in cells}:
return OcrTableEvidence(
ready=False, lines=lines, cells=cells,
issues=sorted(issues | {'ocr_cells_incomplete'}),
image_width=int(width), image_height=int(height),
)
return OcrTableEvidence(
ready=True, lines=lines, cells=cells, issues=sorted(issues),
image_width=int(width), image_height=int(height),
)
def _ambiguous_ocr_lines(lines: list[OcrLine], indices: list[int], expected_text: str) -> bool:
"""同一 cell 内多条 OCR 行且规范化文本无法唯一对上期望值时视为多候选。"""
expected = normalize_layout_text(expected_text).casefold()
matched = [
index for index in indices
if normalize_layout_text(lines[index].text).casefold() == expected
]
return len(matched) != 1 and len(indices) > 1
def _line_indices_within(lines: list[OcrLine], bbox: LayoutBBox) -> list[int]:
@@ -3,7 +3,8 @@ backend/app/services/shipping_notice/document_layout/opencv_table.py
用途:在 MinerU 整表区域内用 OpenCV 恢复严格有框表网格,生成待评测的 HTML cell 几何候选。
依赖:opencv-python-headless、numpy、document_layout.html_table/contracts。
逻辑:多组形态学参数独立检测 cell 轮廓;仅当至少两组结果与 HTML 网格完全一致且边界共识稳定时输出 ready。
逻辑:多组形态学参数独立检测 cell 轮廓;仅当至少两组结果与 HTML 网格完全一致且边界
共识稳定时输出 ready;还必须经独立 PDF 文本验收,不得仅凭几何轮廓接受 cell(阶段 3)。
"""
from __future__ import annotations
@@ -3,7 +3,8 @@ backend/app/services/shipping_notice/document_layout/runtime.py
用途:在独立布局 Job 中调用 MinerU,并生成可持久化的紧凑文本、表格及原生 PDF 候选快照。
依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf。
逻辑:保存受字符预算限制的分页文本块、整表 HTML 和保守 layout.v1 候选;Provider 错误安全降级,不保存原始响应。
逻辑:保存受字符预算限制的分页文本块、整表 HTML 和保守 layout.v1 候选;阶段 1 在
layout_candidate 写入真实 cell bbox 后回填 capability.cell_bbox_count,禁止长期假报 0。
"""
from __future__ import annotations
@@ -238,6 +239,9 @@ def build_mineru_table_snapshot(
if timings is not None:
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
snapshot['layout_candidate'] = layout.model_dump(mode='json')
snapshot['capability'] = _capability_with_layout_cells(
snapshot.get('capability'), layout_payload=snapshot['layout_candidate'],
)
# 冻结表格与整页字符坐标:明细重建只消费前者,订单级字段只能消费后者。
evidence_started = perf_counter()
snapshot['coordinate_evidence'] = _table_coordinate_evidence(
@@ -325,28 +329,40 @@ def _native_pdf_fast_snapshot(
)
if timings is not None:
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
layout_payload_preview = layout.model_dump(mode='json')
capability = _capability_with_layout_cells(
candidate.capability.model_dump(mode='json'),
layout_payload=layout_payload_preview,
)
evidence_started = perf_counter()
evidence = _table_coordinate_evidence(pages=native_pages, tables=tables)
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
# 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,
)
if timings is not None:
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'pdfium', 'provider_version': 'native-text-v1', 'backend': 'native_pdf',
'status': 'ready', 'text_blocks': [], 'tables': tables,
'capability': candidate.capability.model_dump(mode='json'),
'layout_candidate': layout.model_dump(mode='json'),
'capability': capability,
'layout_candidate': layout_payload_preview,
'coordinate_evidence': evidence,
'issues': ['native_pdf_text_table_fallback_used'],
}
def _table_coordinate_evidence(*, pages: list[Any], tables: list[dict[str, Any]]) -> dict[str, Any]:
def _table_coordinate_evidence(
*, pages: list[Any], tables: list[dict[str, Any]], include_page_glyphs: bool = True,
) -> dict[str, Any]:
"""
从已提取页面保存表内及整页字符证据,避免同一 PDF 重复解析和渲染。
Args:
pages: 本轮已提取的 NativePdfPage 列表。
tables: MinerU 或原生文字回退生成的表格摘要。
include_page_glyphs: 是否保留表格外整页字符证据;fallback 只保留表内证据。
Returns:
供明细重建与订单字段重放的坐标证据。
"""
@@ -373,7 +389,7 @@ def _table_coordinate_evidence(*, pages: list[Any], tables: list[dict[str, Any]]
evidence[table_id] = glyphs
page_glyphs: dict[str, list[dict[str, Any]]] = {}
page_sources: dict[str, str] = {}
for page_no, page in pages.items():
for page_no, page in pages.items() if include_page_glyphs else []:
native_glyphs = [item.model_dump(mode='json') for item in page.characters]
if native_glyphs:
page_glyphs[str(page_no)] = native_glyphs
@@ -407,6 +423,52 @@ def _table_coordinate_evidence(*, pages: list[Any], tables: list[dict[str, Any]]
}
def _count_layout_cell_bboxes(layout_payload: dict[str, Any] | None) -> int:
"""统计 layout_candidate 中带有效 bbox 的 cell 数量。"""
if not isinstance(layout_payload, dict):
return 0
count = 0
for page in layout_payload.get('pages') or []:
if not isinstance(page, dict):
continue
for table in page.get('tables') or []:
if not isinstance(table, dict):
continue
for row in table.get('rows') or []:
if not isinstance(row, dict):
continue
for cell in row.get('cells') or []:
if not isinstance(cell, dict):
continue
bbox = cell.get('bbox') if isinstance(cell.get('bbox'), dict) else None
if bbox and all(key in bbox for key in ('x0', 'y0', 'x1', 'y1')):
count += 1
return count
def _capability_with_layout_cells(
capability: dict[str, Any] | None,
*,
layout_payload: dict[str, Any] | None,
) -> dict[str, Any]:
"""
用 layout_candidate 真实 cell bbox 回填 capability,避免假报 cell_bbox_count=0。
核心逻辑:has_cell_coordinates 仅在 cell 覆盖达到 html_cell_count 时为 True;
部分唯一匹配只更新计数,不宣称确定性 cell 证据已就绪。
"""
base = dict(capability) if isinstance(capability, dict) else {}
cell_bbox_count = _count_layout_cell_bboxes(layout_payload)
html_cell_count = int(base.get('html_cell_count') or 0)
has_page = bool(base.get('has_page_coordinates'))
has_table = bool(base.get('has_table_structure'))
has_cells = cell_bbox_count > 0 and (html_cell_count <= 0 or cell_bbox_count >= html_cell_count)
base['cell_bbox_count'] = cell_bbox_count
base['has_cell_coordinates'] = has_cells
base['deterministic_cell_evidence_ready'] = has_page and has_table and has_cells
return base
def _ocr_page_characters(lines: list[Any]) -> list[dict[str, Any]]:
"""把整页 OCR 行均匀拆成字符证据;仅服务订单字段锚点,不参与表格 cell 自动接受。"""
result: list[dict[str, Any]] = []
@@ -2,15 +2,26 @@
backend/app/services/shipping_notice/document_layout/schema_mapping.py
用途:将 shipping_document_layout.v1 的真实 cell/token 证据映射到 Run 冻结订单 Schema。
依赖:布局契约、HTML 网格统一映射器、TableHeaderContract。
逻辑:只消费契约已验证行列和显式 continuation;不猜跨页、不提升质量状态、不接受无 cell 证据字段。
依赖:布局契约、HTML 网格统一映射器、TableHeaderContract;坐标字段对齐 field_highlight_contract。
逻辑:只消费契约已验证行列和显式 continuation;不猜跨页;字段候选分离 cell_bbox 与
token 并集 value_bbox;quote/bbox_text 取自 layout 文本,禁止回写 machine value。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.document_layout.contracts import LayoutDocument, LayoutTable, validate_layout_document
from app.services.shipping_notice.document_layout.cell_coordinate_status import (
classify_cell_coordinate_status,
)
from app.services.shipping_notice.document_layout.contracts import (
LayoutBBox,
LayoutCell,
LayoutDocument,
LayoutTable,
LayoutToken,
validate_layout_document,
)
from app.services.shipping_notice.document_layout.html_table import (
HtmlGrid,
HtmlGridCell,
@@ -28,7 +39,7 @@ def map_layout_document_to_schema(
ignorable_column_headers: list[str] | None = None,
) -> list[dict[str, Any]]:
"""
映射完整布局文档,并输出保留 cell/token 证据的安全候选。
映射完整布局文档,并输出保留 cell/token/坐标证据的安全候选。
Args:
layout: 必须通过 shipping_document_layout.v1 完整校验。
@@ -40,13 +51,14 @@ def map_layout_document_to_schema(
document = validate_layout_document(layout)
result: list[dict[str, Any]] = []
for page in document.pages:
tokens_by_id = {token.token_id: token for token in page.tokens}
for table in page.tables:
grid = layout_table_to_grid(table)
mapped = map_html_grid_to_schema(
grid, page_no=page.page_no, table_id=table.table_id, contract=contract,
)
token_ids_by_cell = {
cell.cell_id: list(cell.token_ids)
cells_by_id = {
cell.cell_id: cell
for row in table.rows for cell in row.cells
}
row_payloads = []
@@ -55,14 +67,17 @@ def map_layout_document_to_schema(
row_payloads.append({
**row.model_dump(mode='json'),
'cells': row_cells,
'fields': [{
**field.model_dump(mode='json'),
'token_ids': token_ids_by_cell.get(field.cell_id, []),
'evidence_ref': (
f'layout:{document.document_id}:p{page.page_no}:'
f'{table.table_id}:{field.cell_id}'
),
} for field in row.fields],
'fields': [
_field_with_coordinate_evidence(
field=field,
cell=cells_by_id.get(field.cell_id),
tokens_by_id=tokens_by_id,
document_id=document.document_id,
page_no=page.page_no,
table_id=table.table_id,
)
for field in row.fields
],
})
unmapped_nonempty = collect_unmapped_nonempty_columns(
grid,
@@ -145,3 +160,97 @@ def _row_cell_snapshots(grid: HtmlGrid, *, row_index: int) -> list[dict[str, str
'text': slot.text.strip(),
})
return snapshots
def _union_layout_bbox(boxes: list[LayoutBBox]) -> LayoutBBox | None:
"""合并多个 bbox 为最小外接矩形;空列表返回 None。"""
if not boxes:
return None
return LayoutBBox(
x0=min(item.x0 for item in boxes),
y0=min(item.y0 for item in boxes),
x1=max(item.x1 for item in boxes),
y1=max(item.y1 for item in boxes),
)
def _field_with_coordinate_evidence(
*,
field: Any,
cell: LayoutCell | None,
tokens_by_id: dict[str, LayoutToken],
document_id: int,
page_no: int,
table_id: str,
) -> dict[str, Any]:
"""
为 Schema 字段候选挂载可回溯坐标证据,供 generic_order_evidence 透传。
核心逻辑:保留 cell_bbox;有 token 时 value_bbox=token 并集且 bbox_text=token 文本;
quote 取自 bbox_text/cell.text,禁止写 machine value;质量由来源分级器裁决。
"""
payload = field.model_dump(mode='json')
evidence_ref = f'layout:{document_id}:p{page_no}:{table_id}:{field.cell_id}'
field_code = str(getattr(field, 'field_code', None) or payload.get('field_code') or '')
payload.update({
'page_no': page_no,
'table_id': table_id,
'token_ids': list(cell.token_ids) if cell is not None else [],
'evidence_ref': evidence_ref,
'row_index': getattr(field, 'row_index', None),
'column_index': getattr(field, 'column_index', None),
})
if cell is None:
grade = classify_cell_coordinate_status(
source='html', has_bbox=False, has_token_ids=False, field_code=field_code,
)
payload.update(grade)
return payload
# [STEP 1] 始终保留整格几何,供审计/诊断;高亮优先用更紧的 value_bbox
payload['cell_id'] = cell.cell_id
payload['cell_bbox'] = cell.bbox.model_dump(mode='json')
payload['cell_normalized_bbox'] = cell.normalized_bbox.model_dump(mode='json')
token_objs = [
tokens_by_id[token_id]
for token_id in cell.token_ids
if token_id in tokens_by_id
]
value_bbox = _union_layout_bbox([item.bbox for item in token_objs])
value_normalized = _union_layout_bbox([item.normalized_bbox for item in token_objs])
if value_bbox is not None and value_normalized is not None:
# [STEP 2] native/OCR 有 token:高亮框用 glyph/token 并集,引文取区域文本
bbox_text = ''.join(item.text for item in token_objs)
payload['value_bbox'] = value_bbox.model_dump(mode='json')
payload['normalized_bbox'] = value_normalized.model_dump(mode='json')
payload['bbox_text'] = bbox_text
payload['quote'] = bbox_text[:1000]
payload['quote_source'] = 'bbox_tokens'
payload['has_value_coordinate'] = True
has_value_bbox = True
else:
# [STEP 3] 无 token:value_bbox 必须为 null,仅保留 cell_bbox 供诊断,禁止冒充字段级框
payload['value_bbox'] = None
payload['normalized_bbox'] = None
payload['has_value_coordinate'] = False
cell_text = str(cell.text or '')
payload['bbox_text'] = cell_text
payload['quote'] = cell_text[:1000]
payload['quote_source'] = 'layout_cell_text'
has_value_bbox = False
grade = classify_cell_coordinate_status(
source=cell.source,
has_bbox=has_value_bbox,
has_token_ids=bool(token_objs),
confidence=float(cell.confidence),
field_code=field_code,
)
payload['source'] = (
'native_glyph' if grade['highlight_source'] == 'native_glyph'
else grade['highlight_source'] if grade['highlight_source'] != 'unknown'
else cell.source
)
payload.update(grade)
return payload
@@ -1,22 +1,29 @@
"""
backend/app/services/shipping_notice/document_layout/text_cell_alignment.py
用途:用原生 PDF 字符坐标为 MinerU HTML cell 生成严格、可追溯的几何候选。
依赖:document_layout contracts/html_table、Pydantic。
逻辑:只接受表格区域内唯一且不重叠的规范化文本匹配;重复、空白或冲突 cell 不猜框。
用途:用原生 PDF glyph 坐标为 HTML cell 生成严格、可追溯的几何候选(阶段 1)。
依赖:document_layout contracts/html_table、Pydantic;issue 码与 field_highlight_contract 对齐。
逻辑:只接受表格区域内唯一、连续、同行且不共享的规范化文本匹配;重复/空白/冲突
cell 不猜框;匹配 bbox 为 glyph 并集,且必须落在表格 bbox 内并与引文一致。
"""
from __future__ import annotations
import re
import unicodedata
from typing import Any
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError as PydanticValidationError, model_validator
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
# 与 field_highlight_contract.COORDINATE_ISSUE_CODES 对齐的对外稳定码。
ISSUE_DUPLICATE_TEXT = 'duplicate_text_coordinate_ambiguous'
ISSUE_VALUE_MISMATCH = 'value_bbox_text_mismatch'
ISSUE_OUTSIDE_TABLE = 'coordinate_outside_table'
ISSUE_SHARED_TOKEN = 'coordinate_shared_token_conflict'
class TextCellAlignmentModel(BaseModel):
"""为字符和 cell 候选启用严格字段校验,防止评测辅助结果静默漂移。"""
@@ -25,15 +32,16 @@ class TextCellAlignmentModel(BaseModel):
class PositionedCharacter(TextCellAlignmentModel):
"""保存 PDF 原生文本层的单个可见字符及页面坐标。"""
"""保存 PDF 原生文本层的单个可见字符、页面坐标与视觉行身份。"""
text: str = Field(min_length=1, max_length=8)
bbox: LayoutBBox
source_index: int | None = Field(default=None, ge=0)
line_id: str | None = None
class TextAlignedCell(TextCellAlignmentModel):
"""保存唯一文本匹配得到的 HTML cell 候选框;仍需人工视觉确认。"""
"""唯一文本匹配得到的 cell 几何;status 供高亮契约投影,不替代业务确认。"""
cell_id: str
row_index: int = Field(ge=0)
@@ -41,6 +49,8 @@ class TextAlignedCell(TextCellAlignmentModel):
bbox: LayoutBBox
normalized_bbox: LayoutBBox
glyph_indices: list[int] = Field(default_factory=list)
line_id: str | None = None
status: Literal['verified', 'candidate'] = 'candidate'
class TextCellAlignmentResult(TextCellAlignmentModel):
@@ -74,13 +84,23 @@ def align_html_cells_from_positioned_text(
"""
在整表区域内按唯一规范化文本匹配 HTML 原始 cell,并合并字符 bbox。
核心逻辑(阶段 1 门禁):
1. 单元格文本规范化后在表格区域内唯一匹配;
2. glyph 必须连续且同一视觉行;
3. glyph 不得被其他 cell 共享;
4. cell bbox = glyph 并集,且不得超出表格 bbox;
5. bbox 内文本必须与 cell 文本一致;
6. 多候选 → 不生成框,issue=`duplicate_text_coordinate_ambiguous`;
7. 空 cell 不参与定位。
Args:
grid: 已展开但仍保留原始 cell 身份的 HTML 网格。
characters: PDF 原生文本层字符及左上原点页面坐标。
table_bbox: MinerU 整表页面 bbox,仅在该范围内搜索。
table_bbox: 整表页面 bbox,仅在该范围内搜索。
page_width/page_height: 页面尺寸,用于生成 0..1 标准化坐标。
Returns:
可供人工叠框 Review 的候选;任何歧义都保留 issue,绝不进入生产证据。
可供复核高亮消费的候选;任何歧义都保留 issue,绝不按序号或均分猜框。
"""
if page_width <= 0 or page_height <= 0:
raise ValueError('text cell alignment page dimensions must be positive')
@@ -99,6 +119,7 @@ def align_html_cells_from_positioned_text(
continue
glyphs.append(glyph)
glyphs = [item for item in glyphs if _bbox_center_within(table_bbox, item.bbox)]
glyphs = _ensure_visual_line_ids(glyphs)
normalized_stream, stream_to_glyph = _normalized_character_stream(glyphs)
used_glyphs: set[int] = set()
matched: list[TextAlignedCell] = []
@@ -106,54 +127,121 @@ def align_html_cells_from_positioned_text(
if invalid_character_bbox:
issues.add('text_cell_alignment_invalid_character_bbox')
# 非空 cell 才计入 complete 期望,空 cell 不参与定位也不阻断唯一匹配覆盖率。
alignable_cells = [cell for cell in grid.cells if _normalize_text(cell.text)]
for cell in grid.cells:
expected = _normalize_text(cell.text)
if not expected:
issues.add('text_cell_alignment_empty_cell')
continue
starts = [match.start() for match in re.finditer(re.escape(expected), normalized_stream)]
if len(starts) != 1:
issues.add(
'text_cell_alignment_text_not_found'
if not starts else 'text_cell_alignment_text_not_unique'
)
if len(starts) == 0:
issues.add('text_cell_alignment_text_not_found')
continue
if len(starts) > 1:
# 关键风险:短文本/重复值不得按「第 N 个」绑定
issues.add('text_cell_alignment_text_not_unique')
issues.add(ISSUE_DUPLICATE_TEXT)
continue
indices = set(stream_to_glyph[starts[0]:starts[0] + len(expected)])
if not indices or indices & used_glyphs:
issues.add('text_cell_alignment_glyph_overlap')
issues.add(ISSUE_SHARED_TOKEN)
continue
matched_glyphs = [glyphs[index] for index in sorted(indices)]
if not _glyphs_form_contiguous_text(matched_glyphs):
issues.add('text_cell_alignment_geometry_discontinuous')
continue
line_ids = {item.line_id for item in matched_glyphs if item.line_id}
if len(line_ids) > 1:
issues.add('text_cell_alignment_geometry_discontinuous')
continue
bbox = _union_bbox([item.bbox for item in matched_glyphs])
if not _bbox_contains(table_bbox, bbox):
issues.add('text_cell_alignment_bbox_outside_table')
issues.add(ISSUE_OUTSIDE_TABLE)
continue
# [STEP] 引文与 bbox 内文字独立校验;不一致禁止产出框
region_text = _normalize_text(''.join(item.text for item in matched_glyphs))
if region_text != expected:
issues.add('text_cell_alignment_value_mismatch')
issues.add(ISSUE_VALUE_MISMATCH)
continue
normalized = LayoutBBox(
x0=bbox.x0 / page_width,
y0=bbox.y0 / page_height,
x1=bbox.x1 / page_width,
y1=bbox.y1 / page_height,
)
if not _roundtrip_normalized_ok(bbox, normalized, page_width, page_height):
issues.add('text_cell_alignment_coordinate_roundtrip_failed')
continue
used_glyphs.update(indices)
matched.append(TextAlignedCell(
cell_id=cell.cell_id,
row_index=cell.row_index,
column_index=cell.column_index,
bbox=bbox,
normalized_bbox=LayoutBBox(
x0=bbox.x0 / page_width,
y0=bbox.y0 / page_height,
x1=bbox.x1 / page_width,
y1=bbox.y1 / page_height,
),
normalized_bbox=normalized,
glyph_indices=sorted(
glyphs[index].source_index if glyphs[index].source_index is not None else index
for index in indices
),
line_id=next(iter(line_ids), None),
# 全部硬门禁通过 → verified;供高亮契约使用,不改业务确认。
status='verified',
))
expected_count = len(alignable_cells)
return TextCellAlignmentResult(
complete=bool(grid.cells) and len(matched) == len(grid.cells),
expected_cell_count=len(grid.cells),
complete=bool(alignable_cells) and len(matched) == expected_count,
expected_cell_count=expected_count,
matched_cell_count=len(matched),
cells=matched,
issues=sorted(issues),
)
def _ensure_visual_line_ids(characters: list[PositionedCharacter]) -> list[PositionedCharacter]:
"""
为缺少 line_id 的 glyph 按视觉基线聚类分配行 ID。
核心逻辑:已有 line_id 保留;其余按 y 中心邻近归入同一行,保证同行门禁可判定。
"""
if not characters:
return characters
if all(item.line_id for item in characters):
return characters
ordered = sorted(
enumerate(characters),
key=lambda pair: ((pair[1].bbox.y0 + pair[1].bbox.y1) / 2, pair[1].bbox.x0),
)
assigned: list[PositionedCharacter | None] = [None] * len(characters)
current_line: list[int] = []
current_center: float | None = None
line_seq = 0
for original_index, glyph in ordered:
center_y = (glyph.bbox.y0 + glyph.bbox.y1) / 2
if current_center is None or abs(center_y - current_center) > 3:
if current_line:
line_id = f'vline-{line_seq}'
line_seq += 1
for index in current_line:
source = characters[index]
assigned[index] = source if source.line_id else source.model_copy(update={'line_id': line_id})
current_line = [original_index]
current_center = center_y
else:
current_line.append(original_index)
current_center = (current_center * (len(current_line) - 1) + center_y) / len(current_line)
if current_line:
line_id = f'vline-{line_seq}'
for index in current_line:
source = characters[index]
assigned[index] = source if source.line_id else source.model_copy(update={'line_id': line_id})
return [item if item is not None else characters[index] for index, item in enumerate(assigned)]
def _normalized_character_stream(
characters: list[PositionedCharacter],
) -> tuple[str, list[int]]:
@@ -180,6 +268,14 @@ def _bbox_center_within(parent: LayoutBBox, child: LayoutBBox) -> bool:
return parent.x0 <= center_x <= parent.x1 and parent.y0 <= center_y <= parent.y1
def _bbox_contains(parent: LayoutBBox, child: LayoutBBox) -> bool:
"""要求子矩形完整落在父矩形内(值框不得超出表格)。"""
return (
child.x0 >= parent.x0 and child.y0 >= parent.y0
and child.x1 <= parent.x1 and child.y1 <= parent.y1
)
def _union_bbox(boxes: list[LayoutBBox]) -> LayoutBBox:
"""合并唯一匹配字符范围;调用方保证列表非空。"""
return LayoutBBox(
@@ -190,6 +286,31 @@ def _union_bbox(boxes: list[LayoutBBox]) -> LayoutBBox:
)
def _roundtrip_normalized_ok(
absolute: LayoutBBox,
normalized: LayoutBBox,
page_width: float,
page_height: float,
*,
tol: float = 0.51,
) -> bool:
"""归一化与绝对坐标双向换算校验,防止缩放错误进入高亮。"""
if not (0 <= normalized.x0 < normalized.x1 <= 1 and 0 <= normalized.y0 < normalized.y1 <= 1):
return False
restored = LayoutBBox(
x0=normalized.x0 * page_width,
y0=normalized.y0 * page_height,
x1=normalized.x1 * page_width,
y1=normalized.y1 * page_height,
)
return (
abs(restored.x0 - absolute.x0) <= tol
and abs(restored.y0 - absolute.y0) <= tol
and abs(restored.x1 - absolute.x1) <= tol
and abs(restored.y1 - absolute.y1) <= tol
)
def _glyphs_form_contiguous_text(characters: list[PositionedCharacter]) -> bool:
"""要求匹配字符处于同一视觉行且水平间距连续,禁止跨 cell/跨行拼接。"""
if not characters: