feat(shipping-notice): 增强订单抽取功能,添加进度事件和诊断运行管理,优化数据模型和访问控制
This commit is contained in:
1 parent
ce26d6d0c4
commit
c4095b08da
175 files changed
+13064
-1814
No files matched your search
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/__init__.py
|
||||
|
||||
用途:导出版面结构化公共契约,供 PDF、OCR、HTML 表格解析器和订单抽取链路复用。
|
||||
依赖:document_layout.contracts。
|
||||
逻辑:上游解析器产出统一 LayoutDocument;下游只消费版本化契约,不依赖具体解析引擎。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import (
|
||||
LAYOUT_SCHEMA_VERSION,
|
||||
LayoutCell,
|
||||
LayoutDocument,
|
||||
LayoutPage,
|
||||
LayoutQuality,
|
||||
LayoutRow,
|
||||
LayoutTable,
|
||||
LayoutToken,
|
||||
canonical_layout_checksum,
|
||||
stable_layout_id,
|
||||
validate_layout_document,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.evaluation import (
|
||||
ANNOTATION_SCHEMA_VERSION,
|
||||
LayoutAnnotation,
|
||||
LayoutEvaluation,
|
||||
evaluate_layout,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.coverage import (
|
||||
HtmlSchemaCoverageReport,
|
||||
summarize_html_schema_coverage,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.mineru import (
|
||||
MINERU_SUPPORTED_EXTENSIONS,
|
||||
MinerUCapabilityReport,
|
||||
MinerUClient,
|
||||
MinerUClientConfig,
|
||||
MinerUParseCandidate,
|
||||
MinerUTextCandidate,
|
||||
inspect_mineru_capabilities,
|
||||
parse_mineru_candidate,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import (
|
||||
HtmlGrid,
|
||||
HtmlTableMappingResult,
|
||||
map_html_table_to_schema,
|
||||
parse_html_grid,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'LAYOUT_SCHEMA_VERSION',
|
||||
'ANNOTATION_SCHEMA_VERSION',
|
||||
'LayoutAnnotation',
|
||||
'LayoutCell',
|
||||
'LayoutDocument',
|
||||
'LayoutEvaluation',
|
||||
'LayoutPage',
|
||||
'LayoutQuality',
|
||||
'LayoutRow',
|
||||
'LayoutTable',
|
||||
'LayoutToken',
|
||||
'HtmlGrid',
|
||||
'HtmlSchemaCoverageReport',
|
||||
'HtmlTableMappingResult',
|
||||
'MINERU_SUPPORTED_EXTENSIONS',
|
||||
'MinerUCapabilityReport',
|
||||
'MinerUClient',
|
||||
'MinerUClientConfig',
|
||||
'MinerUParseCandidate',
|
||||
'MinerUTextCandidate',
|
||||
'canonical_layout_checksum',
|
||||
'evaluate_layout',
|
||||
'inspect_mineru_capabilities',
|
||||
'parse_mineru_candidate',
|
||||
'map_html_table_to_schema',
|
||||
'parse_html_grid',
|
||||
'stable_layout_id',
|
||||
'summarize_html_schema_coverage',
|
||||
'validate_layout_document',
|
||||
]
|
||||
@@ -0,0 +1,355 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/contracts.py
|
||||
|
||||
用途:定义解析器无关的 shipping_document_layout.v1 契约、稳定标识和完整性校验。
|
||||
依赖:Pydantic 2、标准库 hashlib/json/unicodedata。
|
||||
逻辑:PDF/OCR/HTML 解析器先构造 LayoutDocument;持久化、Schema 映射和评测只接受通过本模块校验的结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
|
||||
LAYOUT_SCHEMA_VERSION = 'shipping_document_layout.v1'
|
||||
_ID_PART_RE = re.compile(r'[^a-z0-9._-]+')
|
||||
|
||||
|
||||
class LayoutContractModel(BaseModel):
|
||||
"""为全部版面对象提供严格字段和赋值校验,防止解析器静默输出漂移。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class LayoutBBox(LayoutContractModel):
|
||||
"""表示左上原点坐标系中的矩形;原始坐标使用页面单位,标准化坐标使用 0..1。"""
|
||||
|
||||
x0: float
|
||||
y0: float
|
||||
x1: float
|
||||
y1: float
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_order(self) -> 'LayoutBBox':
|
||||
"""拒绝倒置或零面积矩形,避免下游列聚类读取无效几何。"""
|
||||
if self.x0 < 0 or self.y0 < 0 or self.x1 <= self.x0 or self.y1 <= self.y0:
|
||||
raise ValueError('bbox must have non-negative origin and positive area')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutParserInfo(LayoutContractModel):
|
||||
"""记录生成版面结果的解析器身份,作为重解析和审计版本边界。"""
|
||||
|
||||
name: str = Field(min_length=1, max_length=100)
|
||||
version: str = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class LayoutIssue(LayoutContractModel):
|
||||
"""记录机器可读质量问题及其最小定位信息,不在日志中复制文档正文。"""
|
||||
|
||||
code: str = Field(min_length=1, max_length=100)
|
||||
severity: Literal['info', 'warning', 'blocking']
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
table_id: str | None = None
|
||||
cell_id: str | None = None
|
||||
details: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class LayoutQuality(LayoutContractModel):
|
||||
"""汇总版面解析是否可被确定性字段映射消费。"""
|
||||
|
||||
status: Literal['accepted', 'needs_review', 'failed', 'unsupported']
|
||||
confidence: float = Field(ge=0, le=1)
|
||||
issues: list[LayoutIssue] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_blocking_status(self) -> 'LayoutQuality':
|
||||
"""阻断问题不得被标记为 accepted,避免错误结构流入自动建单。"""
|
||||
if self.status == 'accepted' and any(item.severity == 'blocking' for item in self.issues):
|
||||
raise ValueError('accepted layout must not contain blocking issues')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutToken(LayoutContractModel):
|
||||
"""保存原生 PDF 或 OCR 的最小文本词元及真实页面坐标。"""
|
||||
|
||||
token_id: str = Field(min_length=1, max_length=160)
|
||||
text: str = Field(min_length=1)
|
||||
normalized_text: str
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
source: Literal['native_text', 'ocr']
|
||||
confidence: float = Field(ge=0, le=1)
|
||||
line_id: str | None = None
|
||||
|
||||
@field_validator('normalized_text')
|
||||
@classmethod
|
||||
def validate_normalized_text(cls, value: str) -> str:
|
||||
"""要求规范化文本非空,使单元格匹配不会依赖不可见字符。"""
|
||||
text = str(value or '').strip()
|
||||
if not text:
|
||||
raise ValueError('normalized_text is required')
|
||||
return text
|
||||
|
||||
|
||||
class LayoutCell(LayoutContractModel):
|
||||
"""保存单元格文字、坐标、跨度、来源词元和语义角色。"""
|
||||
|
||||
cell_id: str = Field(min_length=1, max_length=160)
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
row_span: int = Field(default=1, ge=1)
|
||||
column_span: int = Field(default=1, ge=1)
|
||||
text: str
|
||||
normalized_text: str
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
token_ids: list[str] = Field(default_factory=list)
|
||||
source: Literal['native_text', 'ocr', 'html']
|
||||
confidence: float = Field(ge=0, le=1)
|
||||
role: Literal['header', 'data', 'summary', 'deleted', 'footer', 'unknown']
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_text_and_tokens(self) -> 'LayoutCell':
|
||||
"""确保有内容的 PDF/OCR 单元格可追溯到词元;HTML 单元格由 DOM 直接证明。"""
|
||||
if self.text and not self.normalized_text.strip():
|
||||
raise ValueError('non-empty cell text requires normalized_text')
|
||||
if self.source in {'native_text', 'ocr'} and self.text and not self.token_ids:
|
||||
raise ValueError('PDF/OCR cell text requires token_ids')
|
||||
if len(self.token_ids) != len(set(self.token_ids)):
|
||||
raise ValueError('cell token_ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutRow(LayoutContractModel):
|
||||
"""保存表格内稳定行号及其按列排序的单元格。"""
|
||||
|
||||
row_id: str = Field(min_length=1, max_length=160)
|
||||
row_index: int = Field(ge=0)
|
||||
cells: list[LayoutCell]
|
||||
role: Literal['header', 'data', 'summary', 'deleted', 'footer', 'unknown']
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_cells(self) -> 'LayoutRow':
|
||||
"""拒绝空行、重复列和行索引错配,避免解析器将视觉片段伪装为完整数据行。"""
|
||||
if not self.cells:
|
||||
raise ValueError('layout row requires at least one cell')
|
||||
columns = [item.column_index for item in self.cells]
|
||||
if columns != sorted(columns) or len(columns) != len(set(columns)):
|
||||
raise ValueError('row cells must have unique ascending column_index values')
|
||||
if any(item.row_index != self.row_index for item in self.cells):
|
||||
raise ValueError('cell row_index must equal parent row_index')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutTable(LayoutContractModel):
|
||||
"""保存单页表格、表头行、跨页关系和质量状态。"""
|
||||
|
||||
table_id: str = Field(min_length=1, max_length=160)
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
rows: list[LayoutRow]
|
||||
header_row_indices: list[int] = Field(default_factory=list)
|
||||
continuation_of: str | None = None
|
||||
confidence: float = Field(ge=0, le=1)
|
||||
status: Literal['accepted', 'needs_review', 'failed']
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_rows(self) -> 'LayoutTable':
|
||||
"""确保行列跨度、表头角色和单元格几何一致,跨页关系交给文档级校验。"""
|
||||
if not self.rows:
|
||||
raise ValueError('layout table requires at least one row')
|
||||
indices = [item.row_index for item in self.rows]
|
||||
if indices != sorted(indices) or len(indices) != len(set(indices)):
|
||||
raise ValueError('table rows must have unique ascending row_index values')
|
||||
if self.header_row_indices != sorted(set(self.header_row_indices)):
|
||||
raise ValueError('header_row_indices must be unique and ascending')
|
||||
if any(index not in set(indices) for index in self.header_row_indices):
|
||||
raise ValueError('header_row_indices must reference table rows')
|
||||
header_indices = set(self.header_row_indices)
|
||||
if any(row.row_index in header_indices and row.role != 'header' for row in self.rows):
|
||||
raise ValueError('header row role must be header')
|
||||
occupied: set[tuple[int, int]] = set()
|
||||
for row in self.rows:
|
||||
for cell in row.cells:
|
||||
if not _bbox_contains(self.bbox, cell.bbox):
|
||||
raise ValueError(f'cell {cell.cell_id} bbox must be within table bbox')
|
||||
if not _bbox_contains(self.normalized_bbox, cell.normalized_bbox):
|
||||
raise ValueError(f'cell {cell.cell_id} normalized_bbox must be within table normalized_bbox')
|
||||
for row_index in range(cell.row_index, cell.row_index + cell.row_span):
|
||||
for column_index in range(cell.column_index, cell.column_index + cell.column_span):
|
||||
position = (row_index, column_index)
|
||||
if position in occupied:
|
||||
raise ValueError('table cells must not have overlapping row/column spans')
|
||||
occupied.add(position)
|
||||
return self
|
||||
|
||||
|
||||
class LayoutPage(LayoutContractModel):
|
||||
"""保存单页尺寸、旋转、词元和表格;所有原始坐标必须落在页面范围内。"""
|
||||
|
||||
page_no: int = Field(ge=1)
|
||||
width: float = Field(gt=0)
|
||||
height: float = Field(gt=0)
|
||||
rotation: Literal[0, 90, 180, 270] = 0
|
||||
tokens: list[LayoutToken] = Field(default_factory=list)
|
||||
tables: list[LayoutTable] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_page_geometry(self) -> 'LayoutPage':
|
||||
"""验证页面内 ID、词元引用及坐标边界,阻止不可追溯的单元格进入持久化。"""
|
||||
token_ids = [item.token_id for item in self.tokens]
|
||||
if len(token_ids) != len(set(token_ids)):
|
||||
raise ValueError('token_id must be unique within a page')
|
||||
table_ids = [item.table_id for item in self.tables]
|
||||
if len(table_ids) != len(set(table_ids)):
|
||||
raise ValueError('table_id must be unique within a page')
|
||||
cell_ids: set[str] = set()
|
||||
known_tokens = set(token_ids)
|
||||
for token in self.tokens:
|
||||
_validate_bbox(token.bbox, width=self.width, height=self.height, label=token.token_id)
|
||||
_validate_normalized_bbox(token.normalized_bbox, label=token.token_id)
|
||||
for table in self.tables:
|
||||
_validate_bbox(table.bbox, width=self.width, height=self.height, label=table.table_id)
|
||||
_validate_normalized_bbox(table.normalized_bbox, label=table.table_id)
|
||||
for row in table.rows:
|
||||
for cell in row.cells:
|
||||
if cell.cell_id in cell_ids:
|
||||
raise ValueError('cell_id must be unique within a page')
|
||||
cell_ids.add(cell.cell_id)
|
||||
_validate_bbox(cell.bbox, width=self.width, height=self.height, label=cell.cell_id)
|
||||
_validate_normalized_bbox(cell.normalized_bbox, label=cell.cell_id)
|
||||
if not set(cell.token_ids).issubset(known_tokens):
|
||||
raise ValueError(f'cell {cell.cell_id} references unknown token_id')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutDocument(LayoutContractModel):
|
||||
"""表示一份 Document 的完整、版本化、可审计版面结果。"""
|
||||
|
||||
schema_version: Literal[LAYOUT_SCHEMA_VERSION] = LAYOUT_SCHEMA_VERSION
|
||||
document_id: int = Field(ge=1)
|
||||
content_hash: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
parser: LayoutParserInfo
|
||||
pages: list[LayoutPage]
|
||||
quality: LayoutQuality
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_document_graph(self) -> 'LayoutDocument':
|
||||
"""验证页序、全局 ID 和跨页 continuation,保证引用只指向更早页面的表格。"""
|
||||
if not self.pages:
|
||||
raise ValueError('layout document requires at least one page')
|
||||
page_numbers = [item.page_no for item in self.pages]
|
||||
if page_numbers != list(range(1, len(self.pages) + 1)):
|
||||
raise ValueError('page_no values must be contiguous and start at 1')
|
||||
table_pages: dict[str, int] = {}
|
||||
global_ids: set[str] = set()
|
||||
for page in self.pages:
|
||||
for token in page.tokens:
|
||||
_add_global_id(global_ids, token.token_id)
|
||||
for table in page.tables:
|
||||
_add_global_id(global_ids, table.table_id)
|
||||
table_pages[table.table_id] = page.page_no
|
||||
for row in table.rows:
|
||||
_add_global_id(global_ids, row.row_id)
|
||||
for cell in row.cells:
|
||||
_add_global_id(global_ids, cell.cell_id)
|
||||
for page in self.pages:
|
||||
for table in page.tables:
|
||||
if table.continuation_of is None:
|
||||
continue
|
||||
parent_page = table_pages.get(table.continuation_of)
|
||||
if parent_page is None or parent_page >= page.page_no:
|
||||
raise ValueError('continuation_of must reference a table on an earlier page')
|
||||
return self
|
||||
|
||||
|
||||
def stable_layout_id(prefix: str, *parts: Any) -> str:
|
||||
"""
|
||||
由内容稳定的组成部分生成可读标识,避免重复解析使用随机 UUID。
|
||||
|
||||
Args:
|
||||
prefix: token/table/row/cell 等对象类别。
|
||||
parts: 文档哈希、页码、表序、行列序等稳定组成部分。
|
||||
Returns:
|
||||
规范化前缀加 16 位 SHA-256 摘要。
|
||||
Raises:
|
||||
ValueError: 前缀或组成部分为空。
|
||||
"""
|
||||
safe_prefix = _ID_PART_RE.sub('-', str(prefix or '').strip().lower()).strip('-')
|
||||
values = [str(item).strip() for item in parts]
|
||||
if not safe_prefix or not values or any(not item for item in values):
|
||||
raise ValueError('stable layout id requires prefix and non-empty parts')
|
||||
digest = hashlib.sha256('\x1f'.join(values).encode('utf-8')).hexdigest()[:16]
|
||||
return f'{safe_prefix}-{digest}'
|
||||
|
||||
|
||||
def normalize_layout_text(value: Any) -> str:
|
||||
"""以 NFKC 和空白折叠生成布局匹配文本,同时保留原始 text 作为审计证据。"""
|
||||
text = unicodedata.normalize('NFKC', str(value or ''))
|
||||
return ' '.join(text.split()).strip()
|
||||
|
||||
|
||||
def validate_layout_document(payload: dict[str, Any] | LayoutDocument) -> LayoutDocument:
|
||||
"""
|
||||
将字典或既有对象校验为 LayoutDocument。
|
||||
|
||||
Args:
|
||||
payload: 解析器输出的完整布局字典或 LayoutDocument。
|
||||
Returns:
|
||||
通过严格字段、几何和引用校验的 LayoutDocument。
|
||||
Raises:
|
||||
pydantic.ValidationError: 契约、坐标或引用不合法。
|
||||
"""
|
||||
if isinstance(payload, LayoutDocument):
|
||||
return LayoutDocument.model_validate(payload.model_dump(mode='json'))
|
||||
return LayoutDocument.model_validate(payload)
|
||||
|
||||
|
||||
def canonical_layout_checksum(payload: dict[str, Any] | LayoutDocument) -> str:
|
||||
"""
|
||||
计算布局结果的 canonical SHA-256,供幂等、漂移检测和测试重放使用。
|
||||
|
||||
Args:
|
||||
payload: 必须先通过完整契约校验的布局结果。
|
||||
Returns:
|
||||
64 位小写十六进制 SHA-256。
|
||||
"""
|
||||
document = validate_layout_document(payload)
|
||||
raw = json.dumps(
|
||||
document.model_dump(mode='json'), ensure_ascii=False, sort_keys=True, separators=(',', ':'),
|
||||
)
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _validate_bbox(bbox: LayoutBBox, *, width: float, height: float, label: str) -> None:
|
||||
"""验证原始坐标位于页面边界内。"""
|
||||
if bbox.x1 > width or bbox.y1 > height:
|
||||
raise ValueError(f'{label} bbox exceeds page bounds')
|
||||
|
||||
|
||||
def _validate_normalized_bbox(bbox: LayoutBBox, *, label: str) -> None:
|
||||
"""验证标准化坐标完整位于 0..1,供跨页面几何比较。"""
|
||||
if bbox.x1 > 1 or bbox.y1 > 1:
|
||||
raise ValueError(f'{label} normalized_bbox must be within 0..1')
|
||||
|
||||
|
||||
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 _add_global_id(known: set[str], value: str) -> None:
|
||||
"""登记文档内全局 ID,并拒绝不同对象共享同一证据标识。"""
|
||||
if value in known:
|
||||
raise ValueError(f'duplicate layout object id: {value}')
|
||||
known.add(value)
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/coverage.py
|
||||
|
||||
用途:汇总 HTML 表格对冻结订单 Schema 的匿名覆盖指标,供 L0/L4 Review 重复执行。
|
||||
依赖:Pydantic、document_layout.html_table 映射结果。
|
||||
逻辑:调用方完成单表映射后提交结果;本模块只累计计数和受控编码,不保存表头、字段值或证据文本。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from typing import Iterable
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlTableMappingResult
|
||||
|
||||
|
||||
class CoverageModel(BaseModel):
|
||||
"""为匿名覆盖报告启用严格字段校验,避免原文意外进入输出。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class HtmlSchemaCoverageReport(CoverageModel):
|
||||
"""保存不含文件、表头、单元格和值的 Schema 映射聚合指标。"""
|
||||
|
||||
table_count: int = Field(ge=0)
|
||||
tables_with_mapped_header: int = Field(ge=0)
|
||||
tables_without_mapped_header: int = Field(ge=0)
|
||||
mapped_columns: int = Field(ge=0)
|
||||
unmapped_columns: int = Field(ge=0)
|
||||
ambiguous_columns: int = Field(ge=0)
|
||||
mapped_column_rate: float = Field(ge=0, le=1)
|
||||
data_rows: int = Field(ge=0)
|
||||
build_complete_rows: int = Field(ge=0)
|
||||
all_required_complete_rows: int = Field(ge=0)
|
||||
build_complete_rate: float = Field(ge=0, le=1)
|
||||
all_required_complete_rate: float = Field(ge=0, le=1)
|
||||
field_code_frequency: dict[str, int]
|
||||
issue_code_frequency: dict[str, int]
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_totals(self) -> 'HtmlSchemaCoverageReport':
|
||||
"""确保分项不超过对应总数,防止评估脚本产生自相矛盾的验收证据。"""
|
||||
if self.tables_with_mapped_header + self.tables_without_mapped_header != self.table_count:
|
||||
raise ValueError('HTML coverage table totals are inconsistent')
|
||||
if self.build_complete_rows > self.data_rows or self.all_required_complete_rows > self.data_rows:
|
||||
raise ValueError('HTML coverage row totals are inconsistent')
|
||||
return self
|
||||
|
||||
|
||||
def summarize_html_schema_coverage(
|
||||
mappings: Iterable[HtmlTableMappingResult],
|
||||
) -> HtmlSchemaCoverageReport:
|
||||
"""
|
||||
汇总多张 HTML 表格的匿名冻结 Schema 覆盖指标。
|
||||
|
||||
Args:
|
||||
mappings: 已完成映射的单表结果;可来自 MinerU、EML HTML 或测试夹具。
|
||||
Returns:
|
||||
只含聚合计数、字段编码和问题编码的 HtmlSchemaCoverageReport。
|
||||
"""
|
||||
counters: Counter[str] = Counter()
|
||||
fields: Counter[str] = Counter()
|
||||
issues: Counter[str] = Counter()
|
||||
for mapping in mappings:
|
||||
counters['table_count'] += 1
|
||||
counters[
|
||||
'tables_with_mapped_header'
|
||||
if mapping.header_row_index is not None
|
||||
else 'tables_without_mapped_header'
|
||||
] += 1
|
||||
for column in mapping.columns:
|
||||
counters[f'{column.status}_columns'] += 1
|
||||
issues.update(mapping.issues)
|
||||
for row in mapping.rows:
|
||||
if row.role != 'data':
|
||||
continue
|
||||
counters['data_rows'] += 1
|
||||
counters['build_complete_rows'] += int(row.complete_build_fields)
|
||||
counters['all_required_complete_rows'] += int(row.complete_required_fields)
|
||||
fields.update(field.field_code for field in row.fields)
|
||||
|
||||
column_count = (
|
||||
counters['mapped_columns']
|
||||
+ counters['unmapped_columns']
|
||||
+ counters['ambiguous_columns']
|
||||
)
|
||||
data_rows = counters['data_rows']
|
||||
return HtmlSchemaCoverageReport(
|
||||
table_count=counters['table_count'],
|
||||
tables_with_mapped_header=counters['tables_with_mapped_header'],
|
||||
tables_without_mapped_header=counters['tables_without_mapped_header'],
|
||||
mapped_columns=counters['mapped_columns'],
|
||||
unmapped_columns=counters['unmapped_columns'],
|
||||
ambiguous_columns=counters['ambiguous_columns'],
|
||||
mapped_column_rate=(counters['mapped_columns'] / column_count if column_count else 0.0),
|
||||
data_rows=data_rows,
|
||||
build_complete_rows=counters['build_complete_rows'],
|
||||
all_required_complete_rows=counters['all_required_complete_rows'],
|
||||
build_complete_rate=(counters['build_complete_rows'] / data_rows if data_rows else 0.0),
|
||||
all_required_complete_rate=(
|
||||
counters['all_required_complete_rows'] / data_rows if data_rows else 0.0
|
||||
),
|
||||
field_code_frequency=dict(sorted(fields.items())),
|
||||
issue_code_frequency=dict(sorted(issues.items())),
|
||||
)
|
||||
@@ -0,0 +1,264 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/evaluation.py
|
||||
|
||||
用途:定义版面解析人工真值格式并计算阶段 L0/L2/L3 的表格与单元格质量指标。
|
||||
依赖:Pydantic 2、document_layout.contracts。
|
||||
逻辑:人工标注保存期望表格/单元格位置;候选解析结果按页与几何交并比匹配,输出可审计指标而非业务订单值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import (
|
||||
LAYOUT_SCHEMA_VERSION,
|
||||
LayoutBBox,
|
||||
LayoutDocument,
|
||||
validate_layout_document,
|
||||
)
|
||||
|
||||
|
||||
ANNOTATION_SCHEMA_VERSION = 'shipping_document_layout_annotation.v1'
|
||||
|
||||
|
||||
class LayoutAnnotationModel(BaseModel):
|
||||
"""为人工真值对象启用严格字段校验,防止标注格式漂移。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class AnnotatedCell(LayoutAnnotationModel):
|
||||
"""记录人工确认的单元格位置、列归属和可选业务字段,不保存邮件身份信息。"""
|
||||
|
||||
annotation_id: str = Field(min_length=1, max_length=160)
|
||||
page_no: int = Field(ge=1)
|
||||
table_index: int = Field(ge=0)
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
normalized_bbox: LayoutBBox
|
||||
normalized_text: str
|
||||
role: str
|
||||
expected_field_code: str | None = None
|
||||
|
||||
|
||||
class AnnotatedTable(LayoutAnnotationModel):
|
||||
"""记录人工确认的单页表格区域和单元格集合。"""
|
||||
|
||||
annotation_id: str = Field(min_length=1, max_length=160)
|
||||
page_no: int = Field(ge=1)
|
||||
table_index: int = Field(ge=0)
|
||||
normalized_bbox: LayoutBBox
|
||||
cells: list[AnnotatedCell]
|
||||
continuation_of: str | None = None
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_cells(self) -> 'AnnotatedTable':
|
||||
"""要求标准化坐标有效,且子单元格指向并落在同一父表格内。"""
|
||||
_validate_normalized_bbox(self.normalized_bbox, label=self.annotation_id)
|
||||
ids = [item.annotation_id for item in self.cells]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('annotated cell ids must be unique')
|
||||
if any(item.page_no != self.page_no or item.table_index != self.table_index for item in self.cells):
|
||||
raise ValueError('annotated cells must reference their parent table')
|
||||
for cell in self.cells:
|
||||
_validate_normalized_bbox(cell.normalized_bbox, label=cell.annotation_id)
|
||||
if not _bbox_contains(self.normalized_bbox, cell.normalized_bbox):
|
||||
raise ValueError('annotated cell bbox must be within parent table bbox')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutAnnotation(LayoutAnnotationModel):
|
||||
"""保存一份脱敏文档的布局人工真值及样本类别标签。"""
|
||||
|
||||
schema_version: str = ANNOTATION_SCHEMA_VERSION
|
||||
layout_schema_version: str = LAYOUT_SCHEMA_VERSION
|
||||
sample_id: str = Field(min_length=1, max_length=160)
|
||||
content_hash: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
categories: list[str] = Field(min_length=1)
|
||||
tables: list[AnnotatedTable]
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_annotation(self) -> 'LayoutAnnotation':
|
||||
"""拒绝重复表格标识和悬空跨页引用,保证评测真值自身可信。"""
|
||||
if self.schema_version != ANNOTATION_SCHEMA_VERSION:
|
||||
raise ValueError('unsupported annotation schema_version')
|
||||
if self.layout_schema_version != LAYOUT_SCHEMA_VERSION:
|
||||
raise ValueError('annotation layout schema_version mismatch')
|
||||
table_ids = [item.annotation_id for item in self.tables]
|
||||
if len(table_ids) != len(set(table_ids)):
|
||||
raise ValueError('annotated table ids must be unique')
|
||||
pages = {item.annotation_id: item.page_no for item in self.tables}
|
||||
for table in self.tables:
|
||||
if table.continuation_of is None:
|
||||
continue
|
||||
parent_page = pages.get(table.continuation_of)
|
||||
if parent_page is None or parent_page >= table.page_no:
|
||||
raise ValueError('annotated continuation must reference an earlier page')
|
||||
return self
|
||||
|
||||
|
||||
class LayoutEvaluation(LayoutAnnotationModel):
|
||||
"""汇总表格检测、单元格检测、归行归列和业务字段归属指标。"""
|
||||
|
||||
expected_tables: int
|
||||
matched_tables: int
|
||||
expected_cells: int
|
||||
matched_cells: int
|
||||
correctly_positioned_cells: int
|
||||
field_labeled_cells: int
|
||||
correctly_mapped_fields: int
|
||||
table_detection_recall: float = Field(ge=0, le=1)
|
||||
cell_detection_recall: float = Field(ge=0, le=1)
|
||||
cell_position_accuracy: float = Field(ge=0, le=1)
|
||||
field_mapping_accuracy: float | None = Field(default=None, ge=0, le=1)
|
||||
|
||||
|
||||
def evaluate_layout(
|
||||
annotation: dict | LayoutAnnotation,
|
||||
candidate: dict | LayoutDocument,
|
||||
*,
|
||||
table_iou_threshold: float = 0.8,
|
||||
cell_iou_threshold: float = 0.8,
|
||||
mapped_field_codes: dict[str, str] | None = None,
|
||||
) -> LayoutEvaluation:
|
||||
"""
|
||||
将解析结果与人工真值按页和 bbox IoU 一对一匹配并计算阶段指标。
|
||||
|
||||
Args:
|
||||
annotation: 通过 v1 标注契约的人工真值。
|
||||
candidate: 通过 shipping_document_layout.v1 的解析结果。
|
||||
table_iou_threshold: 表格区域视为命中的最小 IoU。
|
||||
cell_iou_threshold: 单元格区域视为命中的最小 IoU。
|
||||
mapped_field_codes: 可选的 candidate cell_id -> field_code 映射,用于阶段 L4 评测。
|
||||
Returns:
|
||||
表格、单元格、位置和字段映射指标。
|
||||
Raises:
|
||||
ValueError: 阈值不在 0..1 或文档 content_hash 与真值不一致。
|
||||
"""
|
||||
if not 0 <= table_iou_threshold <= 1 or not 0 <= cell_iou_threshold <= 1:
|
||||
raise ValueError('IoU thresholds must be within 0..1')
|
||||
truth = annotation if isinstance(annotation, LayoutAnnotation) else LayoutAnnotation.model_validate(annotation)
|
||||
layout = validate_layout_document(candidate)
|
||||
if truth.content_hash != layout.content_hash:
|
||||
raise ValueError('annotation and candidate content_hash must match')
|
||||
|
||||
candidate_tables = [
|
||||
(page.page_no, table)
|
||||
for page in layout.pages
|
||||
for table in page.tables
|
||||
]
|
||||
matched_table_ids: set[str] = set()
|
||||
matched_tables: list[tuple[AnnotatedTable, object]] = []
|
||||
for expected in truth.tables:
|
||||
hit = _best_unused_match(
|
||||
expected.normalized_bbox,
|
||||
[(table.table_id, table.normalized_bbox, table) for page_no, table in candidate_tables if page_no == expected.page_no],
|
||||
used=matched_table_ids,
|
||||
threshold=table_iou_threshold,
|
||||
)
|
||||
if hit is not None:
|
||||
matched_table_ids.add(hit[0])
|
||||
matched_tables.append((expected, hit[1]))
|
||||
|
||||
expected_cells = sum(len(item.cells) for item in truth.tables)
|
||||
matched_cells = 0
|
||||
positioned_cells = 0
|
||||
field_labeled_cells = 0
|
||||
correctly_mapped_fields = 0
|
||||
field_codes = mapped_field_codes or {}
|
||||
for expected_table, candidate_table in matched_tables:
|
||||
used_cells: set[str] = set()
|
||||
candidates = [
|
||||
(cell.cell_id, cell.normalized_bbox, cell)
|
||||
for row in candidate_table.rows
|
||||
for cell in row.cells
|
||||
]
|
||||
for expected_cell in expected_table.cells:
|
||||
if expected_cell.expected_field_code:
|
||||
field_labeled_cells += 1
|
||||
hit = _best_unused_match(
|
||||
expected_cell.normalized_bbox,
|
||||
candidates,
|
||||
used=used_cells,
|
||||
threshold=cell_iou_threshold,
|
||||
)
|
||||
if hit is None:
|
||||
continue
|
||||
cell_id, candidate_cell = hit
|
||||
used_cells.add(cell_id)
|
||||
matched_cells += 1
|
||||
if (
|
||||
candidate_cell.row_index == expected_cell.row_index
|
||||
and candidate_cell.column_index == expected_cell.column_index
|
||||
):
|
||||
positioned_cells += 1
|
||||
if expected_cell.expected_field_code and field_codes.get(cell_id) == expected_cell.expected_field_code:
|
||||
correctly_mapped_fields += 1
|
||||
|
||||
return LayoutEvaluation(
|
||||
expected_tables=len(truth.tables),
|
||||
matched_tables=len(matched_tables),
|
||||
expected_cells=expected_cells,
|
||||
matched_cells=matched_cells,
|
||||
correctly_positioned_cells=positioned_cells,
|
||||
field_labeled_cells=field_labeled_cells,
|
||||
correctly_mapped_fields=correctly_mapped_fields,
|
||||
table_detection_recall=_ratio(len(matched_tables), len(truth.tables)),
|
||||
cell_detection_recall=_ratio(matched_cells, expected_cells),
|
||||
cell_position_accuracy=_ratio(positioned_cells, matched_cells),
|
||||
field_mapping_accuracy=(
|
||||
_ratio(correctly_mapped_fields, field_labeled_cells) if field_labeled_cells else None
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _best_unused_match(
|
||||
expected: LayoutBBox,
|
||||
candidates: list[tuple[str, LayoutBBox, object]],
|
||||
*,
|
||||
used: set[str],
|
||||
threshold: float,
|
||||
) -> tuple[str, object] | None:
|
||||
"""返回达到阈值且尚未使用的最高 IoU 候选,确保一对一评测。"""
|
||||
best: tuple[str, object] | None = None
|
||||
best_iou = threshold
|
||||
for candidate_id, bbox, value in candidates:
|
||||
if candidate_id in used:
|
||||
continue
|
||||
score = _bbox_iou(expected, bbox)
|
||||
if score >= best_iou:
|
||||
best = (candidate_id, value)
|
||||
best_iou = score
|
||||
return best
|
||||
|
||||
|
||||
def _bbox_iou(left: LayoutBBox, right: LayoutBBox) -> float:
|
||||
"""计算两个标准化矩形的交并比。"""
|
||||
x0 = max(left.x0, right.x0)
|
||||
y0 = max(left.y0, right.y0)
|
||||
x1 = min(left.x1, right.x1)
|
||||
y1 = min(left.y1, right.y1)
|
||||
intersection = max(0.0, x1 - x0) * max(0.0, y1 - y0)
|
||||
left_area = (left.x1 - left.x0) * (left.y1 - left.y0)
|
||||
right_area = (right.x1 - right.x0) * (right.y1 - right.y0)
|
||||
union = left_area + right_area - intersection
|
||||
return intersection / union if union > 0 else 0.0
|
||||
|
||||
|
||||
def _ratio(numerator: int, denominator: int) -> float:
|
||||
"""返回 0..1 比例;没有期望对象时按完全满足处理。"""
|
||||
return 1.0 if denominator == 0 else numerator / denominator
|
||||
|
||||
|
||||
def _validate_normalized_bbox(bbox: LayoutBBox, *, label: str) -> None:
|
||||
"""验证人工真值使用的坐标完整位于 0..1。"""
|
||||
if bbox.x1 > 1 or bbox.y1 > 1:
|
||||
raise ValueError(f'{label} normalized bbox must be within 0..1')
|
||||
|
||||
|
||||
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
|
||||
)
|
||||
@@ -0,0 +1,542 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/html_table.py
|
||||
|
||||
用途:把 MinerU/EML 的 HTML 表格恢复为稳定网格,并按冻结订单 Schema 精确映射列与字段候选。
|
||||
依赖:BeautifulSoup、Pydantic、order_schema.table_contract/field_rules、notice_line_values。
|
||||
逻辑:先展开 rowspan/colspan,再选择最高分表头;只接受冻结别名精确命中,未映射或歧义列保留诊断而不猜字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Literal
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.notice_line_values import parse_number
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import (
|
||||
TableHeaderContract,
|
||||
normalize_table_header,
|
||||
)
|
||||
|
||||
|
||||
class HtmlTableModel(BaseModel):
|
||||
"""为 HTML 网格和映射结果启用严格字段校验。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class HtmlGridCell(HtmlTableModel):
|
||||
"""表示 HTML 单元格在展开网格中的原点、跨度、文字和表头身份。"""
|
||||
|
||||
cell_id: str
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
row_span: int = Field(ge=1)
|
||||
column_span: int = Field(ge=1)
|
||||
text: str
|
||||
normalized_text: str
|
||||
is_header: bool
|
||||
|
||||
|
||||
class HtmlGridSlot(HtmlTableModel):
|
||||
"""表示网格坐标指向的原始单元格;合并格的多个 Slot 共享 cell_id。"""
|
||||
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
cell_id: str
|
||||
text: str
|
||||
normalized_text: str
|
||||
is_header: bool
|
||||
origin_row_index: int = Field(ge=0)
|
||||
origin_column_index: int = Field(ge=0)
|
||||
|
||||
|
||||
class HtmlGrid(HtmlTableModel):
|
||||
"""保存按行列展开后的矩形 HTML 表格和原始单元格集合。"""
|
||||
|
||||
row_count: int = Field(ge=1)
|
||||
column_count: int = Field(ge=1)
|
||||
rows: list[list[HtmlGridSlot | None]]
|
||||
cells: list[HtmlGridCell]
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_shape(self) -> 'HtmlGrid':
|
||||
"""确保网格是固定列数矩形,且所有 Slot 引用已知单元格。"""
|
||||
if len(self.rows) != self.row_count or any(len(row) != self.column_count for row in self.rows):
|
||||
raise ValueError('HTML grid shape is inconsistent')
|
||||
ids = {item.cell_id for item in self.cells}
|
||||
if len(ids) != len(self.cells):
|
||||
raise ValueError('HTML cell ids must be unique')
|
||||
if any(slot is not None and slot.cell_id not in ids for row in self.rows for slot in row):
|
||||
raise ValueError('HTML grid slot references unknown cell')
|
||||
return self
|
||||
|
||||
|
||||
class HtmlMappedField(HtmlTableModel):
|
||||
"""保存一项经冻结 Schema 校验的字段候选及其行列表格引用。"""
|
||||
|
||||
field_id: str
|
||||
field_code: str
|
||||
value: Any
|
||||
page_no: int = Field(ge=1)
|
||||
table_id: str
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
cell_id: str
|
||||
evidence_ref: str
|
||||
|
||||
|
||||
class HtmlMappedRow(HtmlTableModel):
|
||||
"""保存一条 HTML 数据行的字段候选和行级质量状态。"""
|
||||
|
||||
row_index: int = Field(ge=0)
|
||||
role: Literal['data', 'deleted', 'summary', 'empty', 'repeated_header']
|
||||
fields: list[HtmlMappedField] = Field(default_factory=list)
|
||||
complete_build_fields: bool = False
|
||||
complete_required_fields: bool = False
|
||||
missing_required_field_codes: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class HtmlColumnMapping(HtmlTableModel):
|
||||
"""记录一列的表头路径、唯一映射结果或未映射/歧义原因。"""
|
||||
|
||||
column_index: int = Field(ge=0)
|
||||
header_path: list[str]
|
||||
field_code: str | None = None
|
||||
field_id: str | None = None
|
||||
status: Literal['mapped', 'unmapped', 'ambiguous']
|
||||
candidates: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class HtmlTableMappingResult(HtmlTableModel):
|
||||
"""汇总表头选择、列映射、数据行候选和阻断问题。"""
|
||||
|
||||
page_no: int = Field(ge=1)
|
||||
table_id: str
|
||||
header_row_index: int | None = Field(default=None, ge=0)
|
||||
header_score: int = Field(ge=0)
|
||||
columns: list[HtmlColumnMapping]
|
||||
rows: list[HtmlMappedRow]
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
@property
|
||||
def mapped_field_codes(self) -> set[str]:
|
||||
"""返回本表唯一映射的字段编码集合。"""
|
||||
return {item.field_code for item in self.columns if item.field_code}
|
||||
|
||||
|
||||
def parse_html_grid(html: str, *, table_id: str) -> HtmlGrid:
|
||||
"""
|
||||
展开 HTML table 的 rowspan/colspan 为矩形网格。
|
||||
|
||||
Args:
|
||||
html: 必须包含 table/tr/td 或 th 的 MinerU/EML HTML。
|
||||
table_id: 当前文档内稳定表格标识,用于生成 cell_id。
|
||||
Returns:
|
||||
保留原始合并格身份的 HtmlGrid。
|
||||
Raises:
|
||||
ValidationError: HTML 无表格、跨度非法或单元格重叠。
|
||||
"""
|
||||
soup = BeautifulSoup(str(html or ''), 'html.parser')
|
||||
table = soup.find('table')
|
||||
if table is None:
|
||||
raise ValidationError(
|
||||
'HTML table is missing', code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
)
|
||||
raw_rows = [row for row in table.find_all('tr') if row.find_parent('table') is table]
|
||||
if not raw_rows:
|
||||
raise ValidationError(
|
||||
'HTML table has no rows', code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
)
|
||||
occupied: dict[tuple[int, int], HtmlGridSlot] = {}
|
||||
cells: list[HtmlGridCell] = []
|
||||
max_column = 0
|
||||
for row_index, row in enumerate(raw_rows):
|
||||
column_index = 0
|
||||
for element in row.find_all(['td', 'th'], recursive=False):
|
||||
while (row_index, column_index) in occupied:
|
||||
column_index += 1
|
||||
row_span = _positive_span(element.get('rowspan'))
|
||||
column_span = _positive_span(element.get('colspan'))
|
||||
text = ' '.join(element.get_text(' ', strip=True).split()).strip()
|
||||
normalized = normalize_table_header(text)
|
||||
cell_id = f'{table_id}:r{row_index}:c{column_index}'
|
||||
cell = HtmlGridCell(
|
||||
cell_id=cell_id,
|
||||
row_index=row_index,
|
||||
column_index=column_index,
|
||||
row_span=row_span,
|
||||
column_span=column_span,
|
||||
text=text,
|
||||
normalized_text=normalized,
|
||||
is_header=element.name.lower() == 'th',
|
||||
)
|
||||
cells.append(cell)
|
||||
for target_row in range(row_index, row_index + row_span):
|
||||
for target_column in range(column_index, column_index + column_span):
|
||||
position = (target_row, target_column)
|
||||
if position in occupied:
|
||||
raise ValidationError(
|
||||
'HTML table cells overlap',
|
||||
code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
)
|
||||
occupied[position] = HtmlGridSlot(
|
||||
row_index=target_row,
|
||||
column_index=target_column,
|
||||
cell_id=cell_id,
|
||||
text=text,
|
||||
normalized_text=normalized,
|
||||
is_header=cell.is_header,
|
||||
origin_row_index=row_index,
|
||||
origin_column_index=column_index,
|
||||
)
|
||||
max_column = max(max_column, target_column + 1)
|
||||
column_index += column_span
|
||||
row_count = max((position[0] for position in occupied), default=-1) + 1
|
||||
if row_count < 1 or max_column < 1:
|
||||
raise ValidationError(
|
||||
'HTML table grid is empty', code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
)
|
||||
rows = [
|
||||
[occupied.get((row_index, column_index)) for column_index in range(max_column)]
|
||||
for row_index in range(row_count)
|
||||
]
|
||||
return HtmlGrid(row_count=row_count, column_count=max_column, rows=rows, cells=cells)
|
||||
|
||||
|
||||
def map_html_table_to_schema(
|
||||
html: str,
|
||||
*,
|
||||
page_no: int,
|
||||
table_id: str,
|
||||
contract: TableHeaderContract,
|
||||
) -> HtmlTableMappingResult:
|
||||
"""
|
||||
按冻结 Schema 精确映射 HTML 表格列并生成类型化行字段候选。
|
||||
|
||||
Args:
|
||||
html: MinerU 或 EML 解析出的 HTML table。
|
||||
page_no: 1-based 来源页码。
|
||||
table_id: 当前 Document 内稳定表格标识。
|
||||
contract: Run 锁定 Schema 编译出的表头契约。
|
||||
Returns:
|
||||
包含列诊断、有效/删除/汇总行和 evidence_ref 的映射结果。
|
||||
"""
|
||||
grid = parse_html_grid(html, table_id=table_id)
|
||||
header_index, score = _select_header_row(grid, contract)
|
||||
if header_index is None:
|
||||
return HtmlTableMappingResult(
|
||||
page_no=page_no,
|
||||
table_id=table_id,
|
||||
header_row_index=None,
|
||||
header_score=0,
|
||||
columns=[
|
||||
HtmlColumnMapping(
|
||||
column_index=index, header_path=[], status='unmapped', candidates=[],
|
||||
)
|
||||
for index in range(grid.column_count)
|
||||
],
|
||||
rows=[],
|
||||
issues=['html_table_header_not_mapped'],
|
||||
)
|
||||
columns, duplicate_codes = _map_columns(
|
||||
grid, header_index=header_index, contract=contract,
|
||||
)
|
||||
issues: list[str] = []
|
||||
if any(item.status == 'ambiguous' for item in columns):
|
||||
issues.append('html_table_columns_ambiguous')
|
||||
if duplicate_codes:
|
||||
issues.append('html_table_duplicate_field_columns')
|
||||
if _header_contains_appended_numeric_value(
|
||||
grid, header_index=header_index, contract=contract,
|
||||
):
|
||||
issues.append('html_table_header_value_contamination')
|
||||
mapped_rows = [
|
||||
_map_data_row(
|
||||
grid,
|
||||
row_index=row_index,
|
||||
header_index=header_index,
|
||||
columns=columns,
|
||||
page_no=page_no,
|
||||
table_id=table_id,
|
||||
contract=contract,
|
||||
)
|
||||
for row_index in range(grid.row_count)
|
||||
if row_index > header_index
|
||||
]
|
||||
required_codes = {
|
||||
code for code, config in contract.fields_by_code.items()
|
||||
if config.get('scope') == 'line' and config.get('required')
|
||||
}
|
||||
build_codes = {'part_number', 'qty'}
|
||||
for row in mapped_rows:
|
||||
present = {field.field_code for field in row.fields}
|
||||
row.complete_build_fields = row.role == 'data' and build_codes.issubset(present)
|
||||
row.complete_required_fields = row.role == 'data' and required_codes.issubset(present)
|
||||
row.missing_required_field_codes = (
|
||||
sorted(required_codes - present) if row.role == 'data' else []
|
||||
)
|
||||
return HtmlTableMappingResult(
|
||||
page_no=page_no,
|
||||
table_id=table_id,
|
||||
header_row_index=header_index,
|
||||
header_score=score,
|
||||
columns=columns,
|
||||
rows=mapped_rows,
|
||||
issues=issues,
|
||||
)
|
||||
|
||||
|
||||
def _select_header_row(grid: HtmlGrid, contract: TableHeaderContract) -> tuple[int | None, int]:
|
||||
"""扫描整张表选择冻结别名命中最多的表头,支持表头后置但不按位置猜测。"""
|
||||
best_index: int | None = None
|
||||
best_score = 0
|
||||
for row_index in range(grid.row_count):
|
||||
codes: set[str] = set()
|
||||
for column_index in range(grid.column_count):
|
||||
candidates = _header_candidates(grid, row_index=row_index, column_index=column_index)
|
||||
codes.update(
|
||||
contract.header_to_field[item]
|
||||
for item in candidates
|
||||
if item in contract.header_to_field
|
||||
)
|
||||
score = len(codes) * 10
|
||||
if 'part_number' in codes and 'qty' in codes:
|
||||
score += 30
|
||||
if 'reservation_id' in codes:
|
||||
score += 10
|
||||
if {'unit_price', 'amount'} & codes:
|
||||
score += 5
|
||||
if score > best_score:
|
||||
best_index = row_index
|
||||
best_score = score
|
||||
return best_index, best_score
|
||||
|
||||
|
||||
def _map_columns(
|
||||
grid: HtmlGrid, *, header_index: int, contract: TableHeaderContract,
|
||||
) -> tuple[list[HtmlColumnMapping], set[str]]:
|
||||
"""按每列多层表头候选精确匹配字段;多字段命中时显式标记歧义。"""
|
||||
result: list[HtmlColumnMapping] = []
|
||||
for column_index in range(grid.column_count):
|
||||
paths = _header_candidates(grid, row_index=header_index, column_index=column_index)
|
||||
codes = sorted({contract.header_to_field[item] for item in paths if item in contract.header_to_field})
|
||||
if len(codes) == 1:
|
||||
code = codes[0]
|
||||
config = contract.fields_by_code[code]
|
||||
result.append(HtmlColumnMapping(
|
||||
column_index=column_index,
|
||||
header_path=_header_display_path(grid, header_index, column_index),
|
||||
field_code=code,
|
||||
field_id=str(config.get('field_id') or ''),
|
||||
status='mapped',
|
||||
candidates=codes,
|
||||
))
|
||||
else:
|
||||
result.append(HtmlColumnMapping(
|
||||
column_index=column_index,
|
||||
header_path=_header_display_path(grid, header_index, column_index),
|
||||
status='ambiguous' if codes else 'unmapped',
|
||||
candidates=codes,
|
||||
))
|
||||
counts: dict[str, int] = {}
|
||||
for item in result:
|
||||
if item.status == 'mapped' and item.field_code:
|
||||
counts[item.field_code] = counts.get(item.field_code, 0) + 1
|
||||
duplicate_codes = {code for code, count in counts.items() if count > 1}
|
||||
if not duplicate_codes:
|
||||
return result, set()
|
||||
blocked = [
|
||||
item.model_copy(update={
|
||||
'field_code': None,
|
||||
'field_id': None,
|
||||
'status': 'ambiguous',
|
||||
'candidates': [item.field_code],
|
||||
})
|
||||
if item.field_code in duplicate_codes else item
|
||||
for item in result
|
||||
]
|
||||
return blocked, duplicate_codes
|
||||
|
||||
|
||||
def _map_data_row(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
row_index: int,
|
||||
header_index: int,
|
||||
columns: list[HtmlColumnMapping],
|
||||
page_no: int,
|
||||
table_id: str,
|
||||
contract: TableHeaderContract,
|
||||
) -> HtmlMappedRow:
|
||||
"""将非表头行按唯一映射列转换为字段候选,并识别空/删除/合计/重复表头。"""
|
||||
row = grid.rows[row_index]
|
||||
texts = [slot.text.strip() if slot is not None else '' for slot in row]
|
||||
normalized = [normalize_table_header(item) for item in texts if item]
|
||||
if not normalized:
|
||||
return HtmlMappedRow(row_index=row_index, role='empty')
|
||||
if _is_repeated_header(grid, row_index=row_index, columns=columns, contract=contract):
|
||||
return HtmlMappedRow(row_index=row_index, role='repeated_header')
|
||||
joined = ' '.join(normalized)
|
||||
if 'item deleted' in joined or 'deleted item' in joined or '项目已删除' in joined or '項目已刪除' in joined:
|
||||
return HtmlMappedRow(row_index=row_index, role='deleted')
|
||||
first = next((item for item in normalized if item), '')
|
||||
if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first):
|
||||
return HtmlMappedRow(row_index=row_index, role='summary')
|
||||
if _has_explicit_zero_quantity(row, columns=columns):
|
||||
return HtmlMappedRow(row_index=row_index, role='deleted')
|
||||
fields: list[HtmlMappedField] = []
|
||||
seen_codes: set[str] = set()
|
||||
for column in columns:
|
||||
if column.status != 'mapped' or not column.field_code or column.field_code in seen_codes:
|
||||
continue
|
||||
slot = row[column.column_index]
|
||||
if slot is None or not slot.text.strip():
|
||||
continue
|
||||
config = contract.fields_by_code.get(column.field_code)
|
||||
value = _normalize_html_value(slot.text, config)
|
||||
if value is None:
|
||||
continue
|
||||
seen_codes.add(column.field_code)
|
||||
fields.append(HtmlMappedField(
|
||||
field_id=str(config.get('field_id') or ''),
|
||||
field_code=column.field_code,
|
||||
value=value.isoformat() if hasattr(value, 'isoformat') else value,
|
||||
page_no=page_no,
|
||||
table_id=table_id,
|
||||
row_index=row_index,
|
||||
column_index=column.column_index,
|
||||
cell_id=slot.cell_id,
|
||||
evidence_ref=f'doc:p{page_no}:{table_id}:r{row_index}:c{column.column_index}',
|
||||
))
|
||||
return HtmlMappedRow(row_index=row_index, role='data', fields=fields)
|
||||
|
||||
|
||||
def _normalize_html_value(raw: str, config: dict[str, Any] | None) -> Any:
|
||||
"""按冻结字段类型、normalizer 和 validator 转换 HTML 单元格;非法值留空不跨列补偿。"""
|
||||
if config is None:
|
||||
return None
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
candidate: Any = raw
|
||||
if value_type in {'decimal', 'integer'}:
|
||||
candidate = parse_number(raw)
|
||||
if candidate is None:
|
||||
return None
|
||||
if value_type == 'integer':
|
||||
if not float(candidate).is_integer():
|
||||
return None
|
||||
candidate = int(candidate)
|
||||
try:
|
||||
value = normalize_order_field_value(candidate, config)
|
||||
return value if value is not None and validate_order_field_value(value, config) else None
|
||||
except (ValidationError, ArithmeticError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _has_explicit_zero_quantity(
|
||||
row: list[HtmlGridSlot | None], *, columns: list[HtmlColumnMapping],
|
||||
) -> bool:
|
||||
"""识别冻结 Qty 列中明确数值 0;仅零值删除,负数/空值/非法值继续走质量复核。"""
|
||||
qty_column = next(
|
||||
(
|
||||
column for column in columns
|
||||
if column.status == 'mapped' and column.field_code == 'qty'
|
||||
),
|
||||
None,
|
||||
)
|
||||
if qty_column is None:
|
||||
return False
|
||||
slot = row[qty_column.column_index]
|
||||
if slot is None or not slot.text.strip():
|
||||
return False
|
||||
value = parse_number(slot.text)
|
||||
return value is not None and value == 0
|
||||
|
||||
|
||||
def _header_candidates(grid: HtmlGrid, *, row_index: int, column_index: int) -> list[str]:
|
||||
"""生成叶表头、上层合并表头和组合路径的标准化候选,保持精确匹配。"""
|
||||
displays = _header_display_path(grid, row_index, column_index)
|
||||
normalized = [normalize_table_header(item) for item in displays if normalize_table_header(item)]
|
||||
candidates: list[str] = []
|
||||
for item in reversed(normalized):
|
||||
if item not in candidates:
|
||||
candidates.append(item)
|
||||
for start in range(len(normalized)):
|
||||
joined = normalize_table_header(' '.join(normalized[start:]))
|
||||
if joined and joined not in candidates:
|
||||
candidates.append(joined)
|
||||
return candidates
|
||||
|
||||
|
||||
def _header_display_path(grid: HtmlGrid, row_index: int, column_index: int) -> list[str]:
|
||||
"""收集当前表头行及其上方相同列的去重显示路径。"""
|
||||
path: list[str] = []
|
||||
seen_cells: set[str] = set()
|
||||
for index in range(row_index + 1):
|
||||
slot = grid.rows[index][column_index]
|
||||
if slot is None or slot.cell_id in seen_cells or not slot.text.strip():
|
||||
continue
|
||||
seen_cells.add(slot.cell_id)
|
||||
path.append(slot.text.strip())
|
||||
return path
|
||||
|
||||
|
||||
def _is_repeated_header(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
row_index: int,
|
||||
columns: list[HtmlColumnMapping],
|
||||
contract: TableHeaderContract,
|
||||
) -> bool:
|
||||
"""判断数据区是否重复出现同一组已映射表头。"""
|
||||
hits = 0
|
||||
expected = 0
|
||||
for column in columns:
|
||||
if column.status != 'mapped' or not column.field_code:
|
||||
continue
|
||||
expected += 1
|
||||
slot = grid.rows[row_index][column.column_index]
|
||||
if slot and contract.header_to_field.get(slot.normalized_text) == column.field_code:
|
||||
hits += 1
|
||||
return expected >= 2 and hits == expected
|
||||
|
||||
|
||||
def _header_contains_appended_numeric_value(
|
||||
grid: HtmlGrid, *, header_index: int, contract: TableHeaderContract,
|
||||
) -> bool:
|
||||
"""检测已知精确表头后拼接纯数字首值的解析污染,不尝试修剪或映射该单元格。"""
|
||||
for slot in grid.rows[header_index]:
|
||||
if slot is None or not slot.normalized_text or slot.normalized_text in contract.header_to_field:
|
||||
continue
|
||||
for header in contract.header_to_field:
|
||||
prefix = f'{header} '
|
||||
if not slot.normalized_text.startswith(prefix):
|
||||
continue
|
||||
suffix = slot.normalized_text[len(prefix):].strip()
|
||||
if suffix and re.fullmatch(r'\d+(?:\s+\d+)*', suffix):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _positive_span(value: Any) -> int:
|
||||
"""读取 rowspan/colspan,空值为 1,零或非法跨度拒绝。"""
|
||||
if value in (None, ''):
|
||||
return 1
|
||||
try:
|
||||
span = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'HTML table span is invalid', code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
) from exc
|
||||
if span < 1 or span > 1000:
|
||||
raise ValidationError(
|
||||
'HTML table span is invalid', code='SHIPPING_NOTICE.LAYOUT_HTML_TABLE_INVALID',
|
||||
)
|
||||
return span
|
||||
@@ -0,0 +1,627 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/mineru.py
|
||||
|
||||
用途:安全调用独立 MinerU 服务,并把嵌套 JSON/HTML 解析为不冒充最终证据的版面候选与能力报告。
|
||||
依赖:requests、BeautifulSoup、Pydantic、统一 AppError。
|
||||
逻辑:调用方提交受支持附件;本模块限制请求/响应大小、解包 MinerU 字符串 JSON,并在缺少单元格坐标时阻止转换为确定性证据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
|
||||
|
||||
MINERU_SUPPORTED_EXTENSIONS = frozenset({
|
||||
'.doc', '.docx', '.jpeg', '.jpg', '.pdf', '.png', '.ppt', '.pptx',
|
||||
})
|
||||
MINERU_JSON_FIELDS = ('middle_json', 'model_output', 'content_list')
|
||||
MINERU_CONTENT_COORDINATE_SCALE = 1000.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MinerUClientConfig:
|
||||
"""保存受控 MinerU 连接和资源上限;凭据不属于当前无认证协议。"""
|
||||
|
||||
base_url: str
|
||||
backend: str = 'pipeline'
|
||||
parse_method: str = 'auto'
|
||||
languages: tuple[str, ...] = ('ch',)
|
||||
connect_timeout_seconds: int = 10
|
||||
read_timeout_seconds: int = 300
|
||||
max_upload_bytes: int = 30 * 1024 * 1024
|
||||
max_response_bytes: int = 20 * 1024 * 1024
|
||||
|
||||
def validated_base_url(self) -> str:
|
||||
"""校验受信配置 URL,不允许凭据、query 或 fragment 混入服务地址。"""
|
||||
value = str(self.base_url or '').strip().rstrip('/')
|
||||
parsed = urlparse(value)
|
||||
if (
|
||||
parsed.scheme not in {'http', 'https'} or not parsed.netloc
|
||||
or parsed.username or parsed.password or parsed.query or parsed.fragment
|
||||
):
|
||||
raise ValidationError(
|
||||
'MinerU base URL is invalid',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_CONFIG_INVALID',
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
class MinerUModel(BaseModel):
|
||||
"""为 MinerU 候选结构启用严格字段校验,避免服务升级静默污染下游。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class MinerUTableCandidate(MinerUModel):
|
||||
"""保存 MinerU 表格 HTML 和整表坐标;没有单元格坐标时不得转成最终 LayoutTable。"""
|
||||
|
||||
candidate_id: str
|
||||
page_no: int = Field(ge=1)
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
html: str
|
||||
row_count: int = Field(ge=0)
|
||||
cell_count: int = Field(ge=0)
|
||||
has_rowspan: bool
|
||||
has_colspan: bool
|
||||
cell_coordinates_available: bool = False
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_normalized_bbox(self) -> 'MinerUTableCandidate':
|
||||
"""拒绝超出 0..1 的表格坐标,避免错误页面尺寸制造伪几何。"""
|
||||
if self.normalized_bbox.x1 > 1 or self.normalized_bbox.y1 > 1:
|
||||
raise ValueError('MinerU table normalized_bbox must be within 0..1')
|
||||
return self
|
||||
|
||||
|
||||
class MinerUTextCandidate(MinerUModel):
|
||||
"""保存页内非表格文本块及其 bbox,供后续非结构化抽取和表格坐标对齐。"""
|
||||
|
||||
candidate_id: str
|
||||
page_no: int = Field(ge=1)
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
text: str
|
||||
content_type: str
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_normalized_bbox(self) -> 'MinerUTextCandidate':
|
||||
"""要求文本块标准化坐标位于 0..1。"""
|
||||
if self.normalized_bbox.x1 > 1 or self.normalized_bbox.y1 > 1:
|
||||
raise ValueError('MinerU text normalized_bbox must be within 0..1')
|
||||
return self
|
||||
|
||||
|
||||
class MinerUPageCandidate(MinerUModel):
|
||||
"""保存一页尺寸及其去重后的表格候选。"""
|
||||
|
||||
page_no: int = Field(ge=1)
|
||||
width: float = Field(gt=0)
|
||||
height: float = Field(gt=0)
|
||||
text_blocks: list[MinerUTextCandidate] = Field(default_factory=list)
|
||||
tables: list[MinerUTableCandidate] = Field(default_factory=list)
|
||||
|
||||
|
||||
class MinerUCapabilityReport(MinerUModel):
|
||||
"""记录 MinerU 输出能否满足页级、表级和单元格级证据要求。"""
|
||||
|
||||
provider_version: str | None = None
|
||||
backend: str | None = None
|
||||
page_count: int = Field(ge=0)
|
||||
page_size_count: int = Field(ge=0)
|
||||
bbox_object_count: int = Field(ge=0)
|
||||
html_table_count: int = Field(ge=0)
|
||||
html_row_count: int = Field(ge=0)
|
||||
html_cell_count: int = Field(ge=0)
|
||||
text_block_count: int = Field(ge=0)
|
||||
cell_bbox_count: int = Field(ge=0)
|
||||
has_page_coordinates: bool
|
||||
has_table_structure: bool
|
||||
has_cell_coordinates: bool
|
||||
deterministic_cell_evidence_ready: bool
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_readiness(self) -> 'MinerUCapabilityReport':
|
||||
"""确定性单元格证据必须同时具备页坐标、表格结构和单元格坐标。"""
|
||||
expected = self.has_page_coordinates and self.has_table_structure and self.has_cell_coordinates
|
||||
if self.deterministic_cell_evidence_ready != expected:
|
||||
raise ValueError('deterministic evidence readiness is inconsistent with capabilities')
|
||||
return self
|
||||
|
||||
|
||||
class MinerUParseCandidate(MinerUModel):
|
||||
"""保存 MinerU 的非最终候选;业务层只能在能力报告准入后转换为 LayoutDocument。"""
|
||||
|
||||
task_id: str | None = None
|
||||
provider_version: str | None = None
|
||||
backend: str | None = None
|
||||
pages: list[MinerUPageCandidate]
|
||||
capability: MinerUCapabilityReport
|
||||
|
||||
|
||||
class MinerUClient:
|
||||
"""同步调用 MinerU `/file_parse`,供 L0 评测和后续异步适配器复用纯解析逻辑。"""
|
||||
|
||||
def __init__(self, config: MinerUClientConfig, *, session: requests.Session | None = None):
|
||||
"""保存已验证配置和可注入 Session,测试不得访问真实服务。"""
|
||||
self.config = config
|
||||
self.base_url = config.validated_base_url()
|
||||
self.session = session or requests.Session()
|
||||
|
||||
def parse_file(self, *, filename: str, content: bytes) -> dict[str, Any]:
|
||||
"""
|
||||
同步提交单个受支持文件并返回已校验 JSON,不记录文件名或正文。
|
||||
|
||||
Args:
|
||||
filename: 仅用于扩展名和 multipart;不得进入异常 details 或日志。
|
||||
content: 文件原始字节,受 max_upload_bytes 限制。
|
||||
Returns:
|
||||
MinerU 顶层任务结果字典。
|
||||
Raises:
|
||||
ValidationError: 文件类型、大小、终态或响应契约不合法。
|
||||
ServiceUnavailableError: 网络、超时、5xx 或响应超限。
|
||||
"""
|
||||
extension = Path(str(filename or '')).suffix.lower()
|
||||
if extension not in MINERU_SUPPORTED_EXTENSIONS:
|
||||
raise ValidationError(
|
||||
'MinerU file type is unsupported',
|
||||
code='SHIPPING_NOTICE.LAYOUT_FILE_TYPE_UNSUPPORTED',
|
||||
details={'extension': extension},
|
||||
)
|
||||
if not content:
|
||||
raise ValidationError(
|
||||
'MinerU input file is empty',
|
||||
code='SHIPPING_NOTICE.LAYOUT_FILE_EMPTY',
|
||||
)
|
||||
if len(content) > self.config.max_upload_bytes:
|
||||
raise ValidationError(
|
||||
'MinerU input file exceeds size limit',
|
||||
code='SHIPPING_NOTICE.LAYOUT_FILE_TOO_LARGE',
|
||||
details={'max_bytes': self.config.max_upload_bytes},
|
||||
)
|
||||
|
||||
data = [
|
||||
('backend', self.config.backend),
|
||||
('parse_method', self.config.parse_method),
|
||||
('formula_enable', 'false'),
|
||||
('table_enable', 'true'),
|
||||
('image_analysis', 'false'),
|
||||
('return_md', 'false'),
|
||||
('return_middle_json', 'true'),
|
||||
('return_model_output', 'true'),
|
||||
('return_content_list', 'true'),
|
||||
('return_images', 'false'),
|
||||
('response_format_zip', 'false'),
|
||||
]
|
||||
data.extend(('lang_list', item) for item in self.config.languages)
|
||||
try:
|
||||
response = self.session.post(
|
||||
f'{self.base_url}/file_parse',
|
||||
files=[('files', (filename, content, _mime_type(extension)))],
|
||||
data=data,
|
||||
stream=True,
|
||||
timeout=(self.config.connect_timeout_seconds, self.config.read_timeout_seconds),
|
||||
)
|
||||
except requests.exceptions.RequestException as exc:
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU request failed',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
|
||||
) from exc
|
||||
|
||||
raw = _read_limited_response(response, max_bytes=self.config.max_response_bytes)
|
||||
try:
|
||||
payload = json.loads(raw.decode(response.encoding or 'utf-8'))
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise ValidationError(
|
||||
'MinerU response is not valid JSON',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
) from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError(
|
||||
'MinerU response must be an object',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
if response.status_code >= 500:
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU service failed',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
|
||||
details={'status': response.status_code},
|
||||
)
|
||||
if response.status_code >= 400 or str(payload.get('status') or '').lower() != 'completed':
|
||||
raise ValidationError(
|
||||
'MinerU parse task failed',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_PARSE_FAILED',
|
||||
details={
|
||||
'status': response.status_code,
|
||||
'backend': str(payload.get('backend') or ''),
|
||||
'provider_error_code': _provider_error_code(payload.get('error')),
|
||||
},
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def parse_mineru_candidate(payload: dict[str, Any]) -> MinerUParseCandidate:
|
||||
"""
|
||||
解包 MinerU 结果并提取页尺寸、HTML 表格、整表坐标和能力报告。
|
||||
|
||||
Args:
|
||||
payload: `/file_parse` 或异步结果接口返回的完整对象。
|
||||
Returns:
|
||||
不含伪造单元格坐标的 MinerUParseCandidate。
|
||||
Raises:
|
||||
ValidationError: 顶层、results 或嵌套 JSON 结构不合法。
|
||||
"""
|
||||
if not isinstance(payload, dict) or str(payload.get('status') or '').lower() != 'completed':
|
||||
raise ValidationError(
|
||||
'MinerU result is not completed',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
results = payload.get('results')
|
||||
if not isinstance(results, dict) or len(results) != 1:
|
||||
raise ValidationError(
|
||||
'MinerU result must contain exactly one file',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
result = next(iter(results.values()))
|
||||
if not isinstance(result, dict):
|
||||
raise ValidationError(
|
||||
'MinerU file result must be an object',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
decoded = {field: _decode_json_field(result.get(field), field=field) for field in MINERU_JSON_FIELDS}
|
||||
page_sizes = _page_sizes(decoded['middle_json'], decoded['model_output'])
|
||||
tables = _table_candidates(decoded['content_list'], page_sizes=page_sizes)
|
||||
text_blocks = _text_candidates(decoded['content_list'], page_sizes=page_sizes)
|
||||
pages = [
|
||||
MinerUPageCandidate(
|
||||
page_no=page_no,
|
||||
width=size[0],
|
||||
height=size[1],
|
||||
text_blocks=[item for item in text_blocks if item.page_no == page_no],
|
||||
tables=[item for item in tables if item.page_no == page_no],
|
||||
)
|
||||
for page_no, size in sorted(page_sizes.items())
|
||||
]
|
||||
report = inspect_mineru_capabilities(
|
||||
payload,
|
||||
decoded=decoded,
|
||||
pages=pages,
|
||||
)
|
||||
return MinerUParseCandidate(
|
||||
task_id=str(payload.get('task_id') or '') or None,
|
||||
provider_version=str(payload.get('version') or '') or None,
|
||||
backend=str(payload.get('backend') or '') or None,
|
||||
pages=pages,
|
||||
capability=report,
|
||||
)
|
||||
|
||||
|
||||
def inspect_mineru_capabilities(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
decoded: dict[str, Any] | None = None,
|
||||
pages: list[MinerUPageCandidate] | None = None,
|
||||
) -> MinerUCapabilityReport:
|
||||
"""
|
||||
审计 MinerU 是否具备页级、表级和单元格级坐标证据。
|
||||
|
||||
Args:
|
||||
payload: 完整 MinerU 任务结果。
|
||||
decoded: 可复用的嵌套 JSON,避免重复解码。
|
||||
pages: 可复用的候选页面。
|
||||
Returns:
|
||||
明确 deterministic_cell_evidence_ready 的能力报告。
|
||||
"""
|
||||
if decoded is None or pages is None:
|
||||
candidate = parse_mineru_candidate(payload)
|
||||
return candidate.capability
|
||||
bbox_count = 0
|
||||
cell_bbox_count = 0
|
||||
for value in decoded.values():
|
||||
for item in _walk_dicts(value):
|
||||
if _valid_raw_bbox(item.get('bbox')):
|
||||
bbox_count += 1
|
||||
if _is_cell_coordinate_object(item):
|
||||
cell_bbox_count += 1
|
||||
table_count = sum(len(page.tables) for page in pages)
|
||||
row_count = sum(item.row_count for page in pages for item in page.tables)
|
||||
cell_count = sum(item.cell_count for page in pages for item in page.tables)
|
||||
text_block_count = sum(len(page.text_blocks) for page in pages)
|
||||
has_pages = bool(pages) and all(page.width > 0 and page.height > 0 for page in pages)
|
||||
has_tables = table_count > 0 and row_count > 0 and cell_count > 0
|
||||
has_cells = cell_count > 0 and cell_bbox_count >= cell_count
|
||||
issues: list[str] = []
|
||||
if not has_pages:
|
||||
issues.append('mineru_page_coordinates_missing')
|
||||
if not has_tables:
|
||||
issues.append('mineru_table_structure_missing')
|
||||
if not has_cells:
|
||||
issues.append(
|
||||
'mineru_cell_coordinates_missing'
|
||||
if cell_bbox_count == 0 else 'mineru_cell_coordinates_incomplete'
|
||||
)
|
||||
return MinerUCapabilityReport(
|
||||
provider_version=str(payload.get('version') or '') or None,
|
||||
backend=str(payload.get('backend') or '') or None,
|
||||
page_count=len(pages),
|
||||
page_size_count=sum(1 for page in pages if page.width > 0 and page.height > 0),
|
||||
bbox_object_count=bbox_count,
|
||||
html_table_count=table_count,
|
||||
html_row_count=row_count,
|
||||
html_cell_count=cell_count,
|
||||
text_block_count=text_block_count,
|
||||
cell_bbox_count=cell_bbox_count,
|
||||
has_page_coordinates=has_pages,
|
||||
has_table_structure=has_tables,
|
||||
has_cell_coordinates=has_cells,
|
||||
deterministic_cell_evidence_ready=has_pages and has_tables and has_cells,
|
||||
issues=issues,
|
||||
)
|
||||
|
||||
|
||||
def _read_limited_response(response: requests.Response, *, max_bytes: int) -> bytes:
|
||||
"""按流读取 MinerU 响应并在超过上限时终止,避免大 JSON/ZIP 耗尽 Worker 内存。"""
|
||||
try:
|
||||
content_length = int(response.headers.get('Content-Length') or 0)
|
||||
except (TypeError, ValueError):
|
||||
content_length = 0
|
||||
if content_length > max_bytes:
|
||||
response.close()
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU response exceeds size limit',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_RESPONSE_TOO_LARGE',
|
||||
details={'max_bytes': max_bytes},
|
||||
)
|
||||
chunks: list[bytes] = []
|
||||
size = 0
|
||||
try:
|
||||
for chunk in response.iter_content(chunk_size=64 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
raise ServiceUnavailableError(
|
||||
'MinerU response exceeds size limit',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_RESPONSE_TOO_LARGE',
|
||||
details={'max_bytes': max_bytes},
|
||||
)
|
||||
chunks.append(chunk)
|
||||
finally:
|
||||
response.close()
|
||||
return b''.join(chunks)
|
||||
|
||||
|
||||
def _decode_json_field(value: Any, *, field: str) -> Any:
|
||||
"""解包 MinerU 将 middle/model/content JSON 作为字符串返回的协议形式。"""
|
||||
parsed = value
|
||||
for _ in range(2):
|
||||
if not isinstance(parsed, str):
|
||||
break
|
||||
try:
|
||||
parsed = json.loads(parsed)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError(
|
||||
f'MinerU {field} is not valid JSON',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
) from exc
|
||||
if not isinstance(parsed, (dict, list)):
|
||||
raise ValidationError(
|
||||
f'MinerU {field} has invalid type',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
return parsed
|
||||
|
||||
|
||||
def _page_sizes(middle_json: Any, model_output: Any) -> dict[int, tuple[float, float]]:
|
||||
"""从 middle_json 优先、model_output 次优读取 1-based 页码与页面宽高。"""
|
||||
result: dict[int, tuple[float, float]] = {}
|
||||
if isinstance(middle_json, dict):
|
||||
pdf_info = middle_json.get('pdf_info')
|
||||
if isinstance(pdf_info, list):
|
||||
for position, page in enumerate(pdf_info):
|
||||
if not isinstance(page, dict):
|
||||
continue
|
||||
size = page.get('page_size')
|
||||
if isinstance(size, (list, tuple)) and len(size) >= 2:
|
||||
_add_page_size(result, position + 1, size[0], size[1])
|
||||
if isinstance(model_output, list):
|
||||
for position, page in enumerate(model_output):
|
||||
if not isinstance(page, dict):
|
||||
continue
|
||||
info = page.get('page_info') if isinstance(page.get('page_info'), dict) else page
|
||||
page_no = _as_int(info.get('page_no'), default=position) + 1
|
||||
_add_page_size(result, page_no, info.get('width'), info.get('height'))
|
||||
return result
|
||||
|
||||
|
||||
def _table_candidates(content_list: Any, *, page_sizes: dict[int, tuple[float, float]]) -> list[MinerUTableCandidate]:
|
||||
"""从 content_list 提取 HTML 表格,并将 MinerU 0..1000 画布坐标映射到 PDF 页面。"""
|
||||
result: list[MinerUTableCandidate] = []
|
||||
seen: set[str] = set()
|
||||
for item in _walk_dicts(content_list):
|
||||
if str(item.get('type') or '').lower() != 'table':
|
||||
continue
|
||||
html = item.get('table_body') or item.get('html')
|
||||
bbox = item.get('bbox')
|
||||
if not isinstance(html, str) or not html.strip() or not _valid_raw_bbox(bbox):
|
||||
continue
|
||||
page_no = _as_int(item.get('page_idx'), default=0) + 1
|
||||
size = page_sizes.get(page_no)
|
||||
if size is None:
|
||||
continue
|
||||
raw_bbox, normalized = _content_bbox_to_page(bbox, page_size=size)
|
||||
soup = BeautifulSoup(html, 'html.parser')
|
||||
row_count = len(soup.find_all('tr'))
|
||||
cell_count = len(soup.find_all(['td', 'th']))
|
||||
fingerprint = hashlib.sha256(
|
||||
f'{page_no}|{bbox}|{html}'.encode('utf-8'),
|
||||
).hexdigest()[:16]
|
||||
if fingerprint in seen:
|
||||
continue
|
||||
seen.add(fingerprint)
|
||||
result.append(MinerUTableCandidate(
|
||||
candidate_id=f'mineru-table-{fingerprint}',
|
||||
page_no=page_no,
|
||||
bbox=raw_bbox,
|
||||
normalized_bbox=normalized,
|
||||
html=html,
|
||||
row_count=row_count,
|
||||
cell_count=cell_count,
|
||||
has_rowspan=bool(soup.find(attrs={'rowspan': True})),
|
||||
has_colspan=bool(soup.find(attrs={'colspan': True})),
|
||||
cell_coordinates_available=False,
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def _text_candidates(content_list: Any, *, page_sizes: dict[int, tuple[float, float]]) -> list[MinerUTextCandidate]:
|
||||
"""提取非表格文本块,并将 MinerU 0..1000 画布坐标映射到 PDF 页面。"""
|
||||
result: list[MinerUTextCandidate] = []
|
||||
seen: set[str] = set()
|
||||
for item in _walk_dicts(content_list):
|
||||
content_type = str(item.get('type') or '').lower()
|
||||
if content_type == 'table':
|
||||
continue
|
||||
text = item.get('text')
|
||||
bbox = item.get('bbox')
|
||||
if not isinstance(text, str) or not text.strip() or not _valid_raw_bbox(bbox):
|
||||
continue
|
||||
page_no = _as_int(item.get('page_idx'), default=0) + 1
|
||||
size = page_sizes.get(page_no)
|
||||
if size is None:
|
||||
continue
|
||||
raw_bbox, normalized = _content_bbox_to_page(bbox, page_size=size)
|
||||
fingerprint = hashlib.sha256(
|
||||
f'{page_no}|{bbox}|{content_type}|{text}'.encode('utf-8'),
|
||||
).hexdigest()[:16]
|
||||
if fingerprint in seen:
|
||||
continue
|
||||
seen.add(fingerprint)
|
||||
result.append(MinerUTextCandidate(
|
||||
candidate_id=f'mineru-text-{fingerprint}',
|
||||
page_no=page_no,
|
||||
bbox=raw_bbox,
|
||||
normalized_bbox=normalized,
|
||||
text=text,
|
||||
content_type=content_type or 'text',
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def _walk_dicts(value: Any) -> Iterable[dict[str, Any]]:
|
||||
"""深度优先遍历嵌套 MinerU JSON 中的所有对象。"""
|
||||
if isinstance(value, dict):
|
||||
yield value
|
||||
for child in value.values():
|
||||
yield from _walk_dicts(child)
|
||||
elif isinstance(value, list):
|
||||
for child in value:
|
||||
yield from _walk_dicts(child)
|
||||
|
||||
|
||||
def _is_cell_coordinate_object(item: dict[str, Any]) -> bool:
|
||||
"""仅把同时具有 bbox 和明确 cell/row/column 身份的对象计为单元格坐标。"""
|
||||
keys = {str(key).lower() for key in item}
|
||||
return bool(
|
||||
{'cell_id', 'cell_index'} & keys
|
||||
or ({'row_index', 'column_index'} <= keys)
|
||||
or ({'row_idx', 'col_idx'} <= keys)
|
||||
)
|
||||
|
||||
|
||||
def _valid_raw_bbox(value: Any) -> bool:
|
||||
"""判断服务 bbox 是否为四个有序非负数。"""
|
||||
if not isinstance(value, (list, tuple)) or len(value) != 4:
|
||||
return False
|
||||
try:
|
||||
x0, y0, x1, y1 = (float(item) for item in value)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return x0 >= 0 and y0 >= 0 and x1 > x0 and y1 > y0
|
||||
|
||||
|
||||
def _content_bbox_to_page(
|
||||
value: list[Any] | tuple[Any, ...], *, page_size: tuple[float, float],
|
||||
) -> tuple[LayoutBBox, LayoutBBox]:
|
||||
"""
|
||||
将 MinerU content_list 的 0..1000 画布坐标转换为标准化坐标和 PDF 页面单位。
|
||||
|
||||
核心逻辑:MinerU model_output 使用模型页面像素,content_list 再分别按宽高缩放到 1000;
|
||||
因此不能直接用 PDF page_size 做除数,也不能把越界值裁剪到 1。
|
||||
"""
|
||||
x0, y0, x1, y1 = (float(item) for item in value)
|
||||
if x1 > MINERU_CONTENT_COORDINATE_SCALE or y1 > MINERU_CONTENT_COORDINATE_SCALE:
|
||||
raise ValidationError(
|
||||
'MinerU content bbox exceeds coordinate canvas',
|
||||
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
normalized = LayoutBBox(
|
||||
x0=x0 / MINERU_CONTENT_COORDINATE_SCALE,
|
||||
y0=y0 / MINERU_CONTENT_COORDINATE_SCALE,
|
||||
x1=x1 / MINERU_CONTENT_COORDINATE_SCALE,
|
||||
y1=y1 / MINERU_CONTENT_COORDINATE_SCALE,
|
||||
)
|
||||
raw_bbox = LayoutBBox(
|
||||
x0=normalized.x0 * page_size[0],
|
||||
y0=normalized.y0 * page_size[1],
|
||||
x1=normalized.x1 * page_size[0],
|
||||
y1=normalized.y1 * page_size[1],
|
||||
)
|
||||
return raw_bbox, normalized
|
||||
|
||||
|
||||
def _add_page_size(result: dict[int, tuple[float, float]], page_no: int, width: Any, height: Any) -> None:
|
||||
"""写入合法页尺寸;已有 middle_json 结果优先保留。"""
|
||||
try:
|
||||
pair = (float(width), float(height))
|
||||
except (TypeError, ValueError):
|
||||
return
|
||||
if page_no >= 1 and pair[0] > 0 and pair[1] > 0:
|
||||
result.setdefault(page_no, pair)
|
||||
|
||||
|
||||
def _as_int(value: Any, *, default: int) -> int:
|
||||
"""安全解析 MinerU 页序,失败时使用调用方提供的零基默认值。"""
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _mime_type(extension: str) -> str:
|
||||
"""按已允许扩展名返回稳定 multipart MIME,不信任用户传入 Content-Type。"""
|
||||
return {
|
||||
'.pdf': 'application/pdf',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.doc': 'application/msword',
|
||||
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'.ppt': 'application/vnd.ms-powerpoint',
|
||||
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
}[extension]
|
||||
|
||||
|
||||
def _provider_error_code(value: Any) -> str:
|
||||
"""将服务端自由文本错误收敛为有限诊断码,避免文件名或正文进入业务错误详情。"""
|
||||
text = str(value or '').lower()
|
||||
if 'device string must not be empty' in text:
|
||||
return 'device_not_configured'
|
||||
if 'out of memory' in text or 'cuda oom' in text:
|
||||
return 'provider_out_of_memory'
|
||||
if 'unsupported' in text:
|
||||
return 'provider_unsupported_input'
|
||||
return 'provider_parse_failed'
|
||||
@@ -0,0 +1,433 @@
|
||||
"""
|
||||
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。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OpenCVGridConfig:
|
||||
"""保存一组形态学线段尺度;不同配置用于形成独立检测共识。"""
|
||||
|
||||
horizontal_divisor: int
|
||||
vertical_divisor: int
|
||||
close_length: int
|
||||
|
||||
|
||||
DEFAULT_GRID_CONFIGS = (
|
||||
OpenCVGridConfig(horizontal_divisor=30, vertical_divisor=20, close_length=3),
|
||||
OpenCVGridConfig(horizontal_divisor=25, vertical_divisor=18, close_length=5),
|
||||
OpenCVGridConfig(horizontal_divisor=20, vertical_divisor=15, close_length=7),
|
||||
)
|
||||
|
||||
|
||||
class OpenCVTableModel(BaseModel):
|
||||
"""为 OpenCV 网格候选启用严格字段校验,防止实验结果静默漂移。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class OpenCVCellGeometry(OpenCVTableModel):
|
||||
"""保存一个 HTML 原始 cell 在页面坐标和标准化坐标中的候选矩形。"""
|
||||
|
||||
cell_id: str
|
||||
row_index: int = Field(ge=0)
|
||||
column_index: int = Field(ge=0)
|
||||
row_span: int = Field(ge=1)
|
||||
column_span: int = Field(ge=1)
|
||||
bbox: LayoutBBox
|
||||
normalized_bbox: LayoutBBox
|
||||
|
||||
|
||||
class OpenCVTableGeometryResult(OpenCVTableModel):
|
||||
"""汇总多参数网格共识、cell 几何候选和不准入原因。"""
|
||||
|
||||
ready: bool
|
||||
consensus_count: int = Field(ge=0)
|
||||
row_count: int = Field(ge=0)
|
||||
column_count: int = Field(ge=0)
|
||||
cells: list[OpenCVCellGeometry] = Field(default_factory=list)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_readiness(self) -> 'OpenCVTableGeometryResult':
|
||||
"""ready 结果必须具有多配置共识和完整原始 cell 几何。"""
|
||||
if self.ready and (self.consensus_count < 2 or not self.cells or self.issues):
|
||||
raise ValueError('ready OpenCV table geometry requires stable complete consensus')
|
||||
if not self.ready and self.cells:
|
||||
raise ValueError('non-ready OpenCV table geometry must not expose cell bboxes')
|
||||
return self
|
||||
|
||||
|
||||
class OpenCVTextValidationResult(OpenCVTableModel):
|
||||
"""保存独立 PDF 文本层对 OpenCV cell bbox 的一致性验收结果。"""
|
||||
|
||||
accepted: bool
|
||||
nonempty_cell_count: int = Field(ge=0)
|
||||
matched_cell_count: int = Field(ge=0)
|
||||
match_rate: float = Field(ge=0, le=1)
|
||||
mismatched_cell_ids: list[str] = Field(default_factory=list)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def reconstruct_opencv_table_geometry(
|
||||
page_image: np.ndarray,
|
||||
*,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
table_bbox: LayoutBBox,
|
||||
grid: HtmlGrid,
|
||||
configs: tuple[OpenCVGridConfig, ...] = DEFAULT_GRID_CONFIGS,
|
||||
min_consensus: int = 2,
|
||||
boundary_tolerance_pixels: int = 8,
|
||||
) -> OpenCVTableGeometryResult:
|
||||
"""
|
||||
从渲染页面中恢复与 HTML 网格完全一致的有框表 cell bbox 候选。
|
||||
|
||||
Args:
|
||||
page_image: 左上原点的灰度或 RGB 页面 ndarray。
|
||||
page_width/page_height: MinerU/PDF 页面单位尺寸,必须与 table_bbox 同坐标系。
|
||||
table_bbox: MinerU 整表页面矩形,仅在该区域内检测。
|
||||
grid: 已展开 rowspan/colspan 的 HTML 网格。
|
||||
configs: 至少两组独立形态学配置。
|
||||
min_consensus: 达到 ready 所需的一致配置数量,最小为 2。
|
||||
boundary_tolerance_pixels: 不同配置边界允许的最大像素差。
|
||||
Returns:
|
||||
ready 时包含所有 HTML 原始 cell 的页面 bbox;失败时仅包含问题码。
|
||||
"""
|
||||
if min_consensus < 2 or len(configs) < min_consensus:
|
||||
raise ValueError('OpenCV grid reconstruction requires at least two configurations')
|
||||
image = _grayscale_page(page_image)
|
||||
crop, origin = _table_crop(
|
||||
image,
|
||||
table_bbox=table_bbox,
|
||||
page_width=page_width,
|
||||
page_height=page_height,
|
||||
)
|
||||
if crop is None:
|
||||
return _not_ready(grid, 'opencv_table_crop_invalid')
|
||||
|
||||
detections = [
|
||||
item
|
||||
for config in configs
|
||||
if (item := _detect_grid_boundaries(crop, config=config)) is not None
|
||||
and len(item[0]) == grid.column_count + 1
|
||||
and len(item[1]) == grid.row_count + 1
|
||||
]
|
||||
consensus = _boundary_consensus(
|
||||
detections,
|
||||
min_consensus=min_consensus,
|
||||
tolerance=boundary_tolerance_pixels,
|
||||
)
|
||||
if consensus is None:
|
||||
issue = 'opencv_table_grid_shape_mismatch' if detections else 'opencv_table_grid_not_detected'
|
||||
return _not_ready(grid, issue)
|
||||
x_boundaries, y_boundaries, consensus_count = consensus
|
||||
cells = _cell_geometries(
|
||||
grid,
|
||||
x_boundaries=x_boundaries,
|
||||
y_boundaries=y_boundaries,
|
||||
crop_origin=origin,
|
||||
image_width=image.shape[1],
|
||||
image_height=image.shape[0],
|
||||
page_width=page_width,
|
||||
page_height=page_height,
|
||||
)
|
||||
if len(cells) != len(grid.cells):
|
||||
return _not_ready(grid, 'opencv_table_cell_geometry_incomplete')
|
||||
return OpenCVTableGeometryResult(
|
||||
ready=True,
|
||||
consensus_count=consensus_count,
|
||||
row_count=grid.row_count,
|
||||
column_count=grid.column_count,
|
||||
cells=cells,
|
||||
)
|
||||
|
||||
|
||||
def validate_opencv_cell_text(
|
||||
geometry: OpenCVTableGeometryResult,
|
||||
*,
|
||||
grid: HtmlGrid,
|
||||
bounded_text_reader: Any,
|
||||
minimum_match_rate: float = 0.95,
|
||||
required_cell_ids: set[str] | None = None,
|
||||
) -> OpenCVTextValidationResult:
|
||||
"""
|
||||
用独立 PDF 文本层验收 OpenCV cell bbox,不允许文本参与修正或选择几何边界。
|
||||
|
||||
Args:
|
||||
geometry: 已通过多参数共识的 OpenCV 几何候选。
|
||||
grid: 同一 HTML 展开网格,用于读取原始 cell 文本。
|
||||
bounded_text_reader: 接收 LayoutBBox 并返回该页面矩形内原生 PDF 文本的函数。
|
||||
minimum_match_rate: 全部非空 cell 的最低一致率,默认 95%。
|
||||
required_cell_ids: 必须逐一匹配的高风险 cell ID 集合;任一不一致即拒绝。
|
||||
Returns:
|
||||
仅包含计数、比率和 cell_id 的验收结果,不复制字段值或原文。
|
||||
"""
|
||||
if not geometry.ready:
|
||||
return OpenCVTextValidationResult(
|
||||
accepted=False,
|
||||
nonempty_cell_count=0,
|
||||
matched_cell_count=0,
|
||||
match_rate=0,
|
||||
issues=['opencv_table_geometry_not_ready'],
|
||||
)
|
||||
if not 0 < minimum_match_rate <= 1:
|
||||
raise ValueError('OpenCV text validation match rate must be within (0, 1]')
|
||||
cells_by_id = {cell.cell_id: cell for cell in grid.cells}
|
||||
mismatched: list[str] = []
|
||||
matched = 0
|
||||
nonempty = 0
|
||||
for item in geometry.cells:
|
||||
cell = cells_by_id.get(item.cell_id)
|
||||
if cell is None:
|
||||
mismatched.append(item.cell_id)
|
||||
continue
|
||||
expected = _normalized_cell_text(cell.text)
|
||||
if not expected:
|
||||
continue
|
||||
nonempty += 1
|
||||
actual = _normalized_cell_text(bounded_text_reader(item.bbox))
|
||||
if actual and (expected in actual or actual in expected):
|
||||
matched += 1
|
||||
else:
|
||||
mismatched.append(item.cell_id)
|
||||
match_rate = matched / nonempty if nonempty else 0.0
|
||||
required = set(required_cell_ids or set())
|
||||
required_mismatch = bool(required & set(mismatched))
|
||||
issues: list[str] = []
|
||||
if nonempty == 0:
|
||||
issues.append('opencv_table_text_validation_empty')
|
||||
if match_rate < minimum_match_rate:
|
||||
issues.append('opencv_table_text_match_rate_low')
|
||||
if required_mismatch:
|
||||
issues.append('opencv_table_required_cell_text_mismatch')
|
||||
return OpenCVTextValidationResult(
|
||||
accepted=not issues,
|
||||
nonempty_cell_count=nonempty,
|
||||
matched_cell_count=matched,
|
||||
match_rate=match_rate,
|
||||
mismatched_cell_ids=sorted(mismatched),
|
||||
issues=issues,
|
||||
)
|
||||
|
||||
|
||||
def _grayscale_page(page_image: np.ndarray) -> np.ndarray:
|
||||
"""将受控页面 ndarray 转为 uint8 灰度图,拒绝不支持的维度。"""
|
||||
image = np.asarray(page_image)
|
||||
if image.dtype != np.uint8:
|
||||
image = np.clip(image, 0, 255).astype(np.uint8)
|
||||
if image.ndim == 2:
|
||||
return image
|
||||
if image.ndim == 3 and image.shape[2] in {3, 4}:
|
||||
code = cv2.COLOR_RGBA2GRAY if image.shape[2] == 4 else cv2.COLOR_RGB2GRAY
|
||||
return cv2.cvtColor(image, code)
|
||||
raise ValueError('OpenCV page image must be grayscale, RGB, or RGBA')
|
||||
|
||||
|
||||
def _table_crop(
|
||||
image: np.ndarray,
|
||||
*,
|
||||
table_bbox: LayoutBBox,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
) -> tuple[np.ndarray | None, tuple[int, int]]:
|
||||
"""把页面单位 table bbox 映射到图像像素并返回受控裁剪及左上原点。"""
|
||||
if page_width <= 0 or page_height <= 0:
|
||||
raise ValueError('OpenCV page dimensions must be positive')
|
||||
scale_x = image.shape[1] / page_width
|
||||
scale_y = image.shape[0] / page_height
|
||||
x0 = max(0, int(round(table_bbox.x0 * scale_x)) - 3)
|
||||
y0 = max(0, int(round(table_bbox.y0 * scale_y)) - 3)
|
||||
x1 = min(image.shape[1], int(round(table_bbox.x1 * scale_x)) + 4)
|
||||
y1 = min(image.shape[0], int(round(table_bbox.y1 * scale_y)) + 4)
|
||||
if x1 - x0 < 16 or y1 - y0 < 16:
|
||||
return None, (x0, y0)
|
||||
return image[y0:y1, x0:x1], (x0, y0)
|
||||
|
||||
|
||||
def _detect_grid_boundaries(
|
||||
crop: np.ndarray, *, config: OpenCVGridConfig,
|
||||
) -> tuple[list[int], list[int]] | None:
|
||||
"""用形态学线段和 cell 轮廓提取基础网格边界;不按文字或预期列宽补线。"""
|
||||
binary = cv2.adaptiveThreshold(
|
||||
crop,
|
||||
255,
|
||||
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||
cv2.THRESH_BINARY_INV,
|
||||
31,
|
||||
15,
|
||||
)
|
||||
horizontal_kernel = cv2.getStructuringElement(
|
||||
cv2.MORPH_RECT,
|
||||
(max(10, crop.shape[1] // config.horizontal_divisor), 1),
|
||||
)
|
||||
vertical_kernel = cv2.getStructuringElement(
|
||||
cv2.MORPH_RECT,
|
||||
(1, max(10, crop.shape[0] // config.vertical_divisor)),
|
||||
)
|
||||
horizontal = cv2.morphologyEx(binary, cv2.MORPH_OPEN, horizontal_kernel)
|
||||
vertical = cv2.morphologyEx(binary, cv2.MORPH_OPEN, vertical_kernel)
|
||||
if config.close_length:
|
||||
horizontal = cv2.morphologyEx(
|
||||
horizontal,
|
||||
cv2.MORPH_CLOSE,
|
||||
cv2.getStructuringElement(cv2.MORPH_RECT, (config.close_length, 1)),
|
||||
)
|
||||
vertical = cv2.morphologyEx(
|
||||
vertical,
|
||||
cv2.MORPH_CLOSE,
|
||||
cv2.getStructuringElement(cv2.MORPH_RECT, (1, config.close_length)),
|
||||
)
|
||||
mask = cv2.bitwise_or(horizontal, vertical)
|
||||
contours, _hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
|
||||
edges_x: list[int] = []
|
||||
edges_y: list[int] = []
|
||||
crop_area = crop.shape[0] * crop.shape[1]
|
||||
for contour in contours:
|
||||
x, y, width, height = cv2.boundingRect(contour)
|
||||
area = width * height
|
||||
if width < 8 or height < 8 or area < 50 or area > crop_area * 0.95:
|
||||
continue
|
||||
edges_x.extend((x, x + width))
|
||||
edges_y.extend((y, y + height))
|
||||
x_boundaries = _cluster_boundaries(edges_x, tolerance=8)
|
||||
y_boundaries = _cluster_boundaries(edges_y, tolerance=8)
|
||||
if len(x_boundaries) < 2 or len(y_boundaries) < 2:
|
||||
return None
|
||||
return x_boundaries, y_boundaries
|
||||
|
||||
|
||||
def _cluster_boundaries(values: list[int], *, tolerance: int) -> list[int]:
|
||||
"""把轮廓的近邻边缘聚合成稳定网格线,不补齐未检测到的边界。"""
|
||||
groups: list[list[int]] = []
|
||||
for value in sorted(values):
|
||||
if not groups or value - groups[-1][-1] > tolerance:
|
||||
groups.append([value])
|
||||
else:
|
||||
groups[-1].append(value)
|
||||
return [int(round(sum(group) / len(group))) for group in groups]
|
||||
|
||||
|
||||
def _boundary_consensus(
|
||||
detections: list[tuple[list[int], list[int]]],
|
||||
*,
|
||||
min_consensus: int,
|
||||
tolerance: int,
|
||||
) -> tuple[list[int], list[int], int] | None:
|
||||
"""选择至少 min_consensus 组逐边界一致的检测,并以中位数形成共识。"""
|
||||
for anchor_index, anchor in enumerate(detections):
|
||||
compatible = [anchor]
|
||||
for index, candidate in enumerate(detections):
|
||||
if index == anchor_index:
|
||||
continue
|
||||
if _boundaries_compatible(anchor, candidate, tolerance=tolerance):
|
||||
compatible.append(candidate)
|
||||
if len(compatible) < min_consensus:
|
||||
continue
|
||||
x_values = [
|
||||
int(round(float(np.median([item[0][index] for item in compatible]))))
|
||||
for index in range(len(anchor[0]))
|
||||
]
|
||||
y_values = [
|
||||
int(round(float(np.median([item[1][index] for item in compatible]))))
|
||||
for index in range(len(anchor[1]))
|
||||
]
|
||||
return x_values, y_values, len(compatible)
|
||||
return None
|
||||
|
||||
|
||||
def _boundaries_compatible(
|
||||
left: tuple[list[int], list[int]],
|
||||
right: tuple[list[int], list[int]],
|
||||
*,
|
||||
tolerance: int,
|
||||
) -> bool:
|
||||
"""判断两组等形边界是否逐项落在允许像素容差内。"""
|
||||
return (
|
||||
len(left[0]) == len(right[0])
|
||||
and len(left[1]) == len(right[1])
|
||||
and all(abs(a - b) <= tolerance for a, b in zip(left[0], right[0]))
|
||||
and all(abs(a - b) <= tolerance for a, b in zip(left[1], right[1]))
|
||||
)
|
||||
|
||||
|
||||
def _cell_geometries(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
x_boundaries: list[int],
|
||||
y_boundaries: list[int],
|
||||
crop_origin: tuple[int, int],
|
||||
image_width: int,
|
||||
image_height: int,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
) -> list[OpenCVCellGeometry]:
|
||||
"""按 HTML 原始 cell 的 rowspan/colspan 合并基础网格,并映射回页面坐标。"""
|
||||
scale_x = page_width / image_width
|
||||
scale_y = page_height / image_height
|
||||
result: list[OpenCVCellGeometry] = []
|
||||
for cell in grid.cells:
|
||||
row_end = cell.row_index + cell.row_span
|
||||
column_end = cell.column_index + cell.column_span
|
||||
if row_end >= len(y_boundaries) or column_end >= len(x_boundaries):
|
||||
return []
|
||||
pixel_x0 = crop_origin[0] + x_boundaries[cell.column_index]
|
||||
pixel_y0 = crop_origin[1] + y_boundaries[cell.row_index]
|
||||
pixel_x1 = crop_origin[0] + x_boundaries[column_end]
|
||||
pixel_y1 = crop_origin[1] + y_boundaries[row_end]
|
||||
bbox = LayoutBBox(
|
||||
x0=pixel_x0 * scale_x,
|
||||
y0=pixel_y0 * scale_y,
|
||||
x1=pixel_x1 * scale_x,
|
||||
y1=pixel_y1 * scale_y,
|
||||
)
|
||||
result.append(OpenCVCellGeometry(
|
||||
cell_id=cell.cell_id,
|
||||
row_index=cell.row_index,
|
||||
column_index=cell.column_index,
|
||||
row_span=cell.row_span,
|
||||
column_span=cell.column_span,
|
||||
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,
|
||||
),
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def _not_ready(grid: HtmlGrid, issue: str) -> OpenCVTableGeometryResult:
|
||||
"""构造不暴露任何候选 bbox 的稳定失败结果。"""
|
||||
return OpenCVTableGeometryResult(
|
||||
ready=False,
|
||||
consensus_count=0,
|
||||
row_count=grid.row_count,
|
||||
column_count=grid.column_count,
|
||||
issues=[issue],
|
||||
)
|
||||
|
||||
|
||||
def _normalized_cell_text(value: Any) -> str:
|
||||
"""以 NFKC、大小写折叠和字母数字/中日韩字符保留生成文本一致性比较键。"""
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).casefold()
|
||||
return re.sub(r'[^0-9a-z\u4e00-\u9fff]+', '', text)
|
||||
@@ -0,0 +1,280 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/order_profile.py
|
||||
|
||||
用途:定义订单文档模板级解析 Profile 纯契约,覆盖全局 Schema 无法表达的模板列语义。
|
||||
依赖:Pydantic、HTML 网格、订单字段规则和既有 TEMP 复合料号规则。
|
||||
逻辑:Profile 只在精确结构指纹命中时按固定列执行注册解析器;行结构已丢失的模板显式阻断,不做相似匹配。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
|
||||
from app.services.shipping_notice.notice_line_values import parse_number
|
||||
from app.services.shipping_notice.notice_lines import resolve_composite_part_numbers
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import (
|
||||
TableHeaderContract,
|
||||
normalize_table_header,
|
||||
)
|
||||
|
||||
|
||||
ORDER_PROFILE_VERSION = 'shipping_order_document_profile.v1'
|
||||
PROFILE_EXTRACTORS = frozenset({'direct', 'temp_internal_parts'})
|
||||
|
||||
|
||||
class OrderProfileModel(BaseModel):
|
||||
"""为模板 Profile 和执行结果启用严格字段及赋值校验。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class OrderProfileColumnRule(OrderProfileModel):
|
||||
"""定义一个固定来源列使用的注册解析器及目标字段编码。"""
|
||||
|
||||
column_index: int = Field(ge=0)
|
||||
extractor_key: Literal['direct', 'temp_internal_parts']
|
||||
target_field_codes: list[str] = Field(min_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_extractor_targets(self) -> 'OrderProfileColumnRule':
|
||||
"""限制注册解析器的固定输出形态,禁止自由脚本或任意字段注入。"""
|
||||
targets = set(self.target_field_codes)
|
||||
if len(targets) != len(self.target_field_codes):
|
||||
raise ValueError('order profile target fields must be unique')
|
||||
if self.extractor_key == 'direct' and len(targets) != 1:
|
||||
raise ValueError('direct order profile extractor requires one target field')
|
||||
if self.extractor_key == 'temp_internal_parts' and targets != {
|
||||
'customer_part_number', 'part_number',
|
||||
}:
|
||||
raise ValueError('TEMP/internal extractor targets are fixed')
|
||||
return self
|
||||
|
||||
|
||||
class OrderDocumentProfile(OrderProfileModel):
|
||||
"""保存不可变模板结构、列覆盖、数据起始行和质量策略。"""
|
||||
|
||||
contract_version: Literal[ORDER_PROFILE_VERSION] = ORDER_PROFILE_VERSION
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
version: int = Field(ge=1)
|
||||
structure_fingerprint: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
header_row_index: int = Field(ge=0)
|
||||
data_start_row_index: int = Field(ge=1)
|
||||
row_structure: Literal['preserved', 'unsupported_row_structure'] = 'preserved'
|
||||
column_rules: list[OrderProfileColumnRule] = Field(default_factory=list)
|
||||
drop_zero_qty: bool = True
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderDocumentProfile':
|
||||
"""禁止列规则重复;不支持的行结构只能作为识别/路由 Profile,不能配置字段解析。"""
|
||||
columns = [item.column_index for item in self.column_rules]
|
||||
if len(columns) != len(set(columns)):
|
||||
raise ValueError('order profile source columns must be unique')
|
||||
if self.data_start_row_index <= self.header_row_index:
|
||||
raise ValueError('order profile data rows must start after the header')
|
||||
if self.row_structure == 'unsupported_row_structure' and self.column_rules:
|
||||
raise ValueError('unsupported row structure profile cannot expose column mappings')
|
||||
if self.row_structure == 'preserved' and not self.column_rules:
|
||||
raise ValueError('preserved row structure profile requires column mappings')
|
||||
return self
|
||||
|
||||
|
||||
class OrderProfileRowResult(OrderProfileModel):
|
||||
"""保存一条模板行的字段值或删除/复核状态,不包含来源原文。"""
|
||||
|
||||
row_index: int = Field(ge=0)
|
||||
status: Literal['parsed', 'deleted', 'needs_review']
|
||||
fields: dict[str, Any] = Field(default_factory=dict)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class OrderProfileParseResult(OrderProfileModel):
|
||||
"""汇总 Profile 是否精确命中以及模板行解析结果。"""
|
||||
|
||||
matched: bool
|
||||
profile_code: str | None = None
|
||||
profile_version: int | None = Field(default=None, ge=1)
|
||||
rows: list[OrderProfileRowResult] = Field(default_factory=list)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def order_profile_structure_fingerprint(
|
||||
grid: HtmlGrid, *, header_row_index: int,
|
||||
) -> str:
|
||||
"""
|
||||
由表头前缀网格的规范化文字、cell 身份和跨度生成精确结构指纹。
|
||||
|
||||
Args:
|
||||
grid: 已展开的 HTML 网格。
|
||||
header_row_index: 模板最后一行表头索引;数据行和值不进入指纹。
|
||||
Returns:
|
||||
64 位 SHA-256 十六进制指纹。
|
||||
"""
|
||||
if header_row_index < 0 or header_row_index >= grid.row_count:
|
||||
raise ValueError('order profile header row index is invalid')
|
||||
cells = [
|
||||
{
|
||||
'row': cell.row_index,
|
||||
'column': cell.column_index,
|
||||
'row_span': cell.row_span,
|
||||
'column_span': cell.column_span,
|
||||
'text': cell.normalized_text,
|
||||
}
|
||||
for cell in grid.cells
|
||||
if cell.row_index <= header_row_index
|
||||
]
|
||||
payload = {
|
||||
'column_count': grid.column_count,
|
||||
'header_row_index': header_row_index,
|
||||
'cells': cells,
|
||||
}
|
||||
encoded = json.dumps(payload, sort_keys=True, ensure_ascii=True, separators=(',', ':')).encode()
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def parse_html_table_with_order_profile(
|
||||
html: str,
|
||||
*,
|
||||
table_id: str,
|
||||
profile: OrderDocumentProfile,
|
||||
contract: TableHeaderContract,
|
||||
) -> OrderProfileParseResult:
|
||||
"""
|
||||
在结构指纹精确命中时按模板列规则解析订单行。
|
||||
|
||||
Args:
|
||||
html: MinerU 或 EML 提供的单张 HTML table。
|
||||
table_id: 当前文档内稳定表格 ID。
|
||||
profile: Run 锁定的 published 模板 Profile 快照。
|
||||
contract: Run 锁定订单 Schema 表头/字段契约。
|
||||
Returns:
|
||||
未命中时不产生行;不支持行结构时返回阻断问题;命中时逐行解析。
|
||||
"""
|
||||
grid = parse_html_grid(html, table_id=table_id)
|
||||
actual = order_profile_structure_fingerprint(
|
||||
grid,
|
||||
header_row_index=profile.header_row_index,
|
||||
)
|
||||
if actual != profile.structure_fingerprint:
|
||||
return OrderProfileParseResult(matched=False, issues=['order_profile_structure_mismatch'])
|
||||
if profile.row_structure == 'unsupported_row_structure':
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
issues=['order_profile_row_structure_unsupported'],
|
||||
)
|
||||
if any(rule.column_index >= grid.column_count for rule in profile.column_rules):
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
issues=['order_profile_column_out_of_range'],
|
||||
)
|
||||
rows = [
|
||||
_parse_profile_row(
|
||||
grid,
|
||||
row_index=index,
|
||||
profile=profile,
|
||||
contract=contract,
|
||||
)
|
||||
for index in range(profile.data_start_row_index, grid.row_count)
|
||||
]
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
rows=rows,
|
||||
)
|
||||
|
||||
|
||||
def _parse_profile_row(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
row_index: int,
|
||||
profile: OrderDocumentProfile,
|
||||
contract: TableHeaderContract,
|
||||
) -> OrderProfileRowResult:
|
||||
"""执行一条 preserved 模板行;零 Qty 删除,非法字段保留机器问题码。"""
|
||||
fields: dict[str, Any] = {}
|
||||
issues: list[str] = []
|
||||
explicit_qty: float | None = None
|
||||
for rule in profile.column_rules:
|
||||
slot = grid.rows[row_index][rule.column_index]
|
||||
raw = slot.text.strip() if slot is not None else ''
|
||||
extracted = (
|
||||
{rule.target_field_codes[0]: raw}
|
||||
if rule.extractor_key == 'direct'
|
||||
else _apply_profile_extractor(rule.extractor_key, raw)
|
||||
)
|
||||
for code in rule.target_field_codes:
|
||||
candidate = extracted.get(code)
|
||||
if candidate in (None, ''):
|
||||
continue
|
||||
if code == 'qty':
|
||||
explicit_qty = parse_number(candidate)
|
||||
config = contract.fields_by_code.get(code)
|
||||
value = _normalize_profile_value(candidate, config)
|
||||
if value is None:
|
||||
issues.append(f'order_profile_field_invalid:{code}')
|
||||
continue
|
||||
fields[code] = value.isoformat() if hasattr(value, 'isoformat') else value
|
||||
if profile.drop_zero_qty and explicit_qty == 0:
|
||||
return OrderProfileRowResult(row_index=row_index, status='deleted')
|
||||
required_build = {'part_number', 'qty'}
|
||||
if not required_build.issubset(fields):
|
||||
issues.append('order_profile_build_fields_missing')
|
||||
return OrderProfileRowResult(
|
||||
row_index=row_index,
|
||||
status='parsed' if not issues else 'needs_review',
|
||||
fields=fields,
|
||||
issues=sorted(set(issues)),
|
||||
)
|
||||
|
||||
|
||||
def _apply_profile_extractor(extractor_key: str, raw: str) -> dict[str, Any]:
|
||||
"""执行代码注册的有限解析器;未知 key 不允许运行。"""
|
||||
if extractor_key == 'temp_internal_parts':
|
||||
resolved = resolve_composite_part_numbers(raw)
|
||||
if resolved:
|
||||
return resolved
|
||||
customer = re.search(r'\b(?:AM)?TEMP-[A-Z0-9._-]+\b', raw, re.IGNORECASE)
|
||||
internal = re.search(r'\bD4-[A-Z0-9._-]+\b', raw, re.IGNORECASE)
|
||||
if customer and internal:
|
||||
return {
|
||||
'customer_part_number': customer.group(0),
|
||||
'part_number': internal.group(0),
|
||||
}
|
||||
return {}
|
||||
raise ValueError('order profile extractor is not registered')
|
||||
|
||||
|
||||
def _normalize_profile_value(raw: Any, config: dict[str, Any] | None) -> Any:
|
||||
"""按冻结 Schema 类型和 validator 规范化模板字段;非法值返回 None。"""
|
||||
if config is None:
|
||||
return None
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
candidate = raw
|
||||
if value_type in {'decimal', 'integer'}:
|
||||
candidate = parse_number(raw)
|
||||
if candidate is None:
|
||||
return None
|
||||
if value_type == 'integer':
|
||||
if not float(candidate).is_integer():
|
||||
return None
|
||||
candidate = int(candidate)
|
||||
try:
|
||||
value = normalize_order_field_value(candidate, config)
|
||||
return value if value is not None and validate_order_field_value(value, config) else None
|
||||
except (ArithmeticError, TypeError, ValueError, ValidationError):
|
||||
return None
|
||||
Reference in new issue
Block a user