feat(shipping-notice): 增强发货通知与订单抽取功能,支持多进程处理与紧急停止
- 移除不再使用的 SHIPPING_NOTICE_LAYOUT_PARSER_REVISION 配置 - 在环境配置中新增 SHIPPING_NOTICE_WORKER_CONCURRENCY 和 SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS - 实现发货通知 worker 进程,支持并发处理订单抽取任务 - 引入紧急停止功能,允许管理员在运行中控制订单解析状态 - 更新相关 API,支持读取与设置紧急停止状态 - 增强文档与代码注释,反映新的业务逻辑与功能要求
This commit is contained in:
1 parent
d0fe084999
commit
b352c281d5
149 files changed
+12550
-1874
No files matched your search
@@ -54,6 +54,7 @@ from app.services.shipping_notice.document_layout.text_cell_alignment import (
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
NativePdfPage,
|
||||
build_native_pdf_layout_candidate,
|
||||
build_native_pdf_text_table_fallbacks,
|
||||
extract_native_pdf_pages,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate
|
||||
@@ -95,6 +96,7 @@ __all__ = [
|
||||
'TextCellAlignmentResult',
|
||||
'NativePdfPage',
|
||||
'build_native_pdf_layout_candidate',
|
||||
'build_native_pdf_text_table_fallbacks',
|
||||
'extract_native_pdf_pages',
|
||||
'build_html_layout_candidate',
|
||||
'OcrCellEvidence',
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/coordinate_region_text.py
|
||||
|
||||
用途:统一从页面坐标字符中读取受控区域文字。
|
||||
依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约。
|
||||
逻辑:标注取字、模板匹配和版本诊断共同使用视觉行聚类与行内横坐标排序,避免阅读顺序分叉。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def visual_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
|
||||
"""
|
||||
将坐标字符按视觉行恢复为阅读顺序文本。
|
||||
|
||||
Args:
|
||||
glyphs: 含 text 与 bbox 的页面字符;无效字符会被忽略。
|
||||
|
||||
Returns:
|
||||
从上到下的文本行;同行字符按 x0 排序,并按视觉间距恢复单个空格。
|
||||
"""
|
||||
rows: list[list[dict[str, Any]]] = []
|
||||
for glyph in sorted(
|
||||
glyphs,
|
||||
key=lambda item: (
|
||||
float((item.get('bbox') or {}).get('y0', 0)),
|
||||
float((item.get('bbox') or {}).get('x0', 0)),
|
||||
),
|
||||
):
|
||||
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
|
||||
if not bbox or not str(glyph.get('text') or '').strip():
|
||||
continue
|
||||
try:
|
||||
center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2
|
||||
height = max(1.0, float(bbox['y1']) - float(bbox['y0']))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if rows:
|
||||
previous = rows[-1][0].get('bbox') or {}
|
||||
previous_y = (float(previous.get('y0', 0)) + float(previous.get('y1', 0))) / 2
|
||||
previous_height = max(1.0, float(previous.get('y1', 0)) - float(previous.get('y0', 0)))
|
||||
if abs(center_y - previous_y) <= max(height, previous_height) * .65:
|
||||
rows[-1].append(glyph)
|
||||
continue
|
||||
rows.append([glyph])
|
||||
|
||||
lines: list[str] = []
|
||||
for row in rows:
|
||||
ordered = sorted(row, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
|
||||
parts: list[str] = []
|
||||
previous_x1: float | None = None
|
||||
previous_width = 0.0
|
||||
for item in ordered:
|
||||
box = item['bbox']
|
||||
x0, x1 = float(box['x0']), float(box['x1'])
|
||||
if previous_x1 is not None and x0 - previous_x1 > max(1.5, previous_width * 1.45):
|
||||
parts.append(' ')
|
||||
parts.append(str(item.get('text') or ''))
|
||||
previous_x1, previous_width = x1, max(1.0, x1 - x0)
|
||||
text = ''.join(parts).strip()
|
||||
if text:
|
||||
lines.append(text)
|
||||
return lines
|
||||
|
||||
|
||||
def read_coordinate_region_text(
|
||||
*,
|
||||
glyphs: list[dict[str, Any]],
|
||||
page: dict[str, Any],
|
||||
region: dict[str, Any],
|
||||
) -> str:
|
||||
"""
|
||||
读取相对坐标区域内的文字,并保持与标注画布一致的阅读顺序。
|
||||
|
||||
Args:
|
||||
glyphs: 当前页冻结坐标字符。
|
||||
page: 必须含正数 width/height。
|
||||
region: 0..1 相对坐标 x0/y0/x1/y1,禁止传入页面绝对坐标。
|
||||
|
||||
Returns:
|
||||
多个视觉行以单个空格连接的纯文本;区域无字符时返回空字符串。
|
||||
"""
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
x0, y0, x1, y1 = (float(region[key]) for key in ('x0', 'y0', 'x1', 'y1'))
|
||||
selected: list[dict[str, Any]] = []
|
||||
overlapping: list[dict[str, Any]] = []
|
||||
for glyph in glyphs:
|
||||
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
|
||||
if not bbox:
|
||||
continue
|
||||
glyph_x0, glyph_x1 = float(bbox['x0']) / width, float(bbox['x1']) / width
|
||||
glyph_y0, glyph_y1 = float(bbox['y0']) / height, float(bbox['y1']) / height
|
||||
center_x, center_y = (glyph_x0 + glyph_x1) / 2, (glyph_y0 + glyph_y1) / 2
|
||||
if x0 <= center_x <= x1 and y0 <= center_y <= y1:
|
||||
selected.append(glyph)
|
||||
elif glyph_x1 >= x0 and glyph_x0 <= x1 and glyph_y1 >= y0 and glyph_y0 <= y1:
|
||||
overlapping.append(glyph)
|
||||
if not selected and overlapping:
|
||||
target_y = (y0 + y1) / 2
|
||||
rows: list[list[dict[str, Any]]] = []
|
||||
for glyph in overlapping:
|
||||
bbox = glyph['bbox']
|
||||
center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2
|
||||
if rows:
|
||||
previous = rows[-1][0]['bbox']
|
||||
previous_y = (float(previous['y0']) + float(previous['y1'])) / 2
|
||||
height_px = max(1.0, float(previous['y1']) - float(previous['y0']))
|
||||
if abs(center_y - previous_y) <= height_px * .65:
|
||||
rows[-1].append(glyph)
|
||||
continue
|
||||
rows.append([glyph])
|
||||
selected = min(
|
||||
rows,
|
||||
key=lambda row: abs(
|
||||
(((float(row[0]['bbox']['y0']) + float(row[0]['bbox']['y1'])) / 2) / height) - target_y
|
||||
),
|
||||
)
|
||||
return ' '.join(visual_text_lines(selected)).strip()
|
||||
+206
-22
@@ -17,6 +17,7 @@ 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.text_cell_alignment import PositionedCharacter
|
||||
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
# 客户 PO 行号常见形态(含前导零);起行锚点默认按此形态识别,不做数值归一化。
|
||||
@@ -265,13 +266,15 @@ def reconstruct_coordinate_profile_rows(
|
||||
include_deleted: bool = False,
|
||||
line_start_field_code: str | None = None,
|
||||
include_unanchored_rows: bool = False,
|
||||
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows',
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""
|
||||
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
|
||||
|
||||
主行必须在其已绑定起行锚点字段(默认 ``customer_po_line_no``)中出现有效值才启动明细;
|
||||
未满足此条件的视觉行不会被猜测为新行。随后只按连续 ``row_offset`` 消费 continuation,
|
||||
避免描述换行、合计或相邻无关表区静默混入当前订单行。``include_deleted`` 仅供标注预览
|
||||
避免描述换行、合计或相邻无关表区静默混入当前订单行。删除文字只有位于模板排除区内
|
||||
才是已授权的删除证据;未授权删除文字会被忽略。``include_deleted`` 仅供标注预览
|
||||
返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。仅管理员预览可开启
|
||||
``include_unanchored_rows``,在没有任何有效起行值时返回待复核的主行字段,不能用于正式解析。
|
||||
"""
|
||||
@@ -297,30 +300,47 @@ def reconstruct_coordinate_profile_rows(
|
||||
_absolute_relative_region(bbox, item)
|
||||
for item in (exclusion_regions or []) if isinstance(item, dict)
|
||||
]
|
||||
if exclusions:
|
||||
# Footer, signature and tax blocks are not candidate rows. Keep an explicit
|
||||
# deletion marker from an exclusion region, however: it controls the prior
|
||||
# detail row and must not be discarded before row reconstruction sees it.
|
||||
deletion_marker_indices = {
|
||||
glyph_index
|
||||
for band in _group_visual_rows(glyphs)
|
||||
if _DELETED_PATTERN.fullmatch(re.sub(
|
||||
r'\s+', '', ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)),
|
||||
))
|
||||
and any(
|
||||
any(_inside_region(glyph.bbox, region) for region in exclusions)
|
||||
for glyph_index, glyph in band
|
||||
)
|
||||
for glyph_index, _glyph in band
|
||||
}
|
||||
glyphs = [
|
||||
item for item in glyphs
|
||||
if item[0] in deletion_marker_indices
|
||||
or not any(_inside_region(item[1].bbox, region) for region in exclusions)
|
||||
]
|
||||
# [STEP 1] 删除文字不是全局业务规则;只有管理员用排除区显式圈定后才授权删除上一条明细。
|
||||
marker_indices: set[int] = set()
|
||||
authorized_marker_indices: set[int] = set()
|
||||
for band in _group_visual_rows(glyphs):
|
||||
compact_text = re.sub(
|
||||
r'\s+', '', ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)),
|
||||
)
|
||||
if not _DELETED_PATTERN.fullmatch(compact_text):
|
||||
continue
|
||||
band_indices = {glyph_index for glyph_index, _glyph in band}
|
||||
marker_indices.update(band_indices)
|
||||
if exclusions and any(
|
||||
_inside_region(glyph.bbox, region)
|
||||
for _glyph_index, glyph in band
|
||||
for region in exclusions
|
||||
):
|
||||
authorized_marker_indices.update(band_indices)
|
||||
# [STEP 2] 普通排除区内容与未授权删除文字都不参与字段重建;已授权删除标记保留到行状态判定。
|
||||
glyphs = [
|
||||
item for item in glyphs
|
||||
if item[0] in authorized_marker_indices
|
||||
or (
|
||||
item[0] not in marker_indices
|
||||
and not any(_inside_region(item[1].bbox, region) for region in exclusions)
|
||||
)
|
||||
]
|
||||
if not glyphs:
|
||||
return []
|
||||
|
||||
# This mode is opt-in per table region. It supports documents whose stable
|
||||
# columns stay put while optional descriptions move values across visual rows.
|
||||
if row_reconstruction_mode == 'adaptive_record_columns':
|
||||
return _reconstruct_adaptive_record_columns_profile_rows(
|
||||
glyphs=glyphs,
|
||||
table_bbox=bbox,
|
||||
ordered_layouts=ordered_layouts,
|
||||
termination_rules=termination_rules or [],
|
||||
include_deleted=include_deleted,
|
||||
line_start_field_code=start_field_code,
|
||||
)
|
||||
|
||||
relative_y_rows = _reconstruct_relative_y_profile_rows(
|
||||
glyphs=glyphs,
|
||||
table_bbox=bbox,
|
||||
@@ -419,6 +439,168 @@ def reconstruct_coordinate_profile_rows(
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
|
||||
|
||||
def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
*,
|
||||
glyphs: list[tuple[int, PositionedCharacter]],
|
||||
table_bbox: LayoutBBox,
|
||||
ordered_layouts: list[dict[str, Any]],
|
||||
termination_rules: list[dict[str, Any]],
|
||||
include_deleted: bool,
|
||||
line_start_field_code: str,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""按起行锚点分段,并在每段内用字段列及格式读取可变视觉子行。"""
|
||||
main_fields = ordered_layouts[0].get('field_regions') or []
|
||||
start_field = next(
|
||||
(item for item in main_fields if isinstance(item, dict) and item.get('field_code') == line_start_field_code),
|
||||
None,
|
||||
)
|
||||
if not isinstance(start_field, dict) or not isinstance(start_field.get('region'), dict):
|
||||
return []
|
||||
fields = [
|
||||
field
|
||||
for layout in ordered_layouts
|
||||
for field in (layout.get('field_regions') or [])
|
||||
if isinstance(field, dict) and isinstance(field.get('region'), dict) and field.get('field_code')
|
||||
]
|
||||
bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = []
|
||||
for row_index, band in enumerate(_group_visual_rows(glyphs)):
|
||||
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
if _SUMMARY_PATTERN.search(text) or _matches_termination_rule(band, table_bbox, termination_rules):
|
||||
break
|
||||
bands.append((row_index, band))
|
||||
start_region = _absolute_relative_region(table_bbox, start_field['region'])
|
||||
anchors = [
|
||||
index for index, (_, band) in enumerate(bands)
|
||||
if _is_adaptive_record_start(
|
||||
band=band,
|
||||
start_region=start_region,
|
||||
main_fields=main_fields,
|
||||
table_bbox=table_bbox,
|
||||
line_start_field_code=line_start_field_code,
|
||||
)
|
||||
]
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
for anchor_index, start in enumerate(anchors):
|
||||
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(bands)
|
||||
record = bands[start:end]
|
||||
deleted = any(_DELETED_PATTERN.fullmatch(re.sub(
|
||||
r'\s+', '', ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)),
|
||||
)) for _, band in record)
|
||||
values: dict[str, str] = {}
|
||||
issues: list[str] = []
|
||||
for field in fields:
|
||||
code = str(field['field_code'])
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
candidates: list[tuple[float, int, dict[str, str]]] = []
|
||||
for band_index, (_, band) in enumerate(record):
|
||||
raw = _adaptive_field_raw(band=band, region=region, field_code=code)
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
|
||||
)
|
||||
if extracted:
|
||||
score = _adaptive_field_score(
|
||||
raw=raw,
|
||||
field_code=code,
|
||||
band_index=band_index,
|
||||
record=record,
|
||||
fields=fields,
|
||||
table_bbox=table_bbox,
|
||||
)
|
||||
candidates.append((score, band_index, extracted))
|
||||
if not candidates:
|
||||
continue
|
||||
# Stable tie breaking favors the configured physical-line order.
|
||||
expected_band = int(next(
|
||||
layout['row_offset'] for layout in ordered_layouts if field in (layout.get('field_regions') or [])
|
||||
))
|
||||
candidates.sort(key=lambda item: (-item[0], abs(item[1] - expected_band), item[1]))
|
||||
score, _band_index, extracted = candidates[0]
|
||||
if score < 0:
|
||||
continue
|
||||
for extracted_code, extracted_value in extracted.items():
|
||||
previous = values.get(extracted_code)
|
||||
if previous is not None and previous != extracted_value:
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
if is_valid_line_start_value(values.get(line_start_field_code, '')):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _ in record],
|
||||
role='deleted' if deleted else 'data',
|
||||
issues=issues,
|
||||
))
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
|
||||
|
||||
def _adaptive_field_raw(
|
||||
*, band: list[tuple[int, PositionedCharacter]], region: LayoutBBox, field_code: str,
|
||||
) -> str:
|
||||
"""读取自适应字段候选;单位仅接受完整字母文本块,避免分页微偏移截断首字符。"""
|
||||
if field_code != 'uom':
|
||||
return _text_in_horizontal_region(band, region)
|
||||
candidates = [
|
||||
''.join(glyph.text for _, glyph in run).strip()
|
||||
for run in _group_text_runs(band)
|
||||
if region.x0 <= (_run_bbox(run).x0 + _run_bbox(run).x1) / 2 <= region.x1
|
||||
]
|
||||
return next((item for item in candidates if _field_content_score(item, 'uom') > 0), '')
|
||||
|
||||
|
||||
def _is_adaptive_record_start(
|
||||
*, band: list[tuple[int, PositionedCharacter]], start_region: LayoutBBox,
|
||||
main_fields: list[dict[str, Any]], table_bbox: LayoutBBox, line_start_field_code: str,
|
||||
) -> bool:
|
||||
"""要求起行号及同一主行的其他绑定字段共同成立,排除页眉、地址中的孤立数字。"""
|
||||
if not is_valid_line_start_value(_text_in_horizontal_region(band, start_region)):
|
||||
return False
|
||||
evidence_fields = [
|
||||
item for item in main_fields
|
||||
if item.get('field_code') != line_start_field_code and item.get('field_code') in {
|
||||
'part_number', 'customer_part_number', 'aws_part_number',
|
||||
}
|
||||
]
|
||||
return all(
|
||||
_is_compact_identifier(
|
||||
_text_in_horizontal_region(band, _absolute_relative_region(table_bbox, field['region']))
|
||||
)
|
||||
for field in evidence_fields
|
||||
)
|
||||
|
||||
|
||||
def _is_compact_identifier(raw: str) -> bool:
|
||||
"""只接受无空格的料号形态,避免地址文本满足宽松的字母数字格式。"""
|
||||
value = str(raw or '').strip()
|
||||
return bool(
|
||||
value
|
||||
and not re.search(r'\s', value)
|
||||
and re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._/-]{2,}', value)
|
||||
)
|
||||
|
||||
|
||||
def _adaptive_field_score(
|
||||
*, raw: str, field_code: str, band_index: int,
|
||||
record: list[tuple[int, list[tuple[int, PositionedCharacter]]]],
|
||||
fields: list[dict[str, Any]], table_bbox: LayoutBBox,
|
||||
) -> float:
|
||||
"""为显式自适应模板评估字段候选,利用字段类型与同一逻辑行关系消除歧义。"""
|
||||
score = _field_content_score(raw, field_code)
|
||||
if score < 0:
|
||||
return score
|
||||
related_code = {'qty': 'uom', 'unit_price': 'line_amount_with_tax'}.get(field_code)
|
||||
related = next((item for item in fields if item.get('field_code') == related_code), None)
|
||||
if related is None:
|
||||
return score
|
||||
related_region = _absolute_relative_region(table_bbox, related['region'])
|
||||
for other_index, (_, band) in enumerate(record):
|
||||
related_raw = _text_in_horizontal_region(band, related_region)
|
||||
if _field_content_score(related_raw, related_code) > 0:
|
||||
# Qty and UOM are adjacent; unit price and amount normally share one band.
|
||||
distance = abs(other_index - band_index)
|
||||
score += 2.0 if distance == 0 else max(0.0, 1.0 - distance * .25)
|
||||
return score
|
||||
|
||||
|
||||
def _reconstruct_relative_y_profile_rows(
|
||||
*,
|
||||
glyphs: list[tuple[int, PositionedCharacter]],
|
||||
@@ -1265,6 +1447,8 @@ def _field_content_score(text: str, field_code: str | None) -> float:
|
||||
compact = value.replace(',', '').replace(' ', '')
|
||||
if field_code in {'line_no', DEFAULT_LINE_START_FIELD_CODE, 'customer_po_line_no'}:
|
||||
return 1.0 if is_valid_line_start_value(compact) else -1.0
|
||||
if field_code == 'reservation_id':
|
||||
return 1.0 if validated_reservation_id(value) else -1.0
|
||||
if field_code in {'qty', 'unit_price', 'amount', 'line_amount_before_tax', 'line_amount_with_tax'}:
|
||||
return 1.0 if re.fullmatch(r'[-+]?\d+(?:\.\d+)?', compact) else -1.0
|
||||
if field_code == 'uom':
|
||||
|
||||
@@ -132,6 +132,62 @@ class HtmlTableMappingResult(HtmlTableModel):
|
||||
return {item.field_code for item in self.columns if item.field_code}
|
||||
|
||||
|
||||
def summarize_row_roles(rows: list[HtmlMappedRow]) -> dict[str, int]:
|
||||
"""
|
||||
汇总行角色计数,供 schema_mapping 与完整性报告使用。
|
||||
|
||||
Returns:
|
||||
role -> count 字典,键顺序稳定。
|
||||
"""
|
||||
counts: dict[str, int] = {}
|
||||
for row in rows:
|
||||
counts[row.role] = counts.get(row.role, 0) + 1
|
||||
return dict(sorted(counts.items()))
|
||||
|
||||
|
||||
def collect_unmapped_nonempty_columns(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
header_index: int | None,
|
||||
columns: list[HtmlColumnMapping],
|
||||
rows: list[HtmlMappedRow],
|
||||
) -> list[int]:
|
||||
"""
|
||||
列出存在非空数据但未映射的列索引。
|
||||
|
||||
核心逻辑:只扫描 data/summary/repeated_header 行;表头行与 empty/deleted 行不参与。
|
||||
|
||||
Args:
|
||||
grid: 当前表网格。
|
||||
header_index: 已选表头行;None 时返回空列表。
|
||||
columns: 列映射诊断。
|
||||
rows: 已分类的数据行列表。
|
||||
|
||||
Returns:
|
||||
升序 column_index 列表。
|
||||
"""
|
||||
if header_index is None:
|
||||
return []
|
||||
unmapped = {
|
||||
column.column_index for column in columns
|
||||
if column.status == 'unmapped'
|
||||
}
|
||||
if not unmapped:
|
||||
return []
|
||||
active_roles = {'data', 'summary', 'repeated_header'}
|
||||
indices: set[int] = set()
|
||||
for row in rows:
|
||||
if row.role not in active_roles:
|
||||
continue
|
||||
if row.row_index < 0 or row.row_index >= grid.row_count:
|
||||
continue
|
||||
for column_index in unmapped:
|
||||
slot = grid.rows[row.row_index][column_index]
|
||||
if slot is not None and slot.text.strip():
|
||||
indices.add(column_index)
|
||||
return sorted(indices)
|
||||
|
||||
|
||||
def parse_html_grid(html: str, *, table_id: str) -> HtmlGrid:
|
||||
"""
|
||||
展开 HTML table 的 rowspan/colspan 为矩形网格。
|
||||
|
||||
@@ -13,6 +13,7 @@ import hashlib
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
@@ -27,6 +28,14 @@ _LOGGER = logging.getLogger(__name__)
|
||||
LAYOUT_PARSER_NAME = 'mineru'
|
||||
LAYOUT_BACKEND = 'pipeline'
|
||||
LAYOUT_CONTRACT_VERSION = 'shipping_document_table_snapshot.v1'
|
||||
LAYOUT_FINGERPRINT_FILES = (
|
||||
'contracts.py',
|
||||
'coordinate_table_reconstruction.py',
|
||||
'html_table.py',
|
||||
'mineru.py',
|
||||
'native_pdf.py',
|
||||
'runtime.py',
|
||||
)
|
||||
CURRENT_LAYOUT_STATUSES = frozenset({'ready', 'needs_review'})
|
||||
TERMINAL_LAYOUT_STATUSES = frozenset({'ready', 'needs_review', 'failed', 'unsupported'})
|
||||
|
||||
@@ -122,12 +131,36 @@ def _sync_workflow_item_for_layout(
|
||||
)
|
||||
|
||||
|
||||
def layout_parser_implementation_fingerprint() -> str:
|
||||
"""
|
||||
计算影响布局快照的源码与输出配置指纹,替代人工维护 parser revision。
|
||||
|
||||
核心逻辑:仅哈希布局解析组件和会改变快照内容的限制参数;聊天、前端等无关代码
|
||||
不会让 PDF 缓存失效。文件缺失时写入明确占位,避免不同节点静默产生同一身份。
|
||||
|
||||
Returns:
|
||||
16 位十六进制内容指纹;相同部署输入必然得到相同值。
|
||||
"""
|
||||
digest = hashlib.sha256()
|
||||
module_dir = Path(__file__).resolve().parent
|
||||
for filename in LAYOUT_FINGERPRINT_FILES:
|
||||
path = module_dir / filename
|
||||
digest.update(filename.encode('utf-8'))
|
||||
source = path.read_bytes().replace(b'\r\n', b'\n') if path.is_file() else b'<missing>'
|
||||
digest.update(source)
|
||||
output_config = {
|
||||
'max_html_chars': int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS', 1_000_000,
|
||||
)),
|
||||
}
|
||||
digest.update(json.dumps(output_config, sort_keys=True, separators=(',', ':')).encode('utf-8'))
|
||||
return digest.hexdigest()[:16]
|
||||
|
||||
|
||||
def current_layout_parser_key() -> str:
|
||||
"""生成运维可轮转的 parser 身份;Provider/模型升级必须提升 revision 防止复用旧结果。"""
|
||||
revision = str(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_PARSER_REVISION', 'v3',
|
||||
) or 'v3').strip()
|
||||
return f'{LAYOUT_PARSER_NAME}:{LAYOUT_BACKEND}:{LAYOUT_CONTRACT_VERSION}:{revision}'
|
||||
"""用布局合同和实现内容指纹生成 parser 身份,代码或输出配置变化时自动失效缓存。"""
|
||||
fingerprint = layout_parser_implementation_fingerprint()
|
||||
return f'{LAYOUT_PARSER_NAME}:{LAYOUT_BACKEND}:{LAYOUT_CONTRACT_VERSION}:sha256-{fingerprint}'
|
||||
|
||||
|
||||
def canonical_layout_payload(payload: dict[str, Any]) -> tuple[str, int]:
|
||||
|
||||
@@ -581,17 +581,23 @@ def _page_sizes(middle_json: Any, model_output: Any) -> dict[int, tuple[float, f
|
||||
|
||||
|
||||
def _table_candidates(content_list: Any, *, page_sizes: dict[int, tuple[float, float]]) -> list[MinerUTableCandidate]:
|
||||
"""从 content_list 提取 HTML 表格,并将 MinerU 0..1000 画布坐标映射到 PDF 页面。"""
|
||||
"""
|
||||
从 content_list 提取 HTML 表格,并将 MinerU 0..1000 画布坐标映射到 PDF 页面。
|
||||
|
||||
核心逻辑:兼容 MinerU 同步/异步结果使用 table_body、table_html 或 html 字段;
|
||||
显式 HTML 表格即使 type 缺失也可作为候选,但仍必须同时具备合法 bbox 和页尺寸。
|
||||
"""
|
||||
result: list[MinerUTableCandidate] = []
|
||||
seen: set[str] = set()
|
||||
for item in _walk_dicts(content_list):
|
||||
if str(item.get('type') or '').lower() != 'table':
|
||||
html = _table_html(item)
|
||||
content_type = str(item.get('type') or item.get('content_type') or '').strip().lower()
|
||||
if 'table' not in content_type and html is None:
|
||||
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
|
||||
page_no = _content_page_no(item)
|
||||
size = page_sizes.get(page_no)
|
||||
if size is None:
|
||||
continue
|
||||
@@ -620,6 +626,27 @@ def _table_candidates(content_list: Any, *, page_sizes: dict[int, tuple[float, f
|
||||
return result
|
||||
|
||||
|
||||
def _table_html(item: dict[str, Any]) -> str | None:
|
||||
"""读取 MinerU 不同版本的整表 HTML 字段,只接受真实 table 标签。"""
|
||||
values = [item.get('table_body'), item.get('table_html'), item.get('html')]
|
||||
nested = item.get('table')
|
||||
if isinstance(nested, dict):
|
||||
values.extend((nested.get('table_body'), nested.get('table_html'), nested.get('html')))
|
||||
for value in values:
|
||||
if isinstance(value, str) and BeautifulSoup(value, 'html.parser').find('table') is not None:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _content_page_no(item: dict[str, Any]) -> int:
|
||||
"""兼容 content_list 的 0-based page_idx/page_index 与 1-based page_no。"""
|
||||
if item.get('page_idx') is not None:
|
||||
return _as_int(item.get('page_idx'), default=0) + 1
|
||||
if item.get('page_index') is not None:
|
||||
return _as_int(item.get('page_index'), default=0) + 1
|
||||
return max(_as_int(item.get('page_no'), default=1), 1)
|
||||
|
||||
|
||||
def _text_candidates(content_list: Any, *, page_sizes: dict[int, tuple[float, float]]) -> list[MinerUTextCandidate]:
|
||||
"""提取非表格文本块,并将 MinerU 0..1000 画布坐标映射到 PDF 页面。"""
|
||||
result: list[MinerUTextCandidate] = []
|
||||
|
||||
@@ -9,6 +9,7 @@ backend/app/services/shipping_notice/document_layout/native_pdf.py
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from html import escape
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
@@ -43,23 +44,40 @@ from app.services.shipping_notice.document_layout.text_cell_alignment import (
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NativePdfPage:
|
||||
"""保存单页原生字符和渲染图;对象仅在 Worker 内存中存在。"""
|
||||
"""保存单页原生字符和可选渲染图;文字快速路径不承担页面渲染成本。"""
|
||||
|
||||
page_no: int
|
||||
width: float
|
||||
height: float
|
||||
rotation: int
|
||||
characters: list[PositionedCharacter]
|
||||
image: np.ndarray
|
||||
image: np.ndarray | None
|
||||
|
||||
|
||||
def extract_native_pdf_pages(content: bytes, *, render_scale: float = 2.0) -> list[NativePdfPage]:
|
||||
_FALLBACK_HEADER_TERM_GROUPS = (
|
||||
('item', 'position', 'pos', 'line'),
|
||||
('material', 'partnumber', 'partno', 'article', 'product', 'sku'),
|
||||
('description', 'designation'),
|
||||
('manufacturer', 'maker', 'vendorpartnumber', 'supplierpartnumber'),
|
||||
('quantity', 'qty', 'orderqty'),
|
||||
('deliverydate', 'delivery', 'requesteddate', 'reqdate', 'date'),
|
||||
('unitprice', 'price', 'amount', 'value'),
|
||||
('unit', 'uom'),
|
||||
('incoterm', 'remark', 'remarks'),
|
||||
)
|
||||
_FALLBACK_TOTAL_TERMS = ('total', 'grandtotal', 'totalamount', 'subtotal')
|
||||
|
||||
|
||||
def extract_native_pdf_pages(
|
||||
content: bytes, *, render_scale: float = 2.0, render_images: bool = True,
|
||||
) -> list[NativePdfPage]:
|
||||
"""
|
||||
从 PDF bytes 提取左上原点字符坐标和页面图。
|
||||
|
||||
Args:
|
||||
content: 原始 PDF 字节,不写文件和日志。
|
||||
render_scale: OpenCV 网格检测使用的渲染倍率,必须为正数。
|
||||
render_images: 是否渲染页面图;纯文字表格快速路径传 False。
|
||||
Returns:
|
||||
连续页列表;扫描 PDF 可返回无字符页面,但仍保留页面尺寸和图像。
|
||||
Raises:
|
||||
@@ -98,17 +116,198 @@ def extract_native_pdf_pages(content: bytes, *, render_scale: float = 2.0) -> li
|
||||
height=float(height),
|
||||
rotation=rotation if rotation in {0, 90, 180, 270} else 0,
|
||||
characters=characters,
|
||||
image=np.asarray(page.render(scale=render_scale).to_numpy()).copy(),
|
||||
image=(
|
||||
np.asarray(page.render(scale=render_scale).to_numpy()).copy()
|
||||
if render_images else None
|
||||
),
|
||||
))
|
||||
return pages
|
||||
|
||||
|
||||
def build_native_pdf_text_table_fallbacks(
|
||||
content: bytes,
|
||||
*,
|
||||
native_pages: list[NativePdfPage] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从有原生文字层但被 MinerU 归类为普通文本的 PDF 中恢复候选明细表。
|
||||
|
||||
AI/调用方触发时机:仅 MinerU 没有输出任何表格时由布局运行时调用。按订单表头
|
||||
同义词组和列几何建立候选,并要求后续正文含数字型多列数据;不能证明时返回空。
|
||||
"""
|
||||
result: list[dict[str, Any]] = []
|
||||
resolved_pages = native_pages if native_pages is not None else extract_native_pdf_pages(content)
|
||||
for page in resolved_pages:
|
||||
lines = _native_text_lines(page.characters)
|
||||
header = _fallback_header_window(lines)
|
||||
if header is None:
|
||||
continue
|
||||
start_index, end_index = header
|
||||
header_lines = lines[start_index:end_index + 1]
|
||||
body_lines = lines[end_index + 1:]
|
||||
stop_index = next((
|
||||
index for index, line in enumerate(body_lines)
|
||||
if _is_fallback_total(line) or _is_fallback_separator(line)
|
||||
), len(body_lines))
|
||||
body_lines = body_lines[:stop_index]
|
||||
if not body_lines:
|
||||
continue
|
||||
boundaries = _fallback_column_boundaries(header_lines, page.width)
|
||||
if len(boundaries) < 3:
|
||||
continue
|
||||
header_cells = _fallback_cells(header_lines, boundaries)
|
||||
body_cells = [_fallback_cells([line], boundaries) for line in body_lines]
|
||||
if not any(_fallback_data_row(row) for row in body_cells):
|
||||
continue
|
||||
x0, y0 = 0.0, header_lines[0]['y0']
|
||||
x1 = page.width
|
||||
y1 = body_lines[-1]['y1']
|
||||
if y1 <= y0:
|
||||
continue
|
||||
result.append({
|
||||
'table_id': f'native-text-table-p{page.page_no}-{len(result) + 1}',
|
||||
'page_no': page.page_no,
|
||||
'bbox': {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1},
|
||||
'normalized_bbox': {'x0': 0, 'y0': y0 / page.height, 'x1': 1, 'y1': y1 / page.height},
|
||||
'html': _fallback_table_html(header_cells, body_cells),
|
||||
'row_count': 1 + len(body_cells),
|
||||
'cell_count': len(header_cells) + sum(len(row) for row in body_cells),
|
||||
'has_rowspan': False, 'has_colspan': False,
|
||||
'source': 'native_pdf_text_header_fallback',
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def _native_text_lines(characters: list[PositionedCharacter]) -> list[dict[str, Any]]:
|
||||
"""按紧邻基线聚合原生 glyph,保留横坐标供无框表的列分配使用。"""
|
||||
lines: list[list[PositionedCharacter]] = []
|
||||
for glyph in sorted(characters, key=lambda item: ((item.bbox.y0 + item.bbox.y1) / 2, item.bbox.x0)):
|
||||
center_y = (glyph.bbox.y0 + glyph.bbox.y1) / 2
|
||||
if not lines or abs(center_y - ((lines[-1][0].bbox.y0 + lines[-1][0].bbox.y1) / 2)) > 3:
|
||||
lines.append([glyph])
|
||||
else:
|
||||
lines[-1].append(glyph)
|
||||
return [{
|
||||
'glyphs': line,
|
||||
'text': ''.join(item.text for item in line),
|
||||
'normalized': normalize_layout_text(''.join(item.text for item in line)),
|
||||
'y0': min(item.bbox.y0 for item in line), 'y1': max(item.bbox.y1 for item in line),
|
||||
} for line in lines if line]
|
||||
|
||||
|
||||
def _fallback_header_window(lines: list[dict[str, Any]]) -> tuple[int, int] | None:
|
||||
"""
|
||||
寻找订单语义可证明的连续表头区,拒绝单个业务字段和普通段落猜测。
|
||||
|
||||
核心逻辑:首行至少命中两个订单列语义组;达到三个直接接受,否则只向下合并
|
||||
连续且仍含表头语义的视觉行,避免把首条数据并入表头。
|
||||
"""
|
||||
for start in range(len(lines)):
|
||||
first_hits = _fallback_header_groups(lines[start])
|
||||
# 表头首行必须自身提供多列证据,防止把付款条款等邻近文本并入表格。
|
||||
if len(first_hits) < 2:
|
||||
continue
|
||||
if len(first_hits) >= 3:
|
||||
return start, start
|
||||
hits: set[str] = set(first_hits)
|
||||
last = start
|
||||
for end in range(start + 1, min(start + 4, len(lines))):
|
||||
if float(lines[end]['y1']) - float(lines[start]['y0']) > 110:
|
||||
break
|
||||
if end > start and float(lines[end]['y0']) - float(lines[end - 1]['y1']) >= 8:
|
||||
break
|
||||
line_hits = _fallback_header_groups(lines[end])
|
||||
if not line_hits:
|
||||
break
|
||||
hits.update(line_hits)
|
||||
last = end
|
||||
if len(hits) >= 3:
|
||||
return start, last
|
||||
if len(hits) >= 3:
|
||||
return start, last
|
||||
return None
|
||||
|
||||
|
||||
def _fallback_header_groups(line: dict[str, Any]) -> set[str]:
|
||||
"""按同义词组统计订单表头维度,避免 Quantity/Qty 等重复别名虚增证据。"""
|
||||
normalized = ''.join(str(line.get('normalized') or '').casefold().split())
|
||||
return {
|
||||
str(index) for index, terms in enumerate(_FALLBACK_HEADER_TERM_GROUPS)
|
||||
if any(term in normalized for term in terms)
|
||||
}
|
||||
|
||||
|
||||
def _is_fallback_total(line: dict[str, Any]) -> bool:
|
||||
"""合计行只用于限制候选表范围,避免页脚或后续说明被误收为明细。"""
|
||||
normalized = str(line['normalized']).lower()
|
||||
return any(term in normalized for term in _FALLBACK_TOTAL_TERMS)
|
||||
|
||||
|
||||
def _is_fallback_separator(line: dict[str, Any]) -> bool:
|
||||
"""把横线分隔符视为表尾;紧邻表头的分隔符会使无数据页拒绝生成候选。"""
|
||||
text = ''.join(str(line.get('text') or '').split())
|
||||
return len(text) >= 20 and set(text) <= {'_', '-', '='}
|
||||
|
||||
|
||||
def _fallback_column_boundaries(header_lines: list[dict[str, Any]], page_width: float) -> list[float]:
|
||||
"""从表头文字起点形成稀疏列边界;没有至少两列共识即关闭兜底。"""
|
||||
positions = sorted({round(word['x0'], 1) for line in header_lines for word in _line_words(line['glyphs'])})
|
||||
starts: list[float] = []
|
||||
for value in positions:
|
||||
if not starts or value - starts[-1] >= max(page_width * .055, 24):
|
||||
starts.append(value)
|
||||
if len(starts) < 2:
|
||||
return []
|
||||
boundaries = [0.0] + [(left + right) / 2 for left, right in zip(starts, starts[1:])] + [page_width]
|
||||
return boundaries if all(left < right for left, right in zip(boundaries, boundaries[1:])) else []
|
||||
|
||||
|
||||
def _fallback_cells(lines: list[dict[str, Any]], boundaries: list[float]) -> list[str]:
|
||||
"""按字符中心点投影到表头推导列;跨视觉行的文字在同列内合并。"""
|
||||
values = [[] for _ in range(len(boundaries) - 1)]
|
||||
for line in lines:
|
||||
for word in _line_words(line['glyphs']):
|
||||
center = (word['x0'] + word['x1']) / 2
|
||||
index = next((item for item in range(len(values)) if boundaries[item] <= center <= boundaries[item + 1]), None)
|
||||
if index is not None:
|
||||
values[index].append(word['text'])
|
||||
return [' '.join(value).strip() for value in values]
|
||||
|
||||
|
||||
def _fallback_data_row(row: list[str]) -> bool:
|
||||
"""要求候选正文至少一行同时含数字和两个非空列,重复表头或说明行不得成表。"""
|
||||
populated = [value for value in row if value]
|
||||
return len(populated) >= 2 and any(any(char.isdigit() for char in value) for value in populated)
|
||||
|
||||
|
||||
def _line_words(glyphs: list[PositionedCharacter]) -> list[dict[str, Any]]:
|
||||
"""按字符间隙聚合为视觉词,避免每个字母被误作一列起点。"""
|
||||
words: list[list[PositionedCharacter]] = []
|
||||
for glyph in sorted(glyphs, key=lambda item: item.bbox.x0):
|
||||
if not words or glyph.bbox.x0 - words[-1][-1].bbox.x1 > 2.5:
|
||||
words.append([glyph])
|
||||
else:
|
||||
words[-1].append(glyph)
|
||||
return [{
|
||||
'text': ''.join(item.text for item in word),
|
||||
'x0': word[0].bbox.x0, 'x1': word[-1].bbox.x1,
|
||||
} for word in words]
|
||||
|
||||
|
||||
def _fallback_table_html(header: list[str], rows: list[list[str]]) -> str:
|
||||
"""生成结构受控的普通 HTML 表格,供现有样本选择和人工坐标配置流程复用。"""
|
||||
head = ''.join(f'<th>{escape(value or f'column_{index + 1}')}</th>' for index, value in enumerate(header))
|
||||
body = ''.join('<tr>' + ''.join(f'<td>{escape(value)}</td>' for value in row) + '</tr>' for row in rows)
|
||||
return f'<table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table>'
|
||||
|
||||
|
||||
def build_native_pdf_layout_candidate(
|
||||
*,
|
||||
document_id: int,
|
||||
content_hash: str,
|
||||
content: bytes,
|
||||
mineru: MinerUParseCandidate,
|
||||
native_pages: list[NativePdfPage] | None = None,
|
||||
) -> LayoutDocument:
|
||||
"""
|
||||
组合 MinerU HTML 与 PDFium 独立证据,生成始终 needs_review 的 layout.v1 候选。
|
||||
@@ -118,16 +317,17 @@ def build_native_pdf_layout_candidate(
|
||||
content_hash: 当前附件 SHA-256,用于稳定 ID 和契约校验。
|
||||
content: 原始 PDF 字节。
|
||||
mineru: 同一文件的 MinerU pipeline 候选。
|
||||
native_pages: 可复用的 PDFium 页面;未传入时由本函数提取。
|
||||
Returns:
|
||||
通过完整布局契约校验的候选;没有可证 cell 时保留空表和 blocking issue。
|
||||
"""
|
||||
native_pages = extract_native_pdf_pages(content)
|
||||
resolved_pages = native_pages if native_pages is not None else extract_native_pdf_pages(content)
|
||||
mineru_pages = {item.page_no: item for item in mineru.pages}
|
||||
issues: list[LayoutIssue] = [LayoutIssue(
|
||||
code='document_cell_truth_deferred', severity='blocking',
|
||||
)]
|
||||
pages: list[LayoutPage] = []
|
||||
for native in native_pages:
|
||||
for native in resolved_pages:
|
||||
page_candidate = mineru_pages.get(native.page_no)
|
||||
tables: list[LayoutTable] = []
|
||||
page_tokens: dict[str, LayoutToken] = {}
|
||||
@@ -211,6 +411,9 @@ def _candidate_cells(
|
||||
}
|
||||
for item in alignment.cells
|
||||
}, ['native_pdf_cells_from_unique_text_candidate']
|
||||
if native.image is None:
|
||||
# 快速路径只允许原生文字的严格唯一对齐;不足时由调用方回退完整 MinerU/图像链路。
|
||||
return {}, sorted(set(alignment.issues + ['native_pdf_render_deferred']))
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
native.image, page_width=native.width, page_height=native.height,
|
||||
table_bbox=table_bbox, grid=grid,
|
||||
|
||||
@@ -174,7 +174,11 @@ def _read_value_region(
|
||||
值框是字段边界的主证据。即使 ``right_of_anchor`` 也不跨出该边界补字,
|
||||
以免相邻字段的临界字符混入当前字段并与画布标注不一致。
|
||||
"""
|
||||
selected = [(index, item) for index, item in enumerate(glyphs) if _glyph_center_inside(item, region)]
|
||||
tolerate_rendering_error = layout.absolute_value_region is not None or str(config.get('value_type') or '') != 'date'
|
||||
selected = [
|
||||
(index, item) for index, item in enumerate(glyphs)
|
||||
if _glyph_center_inside(item, region, tolerate_rendering_error=tolerate_rendering_error)
|
||||
]
|
||||
if layout.value_mode == 'multi_line':
|
||||
selected = _stop_before_anchor(
|
||||
selected, glyphs=glyphs, stop_anchors=layout.stop_anchors, anchor_bbox=anchor_bbox,
|
||||
@@ -459,7 +463,7 @@ def _absolute_relative_region(region: RelativeRegion | None, *, width: float, he
|
||||
|
||||
|
||||
def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutBBox) -> LayoutBBox:
|
||||
"""用标签框宽高投影相对值区,使整页平移或缩放不改变读取关系。"""
|
||||
"""仅为历史相对值框恢复页面区域;新模板不调用此换算保存坐标。"""
|
||||
if region is None:
|
||||
raise ValueError('anchored order field region is required')
|
||||
width, height = anchor.x1 - anchor.x0, anchor.y1 - anchor.y0
|
||||
@@ -470,41 +474,54 @@ def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutB
|
||||
|
||||
|
||||
def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float) -> LayoutBBox:
|
||||
"""读取值区;旧版“标签右侧/下方”绝对框自动转换为可移动相对框。"""
|
||||
"""读取管理员值框;右侧/下方字段只随标签平移,绝不按标签框尺寸缩放。"""
|
||||
if layout.value_region is not None:
|
||||
region = _absolute_anchor_region(layout.value_region, anchor)
|
||||
if layout.value_mode == 'right_of_anchor':
|
||||
# The left edge of a right-side field is semantic, not a canvas
|
||||
# gap: start at the matched label so font-width differences cannot
|
||||
# discard the first value character on another document.
|
||||
return LayoutBBox(x0=anchor.x1, y0=region.y0, x1=region.x1, y1=region.y1)
|
||||
return region
|
||||
if _uses_movable_anchor_value_region(layout=layout, width=width, height=height):
|
||||
# Historical canvas persisted a page box even when the UI said "right of
|
||||
# anchor". Rebase it onto the actual label to retain that relationship.
|
||||
if layout.anchor is None or layout.anchor.region is None:
|
||||
return _absolute_anchor_region(layout.value_region, anchor)
|
||||
if layout.value_mode not in {'right_of_anchor', 'below_anchor'}:
|
||||
return _absolute_anchor_region(layout.value_region, anchor)
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
|
||||
saved = _absolute_anchor_region(layout.value_region, reference)
|
||||
if layout.value_mode == 'right_of_anchor':
|
||||
region = _absolute_anchor_region(layout.value_region, anchor)
|
||||
reference_width = max(saved.x1 - reference.x1, 0)
|
||||
projected_width = max(region.x1 - anchor.x1, reference_width)
|
||||
return LayoutBBox(
|
||||
x0=anchor.x1, y0=region.y0,
|
||||
x1=anchor.x1 + projected_width, y1=region.y1,
|
||||
)
|
||||
elif layout.absolute_value_region is not None:
|
||||
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
|
||||
reference_width = reference.x1 - reference.x0
|
||||
reference_height = reference.y1 - reference.y0
|
||||
relative = AnchorRelativeRegion(
|
||||
# The old canvas selected a page box, whose left gap depends on
|
||||
# preceding text. The mode itself is the durable intent: begin at
|
||||
# the matched label's right edge and retain the configured extent.
|
||||
x0=1,
|
||||
y0=0,
|
||||
x1=1 + (saved.x1 - reference.x1) / reference_width,
|
||||
y1=1,
|
||||
)
|
||||
return _absolute_anchor_region(relative, anchor)
|
||||
if layout.absolute_value_region is not None:
|
||||
return _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
|
||||
raise ValueError('anchored order field has no value region')
|
||||
if layout.anchor is None or layout.anchor.region is None:
|
||||
return saved
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
|
||||
else:
|
||||
raise ValueError('anchored order field has no value region')
|
||||
if layout.value_mode not in {'right_of_anchor', 'below_anchor'}:
|
||||
return saved
|
||||
anchor_center_x, anchor_center_y = (anchor.x0 + anchor.x1) / 2, (anchor.y0 + anchor.y1) / 2
|
||||
if _regions_overlap(anchor, reference):
|
||||
return saved
|
||||
if layout.absolute_value_region is not None and not _uses_movable_anchor_value_region(
|
||||
layout=layout, width=width, height=height,
|
||||
):
|
||||
return saved
|
||||
if layout.value_mode == 'right_of_anchor':
|
||||
offset_x = anchor.x1 - reference.x1
|
||||
offset_y = anchor_center_y - (reference.y0 + reference.y1) / 2
|
||||
else:
|
||||
offset_x = anchor_center_x - (reference.x0 + reference.x1) / 2
|
||||
offset_y = anchor.y1 - reference.y1
|
||||
return LayoutBBox(
|
||||
x0=saved.x0 + offset_x, y0=saved.y0 + offset_y,
|
||||
x1=saved.x1 + offset_x, y1=saved.y1 + offset_y,
|
||||
)
|
||||
|
||||
|
||||
def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float, height: float) -> bool:
|
||||
"""判断新相对规则或同一行的旧右侧框是否应跟随实际标签移动。"""
|
||||
if layout.value_region is not None:
|
||||
return True
|
||||
return layout.value_mode in {'right_of_anchor', 'below_anchor'}
|
||||
if (
|
||||
layout.absolute_value_region is None or layout.anchor is None or layout.anchor.region is None
|
||||
or layout.value_mode not in {'right_of_anchor', 'below_anchor'}
|
||||
@@ -516,18 +533,31 @@ def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float,
|
||||
return saved.y0 <= reference.y1 + tolerance and reference.y0 <= saved.y1 + tolerance
|
||||
|
||||
|
||||
def _regions_overlap(left: LayoutBBox, right: LayoutBBox) -> bool:
|
||||
"""判断两个坐标框是否相交;实际标签仍在管理员紫框内时不应移动绿色值框。"""
|
||||
return left.x0 <= right.x1 and right.x0 <= left.x1 and left.y0 <= right.y1 and right.y0 <= left.y1
|
||||
|
||||
|
||||
def _glyph_bbox(glyph: dict[str, Any]) -> LayoutBBox:
|
||||
"""严格解析一枚冻结 glyph 的 bbox;坏坐标不会被修正后参与提取。"""
|
||||
return LayoutBBox.model_validate(glyph.get('bbox'))
|
||||
|
||||
|
||||
def _glyph_center_inside(glyph: dict[str, Any], region: LayoutBBox) -> bool:
|
||||
"""判断字符中心是否处于值区,边界字符仍归属到管理员确认的区域。"""
|
||||
def _glyph_center_inside(
|
||||
glyph: dict[str, Any], region: LayoutBBox, *, tolerate_rendering_error: bool = False,
|
||||
) -> bool:
|
||||
"""判断字符中心是否处于区域;管理员绝对框可选择容忍小幅 PDF 渲染误差。"""
|
||||
try:
|
||||
bbox = _glyph_bbox(glyph)
|
||||
except Exception:
|
||||
return False
|
||||
return region.x0 <= (bbox.x0 + bbox.x1) / 2 <= region.x1 and region.y0 <= (bbox.y0 + bbox.y1) / 2 <= region.y1
|
||||
center_x, center_y = (bbox.x0 + bbox.x1) / 2, (bbox.y0 + bbox.y1) / 2
|
||||
tolerance_x = max(bbox.x1 - bbox.x0, 0) * .25 if tolerate_rendering_error else 0
|
||||
tolerance_y = max(bbox.y1 - bbox.y0, 0) * .25 if tolerate_rendering_error else 0
|
||||
return (
|
||||
region.x0 - tolerance_x <= center_x <= region.x1 + tolerance_x
|
||||
and region.y0 - tolerance_y <= center_y <= region.y1 + tolerance_y
|
||||
)
|
||||
|
||||
|
||||
def _union_bbox(glyphs: list[dict[str, Any]]) -> LayoutBBox:
|
||||
|
||||
@@ -63,10 +63,8 @@ class RelativeRegion(OrderProfileModel):
|
||||
|
||||
|
||||
class AnchorRelativeRegion(OrderProfileModel):
|
||||
"""表示相对锚点框宽高的值区偏移;允许标签右侧或下方落在锚点外。"""
|
||||
"""仅接收历史锚点相对值框;新模板统一保存 absolute_value_region。"""
|
||||
|
||||
# Address values can be much wider than short labels such as "BILL TO".
|
||||
# Keep a finite bound while accepting the deterministic suggestion geometry.
|
||||
x0: float = Field(ge=-12, le=12)
|
||||
y0: float = Field(ge=-12, le=12)
|
||||
x1: float = Field(ge=-12, le=12)
|
||||
@@ -74,7 +72,7 @@ class AnchorRelativeRegion(OrderProfileModel):
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_area(self) -> 'AnchorRelativeRegion':
|
||||
"""拒绝零面积和反向偏移区域,确保运行期投影只有一个解释。"""
|
||||
"""拒绝零面积和反向历史偏移,避免兼容读取产生不确定区域。"""
|
||||
if self.x0 >= self.x1 or self.y0 >= self.y1:
|
||||
raise ValueError('anchor-relative region must have positive area')
|
||||
return self
|
||||
@@ -112,9 +110,7 @@ class OrderFieldLayout(OrderProfileModel):
|
||||
page_scope: Literal['first_page', 'all_pages', 'exact_page'] = 'first_page'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
anchor: AnchorRule | None = None
|
||||
# ``absolute_value_region`` is the authoritative administrator-drawn page box.
|
||||
# ``value_region`` remains only for legacy profiles whose values were stored as
|
||||
# offsets relative to the anchor bbox.
|
||||
# 新模板只写 absolute_value_region;value_region 仅用于清理前的历史输入。
|
||||
value_region: AnchorRelativeRegion | None = None
|
||||
absolute_value_region: RelativeRegion | None = None
|
||||
fallback_value_region: RelativeRegion | None = None
|
||||
@@ -268,6 +264,8 @@ class TableRegionProfile(OrderProfileModel):
|
||||
region: RelativeRegion
|
||||
# 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。
|
||||
line_start_field_code: str = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
# 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。
|
||||
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows'
|
||||
header_layouts: list[HeaderLayout] = Field(default_factory=list)
|
||||
line_layouts: list[LineLayout] = Field(default_factory=list)
|
||||
continuation_rule: ContinuationRule = Field(default_factory=ContinuationRule)
|
||||
@@ -320,6 +318,46 @@ class TableRegionProfile(OrderProfileModel):
|
||||
return self
|
||||
|
||||
|
||||
SCORING_DIMENSION_KEYS = (
|
||||
'table_topology',
|
||||
'row_structure',
|
||||
'anchor_geometry',
|
||||
'header_regions',
|
||||
'page_structure',
|
||||
'header_path',
|
||||
'customer_hint',
|
||||
)
|
||||
CRITICAL_STRUCTURE_DIMENSION_KEYS = ('table_topology', 'row_structure', 'anchor_geometry')
|
||||
|
||||
|
||||
class ProfileScoringWeights(OrderProfileModel):
|
||||
"""分项权重;七维之和必须为 1.0,供 matcher 加权汇总确定性评分。"""
|
||||
|
||||
table_topology: float = Field(default=0.25, ge=0, le=1)
|
||||
row_structure: float = Field(default=0.20, ge=0, le=1)
|
||||
anchor_geometry: float = Field(default=0.20, ge=0, le=1)
|
||||
header_regions: float = Field(default=0.10, ge=0, le=1)
|
||||
page_structure: float = Field(default=0.10, ge=0, le=1)
|
||||
header_path: float = Field(default=0.10, ge=0, le=1)
|
||||
customer_hint: float = Field(default=0.05, ge=0, le=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_weight_sum(self) -> 'ProfileScoringWeights':
|
||||
"""拒绝权重和偏离 1.0 的配置,避免运行时隐式归一化掩盖模板治理问题。"""
|
||||
total = sum(getattr(self, key) for key in SCORING_DIMENSION_KEYS)
|
||||
if abs(total - 1.0) > 0.001:
|
||||
raise ValueError('scoring dimension weights must sum to 1.0')
|
||||
return self
|
||||
|
||||
|
||||
class ProfileScoringThresholds(OrderProfileModel):
|
||||
"""自动决胜与关键结构单项阈值;与 minimum_score/minimum_margin 并存,服务多候选评分决胜。"""
|
||||
|
||||
auto_select_minimum_score: float = Field(default=0.95, ge=0, le=1)
|
||||
auto_select_minimum_margin: float = Field(default=0.15, ge=0, le=1)
|
||||
critical_structure_minimum: float = Field(default=0.90, ge=0, le=1)
|
||||
|
||||
|
||||
class DocumentMatchAnchor(OrderProfileModel):
|
||||
"""文档匹配锚点以管理员框选的标签和值区域验证关系,禁止全文纯文本命中。"""
|
||||
|
||||
@@ -342,6 +380,8 @@ class DocumentMatchProfile(OrderProfileModel):
|
||||
optional_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
|
||||
minimum_score: float = Field(default=0.9, ge=0, le=1)
|
||||
minimum_margin: float = Field(default=0.15, ge=0, le=1)
|
||||
scoring_weights: ProfileScoringWeights = Field(default_factory=ProfileScoringWeights)
|
||||
scoring_thresholds: ProfileScoringThresholds = Field(default_factory=ProfileScoringThresholds)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_anchor_ids(self) -> 'DocumentMatchProfile':
|
||||
|
||||
@@ -12,6 +12,7 @@ import re
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from app.services.shipping_notice.notice_lines import resolve_composite_part_numbers
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
_NUMBER_UNIT = re.compile(r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*([A-Za-z]{1,12})\s*$')
|
||||
@@ -21,11 +22,14 @@ _CURRENCY_SYMBOLS = {'$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'CNY'}
|
||||
|
||||
|
||||
def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str) -> dict[str, str]:
|
||||
"""将一个已确认区域按注册解析器拆分;不允许调用方传入规则、脚本或正则。"""
|
||||
"""将已确认区域按注册解析器拆分,并把预约单号统一为合法纯数字。"""
|
||||
text = str(raw or '').strip()
|
||||
if not text:
|
||||
return {}
|
||||
if extractor_key == 'direct':
|
||||
if field_code == 'reservation_id':
|
||||
value = validated_reservation_id(text)
|
||||
return {field_code: value} if value else {}
|
||||
return {field_code: text}
|
||||
if extractor_key == 'temp_internal_parts':
|
||||
resolved = resolve_composite_part_numbers(text)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
|
||||
用途:以冻结的页面坐标证据唯一匹配订单坐标模板。
|
||||
依赖:OrderCoordinateProfileV2 和布局快照。逻辑:必需锚点与表区数量先作为硬条件,
|
||||
可选锚点只参与评分;没有达到阈值或分差的候选绝不进入确定性解析。
|
||||
用途:以冻结的页面坐标证据唯一匹配订单坐标模板,并按分项权重做确定性综合评分。
|
||||
依赖:OrderCoordinateProfileV2、order_extraction_route_contract 评分策略版本。
|
||||
逻辑:必需锚点与表区数量先作为硬条件;分项得分只使用结构/锚点/页域证据;未达到阈值或
|
||||
分差的候选绝不进入确定性解析;漂移与无异型特征严格区分。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,7 +13,13 @@ from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfileV2
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
CRITICAL_STRUCTURE_DIMENSION_KEYS,
|
||||
OrderCoordinateProfileV2,
|
||||
SCORING_DIMENSION_KEYS,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
|
||||
from app.services.shipping_notice.order_extraction_route_contract import PROFILE_SCORING_POLICY_VERSION
|
||||
|
||||
|
||||
def _anchor_comparable_text(value: Any) -> str:
|
||||
@@ -20,6 +27,20 @@ def _anchor_comparable_text(value: Any) -> str:
|
||||
return ''.join(str(value or '').casefold().split())
|
||||
|
||||
|
||||
class ProfileMatchDimensionScores(BaseModel):
|
||||
"""记录单个候选在七维评分上的非敏感得分。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
table_topology: float = Field(ge=0, le=1)
|
||||
row_structure: float = Field(ge=0, le=1)
|
||||
anchor_geometry: float = Field(ge=0, le=1)
|
||||
header_regions: float = Field(ge=0, le=1)
|
||||
page_structure: float = Field(ge=0, le=1)
|
||||
header_path: float = Field(ge=0, le=1)
|
||||
customer_hint: float = Field(ge=0, le=1)
|
||||
|
||||
|
||||
class ProfileMatchCandidate(BaseModel):
|
||||
"""记录单个冻结 Profile 的非敏感匹配分数和失败原因。"""
|
||||
|
||||
@@ -32,22 +53,51 @@ class ProfileMatchCandidate(BaseModel):
|
||||
reason_codes: list[str] = Field(default_factory=list)
|
||||
# Anchor IDs are template configuration identifiers, never document text.
|
||||
missing_required_anchor_ids: list[str] = Field(default_factory=list)
|
||||
dimension_scores: ProfileMatchDimensionScores | None = None
|
||||
margin_to_next: float | None = Field(default=None, ge=0, le=1)
|
||||
|
||||
|
||||
class ProfileMatchResult(BaseModel):
|
||||
"""文档级唯一匹配结果;只有 unique_match 可以启动坐标确定性解析。"""
|
||||
"""文档级唯一匹配结果;unique_match / selected_by_score 可启动坐标确定性解析。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
status: Literal['unique_match', 'no_match', 'ambiguous', 'layout_drift', 'evidence_insufficient']
|
||||
status: Literal[
|
||||
'unique_match',
|
||||
'selected_by_score',
|
||||
'no_special_profile_feature',
|
||||
'no_match',
|
||||
'ambiguous',
|
||||
'layout_drift',
|
||||
'evidence_insufficient',
|
||||
]
|
||||
profile_code: str | None = None
|
||||
version: int | None = None
|
||||
checksum: str | None = None
|
||||
candidates: list[ProfileMatchCandidate] = Field(default_factory=list)
|
||||
top1_score: float | None = Field(default=None, ge=0, le=1)
|
||||
top2_score: float | None = Field(default=None, ge=0, le=1)
|
||||
margin: float | None = Field(default=None, ge=0, le=1)
|
||||
scoring_policy_version: str = PROFILE_SCORING_POLICY_VERSION
|
||||
|
||||
|
||||
def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout: dict[str, Any]) -> ProfileMatchResult:
|
||||
"""对同一文档的冻结 Profile 做唯一匹配,业务值和上传时间均不参与计算。"""
|
||||
def match_frozen_coordinate_profiles(
|
||||
*,
|
||||
profiles: list[dict[str, Any]],
|
||||
layout: dict[str, Any],
|
||||
customer_hint_id: int | None = None,
|
||||
) -> ProfileMatchResult:
|
||||
"""
|
||||
对同一文档的冻结 Profile 做硬门禁、分项评分与唯一匹配;业务值和上传时间均不参与计算。
|
||||
|
||||
Args:
|
||||
profiles: 已发布模板快照列表;仅消费 v2 坐标契约。
|
||||
layout: 冻结 layout 快照,含 tables 与 coordinate_evidence。
|
||||
customer_hint_id: 可选运行期客户 ID,仅用于 customer_hint 维度弱提示。
|
||||
|
||||
Returns:
|
||||
ProfileMatchResult:含 Top1/Top2/Margin 与候选分项得分。
|
||||
"""
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
@@ -57,6 +107,7 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
|
||||
if not pages or (not glyph_tables and not page_glyphs):
|
||||
return ProfileMatchResult(status='evidence_insufficient')
|
||||
|
||||
page_text = _layout_page_text(tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages)
|
||||
candidates: list[tuple[dict[str, Any], OrderCoordinateProfileV2, ProfileMatchCandidate]] = []
|
||||
for raw in profiles:
|
||||
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
|
||||
@@ -81,35 +132,264 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
|
||||
if missing_required_anchor_ids:
|
||||
reason_codes.append('required_anchor_missing')
|
||||
optional = profile.document_match.optional_anchors
|
||||
optional_hits = sum(_anchor_present(
|
||||
anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
) for anchor in optional)
|
||||
optional_hits = [
|
||||
_anchor_present(
|
||||
anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
) for anchor in optional
|
||||
]
|
||||
hard_match = not reason_codes
|
||||
# Required evidence is mandatory rather than a soft score. Optional evidence only separates already valid templates.
|
||||
score = 1.0 if not optional else 0.8 + 0.2 * optional_hits / len(optional)
|
||||
dimension_scores = _compute_dimension_scores(
|
||||
profile=profile,
|
||||
tables=tables,
|
||||
pages=pages,
|
||||
required_hits=required_hits,
|
||||
optional_hits=optional_hits,
|
||||
page_text=page_text,
|
||||
customer_ids=raw.get('customer_ids') if isinstance(raw.get('customer_ids'), list) else None,
|
||||
customer_hint_id=customer_hint_id,
|
||||
)
|
||||
weights = profile.document_match.scoring_weights
|
||||
score = round(sum(
|
||||
getattr(weights, key) * getattr(dimension_scores, key) for key in SCORING_DIMENSION_KEYS
|
||||
), 6)
|
||||
if not hard_match:
|
||||
score = 0.0
|
||||
candidates.append((raw, profile, ProfileMatchCandidate(
|
||||
profile_code=profile.profile_code, version=profile.version, score=score if hard_match else 0.0,
|
||||
profile_code=profile.profile_code, version=profile.version, score=score,
|
||||
hard_match=hard_match, reason_codes=reason_codes,
|
||||
missing_required_anchor_ids=missing_required_anchor_ids,
|
||||
dimension_scores=dimension_scores,
|
||||
)))
|
||||
|
||||
rendered = sorted((item[2] for item in candidates), key=lambda item: (-item.score, item.profile_code, item.version))
|
||||
valid = sorted((item for item in candidates if item[2].hard_match), key=lambda item: (-item[2].score, item[1].profile_code, item[1].version))
|
||||
top1_score = rendered[0].score if rendered else None
|
||||
top2_score = rendered[1].score if len(rendered) > 1 else None
|
||||
margin = (
|
||||
round(top1_score - top2_score, 6)
|
||||
if top1_score is not None and top2_score is not None
|
||||
else (round(top1_score, 6) if top1_score is not None else None)
|
||||
)
|
||||
if margin is not None:
|
||||
for index, candidate in enumerate(rendered):
|
||||
next_score = rendered[index + 1].score if index + 1 < len(rendered) else 0.0
|
||||
candidate.margin_to_next = round(max(0.0, candidate.score - next_score), 6)
|
||||
|
||||
if not valid:
|
||||
status: Literal['no_match', 'layout_drift'] = 'layout_drift' if rendered else 'no_match'
|
||||
return ProfileMatchResult(status=status, candidates=rendered)
|
||||
if not rendered:
|
||||
return ProfileMatchResult(status='no_match', candidates=rendered, top1_score=top1_score, top2_score=top2_score, margin=margin)
|
||||
if _any_special_profile_feature(candidates, page_text=page_text):
|
||||
return ProfileMatchResult(status='layout_drift', candidates=rendered, top1_score=top1_score, top2_score=top2_score, margin=margin)
|
||||
return ProfileMatchResult(
|
||||
status='no_special_profile_feature', candidates=rendered,
|
||||
top1_score=top1_score, top2_score=top2_score, margin=margin,
|
||||
)
|
||||
|
||||
raw, profile, first = valid[0]
|
||||
if first.score < profile.document_match.minimum_score:
|
||||
return ProfileMatchResult(status='no_match', candidates=rendered)
|
||||
if len(valid) > 1 and first.score - valid[1][2].score < profile.document_match.minimum_margin:
|
||||
return ProfileMatchResult(status='ambiguous', candidates=rendered)
|
||||
return ProfileMatchResult(
|
||||
status='unique_match', profile_code=profile.profile_code, version=profile.version,
|
||||
checksum=str(raw.get('checksum') or ''), candidates=rendered,
|
||||
match_config = profile.document_match
|
||||
if first.score < match_config.minimum_score:
|
||||
return ProfileMatchResult(status='no_match', candidates=rendered, top1_score=top1_score, top2_score=top2_score, margin=margin)
|
||||
|
||||
if len(valid) == 1:
|
||||
return ProfileMatchResult(
|
||||
status='unique_match', profile_code=profile.profile_code, version=profile.version,
|
||||
checksum=str(raw.get('checksum') or ''), candidates=rendered,
|
||||
top1_score=top1_score, top2_score=top2_score, margin=margin,
|
||||
)
|
||||
|
||||
second_score = valid[1][2].score
|
||||
score_margin = first.score - second_score
|
||||
if score_margin < match_config.minimum_margin:
|
||||
return ProfileMatchResult(status='ambiguous', candidates=rendered, top1_score=top1_score, top2_score=top2_score, margin=margin)
|
||||
|
||||
if _can_auto_select_by_score(first, profile=profile, margin=score_margin):
|
||||
return ProfileMatchResult(
|
||||
status='selected_by_score', profile_code=profile.profile_code, version=profile.version,
|
||||
checksum=str(raw.get('checksum') or ''), candidates=rendered,
|
||||
top1_score=top1_score, top2_score=top2_score, margin=margin,
|
||||
)
|
||||
return ProfileMatchResult(status='ambiguous', candidates=rendered, top1_score=top1_score, top2_score=top2_score, margin=margin)
|
||||
|
||||
|
||||
def _can_auto_select_by_score(candidate: ProfileMatchCandidate, *, profile: OrderCoordinateProfileV2, margin: float) -> bool:
|
||||
"""判断多候选 hard_match 时是否满足自动决胜阈值。"""
|
||||
thresholds = profile.document_match.scoring_thresholds
|
||||
if candidate.dimension_scores is None:
|
||||
return False
|
||||
return (
|
||||
candidate.score >= thresholds.auto_select_minimum_score
|
||||
and margin >= thresholds.auto_select_minimum_margin
|
||||
and all(
|
||||
getattr(candidate.dimension_scores, key) >= thresholds.critical_structure_minimum
|
||||
for key in CRITICAL_STRUCTURE_DIMENSION_KEYS
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _layout_page_text(
|
||||
*, tables: list[dict[str, Any]], glyph_tables: dict[str, Any],
|
||||
page_glyphs: dict[str, Any], pages: dict[str, Any],
|
||||
) -> str:
|
||||
"""合并页级与表内字符为规范化全文,供弱漂移信号检测使用。"""
|
||||
chunks: list[str] = []
|
||||
page_numbers = sorted({str(item.get('page_no') or '') for item in tables if item.get('page_no')})
|
||||
if not page_numbers:
|
||||
page_numbers = sorted(str(page_no) for page_no in pages)
|
||||
for page_no in page_numbers:
|
||||
glyphs = page_glyphs.get(page_no)
|
||||
if not isinstance(glyphs, list):
|
||||
glyphs = [
|
||||
glyph for table in tables if str(table.get('page_no') or '') == page_no
|
||||
for glyph in (glyph_tables.get(str(table.get('table_id') or '')) or [])
|
||||
]
|
||||
if isinstance(glyphs, list):
|
||||
chunks.append(_anchor_comparable_text(''.join(str(item.get('text') or '') for item in glyphs)))
|
||||
return ''.join(chunks)
|
||||
|
||||
|
||||
def _compute_dimension_scores(
|
||||
*,
|
||||
profile: OrderCoordinateProfileV2,
|
||||
tables: list[dict[str, Any]],
|
||||
pages: dict[str, Any],
|
||||
required_hits: list[bool],
|
||||
optional_hits: list[bool],
|
||||
page_text: str,
|
||||
customer_ids: list[int] | None,
|
||||
customer_hint_id: int | None,
|
||||
) -> ProfileMatchDimensionScores:
|
||||
"""
|
||||
基于可用冻结证据计算七维启发式得分;首版不依赖 LLM 或业务字段值。
|
||||
|
||||
核心逻辑:锚点几何由必选/可选命中驱动;表拓扑比较检测表数与模板表区数;其余维度
|
||||
由模板结构配置与页证据存在性给出保守分数。
|
||||
"""
|
||||
required_total = len(required_hits)
|
||||
optional_total = len(optional_hits)
|
||||
required_ratio = (sum(required_hits) / required_total) if required_total else 1.0
|
||||
optional_ratio = (sum(optional_hits) / optional_total) if optional_total else 1.0
|
||||
anchor_geometry = required_ratio if optional_total == 0 else round(0.8 * required_ratio + 0.2 * optional_ratio, 6)
|
||||
|
||||
expected_regions = _applicable_table_region_count(profile, tables=tables, pages=pages)
|
||||
detected_tables = len(tables)
|
||||
if expected_regions <= 0:
|
||||
table_topology = 0.0
|
||||
elif detected_tables <= 0 and pages:
|
||||
# v2 templates reconstruct rows from frozen page coordinates. MinerU table detection is
|
||||
# auxiliary evidence and must not zero the score when complete page geometry is available.
|
||||
table_topology = 1.0
|
||||
else:
|
||||
table_topology = round(min(detected_tables, expected_regions) / max(detected_tables, expected_regions), 6)
|
||||
|
||||
line_layout_count = sum(len(item.line_layouts) for item in profile.table_regions)
|
||||
row_structure = 1.0 if line_layout_count >= 1 else 0.0
|
||||
|
||||
header_layout_count = sum(len(item.header_layouts) for item in profile.table_regions)
|
||||
order_field_count = len(profile.order_field_layouts)
|
||||
if header_layout_count + order_field_count == 0:
|
||||
header_regions = 0.5
|
||||
else:
|
||||
header_regions = round(min(1.0, 0.4 + 0.06 * (header_layout_count + order_field_count)), 6)
|
||||
|
||||
page_structure = 1.0 if pages else 0.0
|
||||
header_path = 1.0 if header_layout_count > 0 else 0.5
|
||||
|
||||
normalized_customer_ids = [int(item) for item in (customer_ids or [])]
|
||||
if not normalized_customer_ids:
|
||||
customer_hint = 1.0
|
||||
elif customer_hint_id is not None and int(customer_hint_id) in set(normalized_customer_ids):
|
||||
customer_hint = 1.0
|
||||
elif customer_hint_id is not None:
|
||||
customer_hint = 0.0
|
||||
else:
|
||||
customer_hint = 0.5
|
||||
|
||||
return ProfileMatchDimensionScores(
|
||||
table_topology=table_topology,
|
||||
row_structure=row_structure,
|
||||
anchor_geometry=anchor_geometry,
|
||||
header_regions=header_regions,
|
||||
page_structure=page_structure,
|
||||
header_path=header_path,
|
||||
customer_hint=customer_hint,
|
||||
)
|
||||
|
||||
|
||||
def _applicable_table_region_count(
|
||||
profile: OrderCoordinateProfileV2,
|
||||
*,
|
||||
tables: list[dict[str, Any]],
|
||||
pages: dict[str, Any],
|
||||
) -> int:
|
||||
"""
|
||||
统计当前冻结页面上实际参与比对的表区数量,避免续页 exact_page 区域拉低拓扑得分。
|
||||
|
||||
核心逻辑:first_page/all_pages 区域总计入;exact_page 仅在对应页有证据时才计入。
|
||||
"""
|
||||
page_numbers = sorted({str(item.get('page_no') or '') for item in tables if item.get('page_no')})
|
||||
if not page_numbers:
|
||||
page_numbers = sorted(str(page_no) for page_no in pages)
|
||||
applicable = 0
|
||||
for region in profile.table_regions:
|
||||
if region.page_scope in {'first_page', 'all_pages', 'continuation_pages'}:
|
||||
applicable += 1
|
||||
elif region.page_scope == 'exact_page' and str(region.page_no) in page_numbers:
|
||||
applicable += 1
|
||||
return applicable
|
||||
|
||||
|
||||
def _any_drift_signal(
|
||||
candidates: list[tuple[dict[str, Any], OrderCoordinateProfileV2, ProfileMatchCandidate]],
|
||||
*,
|
||||
page_text: str,
|
||||
) -> bool:
|
||||
"""检测部分硬门禁失败但仍出现模板锚点/值证据的漂移信号。"""
|
||||
for _, profile, candidate in candidates:
|
||||
if 'required_anchor_missing' not in candidate.reason_codes:
|
||||
continue
|
||||
required = profile.document_match.required_anchors
|
||||
optional = profile.document_match.optional_anchors
|
||||
for anchor in required:
|
||||
label = _anchor_comparable_text(anchor.label)
|
||||
expected = _anchor_comparable_text(anchor.value)
|
||||
if label and label in page_text:
|
||||
return True
|
||||
if expected and expected in page_text:
|
||||
return True
|
||||
for anchor in optional:
|
||||
label = _anchor_comparable_text(anchor.label)
|
||||
expected = _anchor_comparable_text(anchor.value)
|
||||
if label and expected and label in page_text and expected in page_text:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _any_special_profile_feature(
|
||||
candidates: list[tuple[dict[str, Any], OrderCoordinateProfileV2, ProfileMatchCandidate]],
|
||||
*,
|
||||
page_text: str,
|
||||
) -> bool:
|
||||
"""
|
||||
判断是否存在任何异型模板特征得分;与 drift 信号一起用于拒识边界。
|
||||
|
||||
核心逻辑:任一候选 anchor_geometry 或 table_topology 达弱阈值,或页内出现模板锚点
|
||||
标签/值,即视为“有特殊特征”,不得落入 no_special_profile_feature。
|
||||
"""
|
||||
for _, _, candidate in candidates:
|
||||
if candidate.hard_match:
|
||||
return True
|
||||
if candidate.dimension_scores is not None and candidate.dimension_scores.anchor_geometry >= 0.3:
|
||||
return True
|
||||
return _any_drift_signal(candidates, page_text=page_text)
|
||||
|
||||
|
||||
def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
|
||||
"""按视觉行重组冻结字符,供标签和值的相对位置校验使用。"""
|
||||
"""
|
||||
按视觉行重组冻结字符,并在行内按横坐标恢复阅读顺序。
|
||||
|
||||
核心逻辑:使用与标注取字一致的行高容差聚合同一视觉行,避免原生 PDF 字符的
|
||||
纵向轻微抖动打乱同行地址;调用方再按行序拼接多行固定值。
|
||||
"""
|
||||
lines: list[list[dict[str, Any]]] = []
|
||||
for glyph in sorted(glyphs, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0))):
|
||||
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else {}
|
||||
@@ -123,7 +403,7 @@ def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
|
||||
previous_bbox = previous[0].get('bbox') or {}
|
||||
previous_center_y = (float(previous_bbox.get('y0', 0)) + float(previous_bbox.get('y1', 0))) / 2
|
||||
previous_height = float(previous_bbox.get('y1', 0)) - float(previous_bbox.get('y0', 0))
|
||||
if abs(center_y - previous_center_y) <= max(height, previous_height) * .55:
|
||||
if abs(center_y - previous_center_y) <= max(height, previous_height) * .65:
|
||||
previous.append(glyph)
|
||||
continue
|
||||
lines.append([glyph])
|
||||
@@ -189,7 +469,10 @@ def _anchor_present(
|
||||
selected = [item for item in overlaps if abs(
|
||||
(float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 - reference_y,
|
||||
) <= max(reference_height, float(item['bbox'].get('y1', 0)) - float(item['bbox'].get('y0', 0))) * .55]
|
||||
return _anchor_comparable_text(''.join(str(item.get('text') or '') for item in sorted(selected, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0)))))
|
||||
# 运行匹配与标注取字共用阅读顺序,避免多行地址的字体基线抖动重排字符。
|
||||
return _anchor_comparable_text(read_coordinate_region_text(
|
||||
glyphs=glyphs, page=page, region=region,
|
||||
))
|
||||
if label in region_text(label_region) and expected in region_text(value_region):
|
||||
return True
|
||||
except (KeyError, TypeError, ValueError):
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from time import perf_counter
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
@@ -19,6 +20,10 @@ from app.services.shipping_notice.document_layout.mineru import (
|
||||
MINERU_SUPPORTED_EXTENSIONS,
|
||||
MinerUClient,
|
||||
MinerUClientConfig,
|
||||
MinerUCapabilityReport,
|
||||
MinerUPageCandidate,
|
||||
MinerUParseCandidate,
|
||||
MinerUTableCandidate,
|
||||
parse_mineru_candidate,
|
||||
)
|
||||
|
||||
@@ -43,23 +48,50 @@ def build_mineru_table_snapshot(
|
||||
read_timeout_seconds: int | None = None,
|
||||
document_id: int | None = None,
|
||||
content_hash: str | None = None,
|
||||
timings: dict[str, int] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
为一个受支持附件生成紧凑 MinerU 文本与表格快照。
|
||||
|
||||
核心逻辑:保留分页非表格文本块和表格 HTML,分别执行字符预算;不持久化
|
||||
task_id、Provider 原始响应、模型中间输出或逐字符坐标。
|
||||
核心逻辑:文字型 PDF 先用本地坐标和严格表头门槛恢复表格,成功即跳过 MinerU;
|
||||
本地证据不足时再调用 MinerU。两条路径都冻结相同的页面坐标契约。
|
||||
|
||||
Args:
|
||||
filename: 原附件名,仅用于扩展名和 MinerU multipart,不进入返回错误详情。
|
||||
content: 原始文件字节;不写数据库和日志。
|
||||
document_id/content_hash: PDF 的版本化 Document 身份;两者齐全时生成 layout.v1 候选。
|
||||
timings: 可选运维耗时字典;只写阶段毫秒数,不进入持久化快照。
|
||||
Returns:
|
||||
关闭/不支持时返回 None;成功或 Provider 降级均返回受控的版本化状态对象。
|
||||
"""
|
||||
extension = Path(str(filename or '')).suffix.lower()
|
||||
if not mineru_layout_capture_enabled(filename) or not content:
|
||||
return None
|
||||
native_pages: list[Any] | None = None
|
||||
if extension == '.pdf' and document_id and content_hash:
|
||||
try:
|
||||
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
|
||||
|
||||
native_started = perf_counter()
|
||||
native_pages = extract_native_pdf_pages(content, render_images=False)
|
||||
if timings is not None:
|
||||
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
|
||||
fast_snapshot = _native_pdf_fast_snapshot(
|
||||
content=content,
|
||||
document_id=int(document_id),
|
||||
content_hash=str(content_hash),
|
||||
native_pages=native_pages,
|
||||
timings=timings,
|
||||
)
|
||||
if fast_snapshot is not None:
|
||||
if timings is not None:
|
||||
timings['layout_fast_path'] = 1
|
||||
return fast_snapshot
|
||||
except Exception:
|
||||
native_pages = None
|
||||
if native_pages is not None:
|
||||
# 本地文字门槛未命中时,后续 MinerU 增强路径需要完整页面图,按需重新提取。
|
||||
native_pages = None
|
||||
base_url = str(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL') or '').strip()
|
||||
if not base_url:
|
||||
return {
|
||||
@@ -82,9 +114,14 @@ def build_mineru_table_snapshot(
|
||||
)),
|
||||
)
|
||||
try:
|
||||
candidate = parse_mineru_candidate(
|
||||
MinerUClient(config).parse_file_async(filename=filename, content=content),
|
||||
)
|
||||
provider_started = perf_counter()
|
||||
provider_result = MinerUClient(config).parse_file_async(filename=filename, content=content)
|
||||
if timings is not None:
|
||||
timings['mineru_wait_ms'] = round((perf_counter() - provider_started) * 1000)
|
||||
result_parse_started = perf_counter()
|
||||
candidate = parse_mineru_candidate(provider_result)
|
||||
if timings is not None:
|
||||
timings['mineru_result_parse_ms'] = round((perf_counter() - result_parse_started) * 1000)
|
||||
except AppError as exc:
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
@@ -167,30 +204,153 @@ def build_mineru_table_snapshot(
|
||||
try:
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
build_native_pdf_layout_candidate,
|
||||
build_native_pdf_text_table_fallbacks,
|
||||
extract_native_pdf_pages,
|
||||
)
|
||||
|
||||
if native_pages is None:
|
||||
native_started = perf_counter()
|
||||
native_pages = extract_native_pdf_pages(content)
|
||||
if timings is not None:
|
||||
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
|
||||
|
||||
# MinerU occasionally returns only text blocks for unbordered purchase-order lines.
|
||||
# Restrict the fallback to an otherwise empty table result so normal templates retain
|
||||
# the provider's original table structure unchanged.
|
||||
if not tables:
|
||||
fallback_tables = build_native_pdf_text_table_fallbacks(
|
||||
content,
|
||||
native_pages=native_pages,
|
||||
)
|
||||
if fallback_tables:
|
||||
tables.extend(fallback_tables)
|
||||
snapshot['tables'] = tables
|
||||
snapshot['issues'] = sorted(set(
|
||||
issue for issue in snapshot['issues']
|
||||
if issue not in {'mineru_table_structure_missing', 'mineru_cell_coordinates_missing'}
|
||||
) | {'native_pdf_text_table_fallback_used'})
|
||||
|
||||
layout_started = perf_counter()
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=int(document_id), content_hash=str(content_hash),
|
||||
content=content, mineru=candidate,
|
||||
content=content, mineru=candidate, native_pages=native_pages,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
|
||||
snapshot['layout_candidate'] = layout.model_dump(mode='json')
|
||||
# 冻结表格与整页字符坐标:明细重建只消费前者,订单级字段只能消费后者。
|
||||
evidence_started = perf_counter()
|
||||
snapshot['coordinate_evidence'] = _table_coordinate_evidence(
|
||||
content=content, tables=tables,
|
||||
pages=native_pages, tables=tables,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
|
||||
except Exception:
|
||||
snapshot['issues'] = sorted(set(
|
||||
list(snapshot['issues']) + ['native_pdf_layout_candidate_invalid'],
|
||||
))
|
||||
if not snapshot['tables']:
|
||||
snapshot['issues'] = sorted(set(
|
||||
list(snapshot['issues']) + ['shipping_document_business_table_not_detected'],
|
||||
))
|
||||
return snapshot
|
||||
|
||||
|
||||
def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""保存表内及整页原生字符和页尺寸,分别供明细与订单级字段确定性重放。"""
|
||||
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
|
||||
def _native_pdf_fast_snapshot(
|
||||
*, content: bytes, document_id: int, content_hash: str,
|
||||
native_pages: list[Any], timings: dict[str, int] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
用严格原生文字表格证据生成可立即消费的布局快照。
|
||||
|
||||
pages = {item.page_no: item for item in extract_native_pdf_pages(content)}
|
||||
AI/调用方触发时机:版面 Job 收到文字型 PDF 时先调用;只有表头、列边界和
|
||||
数据行同时成立才返回快照,否则返回 None 继续 MinerU,禁止宽松猜测表格。
|
||||
|
||||
Args:
|
||||
content: 当前 PDF 字节,仅传给既有布局构建器,不持久化。
|
||||
document_id/content_hash: 当前不可变 Document 身份。
|
||||
native_pages: 已完成一次 PDFium 提取的页面,后续阶段必须复用。
|
||||
timings: 可选运维阶段耗时,不进入快照。
|
||||
|
||||
Returns:
|
||||
证据充分时返回 ready 快照;无法证明业务表格时返回 None。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
build_native_pdf_layout_candidate,
|
||||
build_native_pdf_text_table_fallbacks,
|
||||
)
|
||||
|
||||
fallback_started = perf_counter()
|
||||
tables = build_native_pdf_text_table_fallbacks(content, native_pages=native_pages)
|
||||
if timings is not None:
|
||||
timings['native_table_detect_ms'] = round((perf_counter() - fallback_started) * 1000)
|
||||
if not tables:
|
||||
return None
|
||||
|
||||
page_candidates = []
|
||||
for page in native_pages:
|
||||
page_tables = []
|
||||
for table in tables:
|
||||
if int(table.get('page_no') or 0) != int(page.page_no):
|
||||
continue
|
||||
page_tables.append(MinerUTableCandidate(
|
||||
candidate_id=str(table['table_id']), page_no=int(page.page_no),
|
||||
bbox=table['bbox'], normalized_bbox=table['normalized_bbox'],
|
||||
html=str(table['html']), row_count=int(table['row_count']),
|
||||
cell_count=int(table['cell_count']),
|
||||
has_rowspan=bool(table.get('has_rowspan')), has_colspan=bool(table.get('has_colspan')),
|
||||
))
|
||||
page_candidates.append(MinerUPageCandidate(
|
||||
page_no=int(page.page_no), width=float(page.width), height=float(page.height),
|
||||
text_blocks=[], tables=page_tables,
|
||||
))
|
||||
candidate = MinerUParseCandidate(
|
||||
provider_version='pdfium-native-text-v1', backend='native_pdf', pages=page_candidates,
|
||||
capability=MinerUCapabilityReport(
|
||||
provider_version='pdfium-native-text-v1', backend='native_pdf',
|
||||
page_count=len(page_candidates), page_size_count=len(page_candidates),
|
||||
bbox_object_count=len(tables), html_table_count=len(tables),
|
||||
html_row_count=sum(int(item.get('row_count') or 0) for item in tables),
|
||||
html_cell_count=sum(int(item.get('cell_count') or 0) for item in tables),
|
||||
text_block_count=0, cell_bbox_count=0, has_page_coordinates=True,
|
||||
has_table_structure=True, has_cell_coordinates=False,
|
||||
deterministic_cell_evidence_ready=False,
|
||||
issues=['native_pdf_text_table_fallback_used'],
|
||||
),
|
||||
)
|
||||
layout_started = perf_counter()
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=document_id, content_hash=content_hash,
|
||||
content=content, mineru=candidate, native_pages=native_pages,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
|
||||
evidence_started = perf_counter()
|
||||
evidence = _table_coordinate_evidence(pages=native_pages, tables=tables)
|
||||
if timings is not None:
|
||||
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'pdfium', 'provider_version': 'native-text-v1', 'backend': 'native_pdf',
|
||||
'status': 'ready', 'text_blocks': [], 'tables': tables,
|
||||
'capability': candidate.capability.model_dump(mode='json'),
|
||||
'layout_candidate': layout.model_dump(mode='json'),
|
||||
'coordinate_evidence': evidence,
|
||||
'issues': ['native_pdf_text_table_fallback_used'],
|
||||
}
|
||||
|
||||
|
||||
def _table_coordinate_evidence(*, pages: list[Any], tables: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""
|
||||
从已提取页面保存表内及整页字符证据,避免同一 PDF 重复解析和渲染。
|
||||
|
||||
Args:
|
||||
pages: 本轮已提取的 NativePdfPage 列表。
|
||||
tables: MinerU 或原生文字回退生成的表格摘要。
|
||||
Returns:
|
||||
供明细重建与订单字段重放的坐标证据。
|
||||
"""
|
||||
pages = {item.page_no: item for item in pages}
|
||||
evidence: dict[str, list[dict[str, Any]]] = {}
|
||||
for table in tables:
|
||||
table_id = str(table.get('table_id') or '')
|
||||
|
||||
@@ -15,13 +15,17 @@ from app.services.shipping_notice.document_layout.html_table import (
|
||||
HtmlGrid,
|
||||
HtmlGridCell,
|
||||
HtmlGridSlot,
|
||||
collect_unmapped_nonempty_columns,
|
||||
map_html_grid_to_schema,
|
||||
summarize_row_roles,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import TableHeaderContract
|
||||
|
||||
|
||||
def map_layout_document_to_schema(
|
||||
layout: LayoutDocument | dict[str, Any], *, contract: TableHeaderContract,
|
||||
layout: LayoutDocument | dict[str, Any], *,
|
||||
contract: TableHeaderContract,
|
||||
ignorable_column_headers: list[str] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
映射完整布局文档,并输出保留 cell/token 证据的安全候选。
|
||||
@@ -29,8 +33,9 @@ def map_layout_document_to_schema(
|
||||
Args:
|
||||
layout: 必须通过 shipping_document_layout.v1 完整校验。
|
||||
contract: 当前 Run 冻结订单 Schema 表头契约。
|
||||
ignorable_column_headers: 冻结 Schema 配置的显式可忽略列表头(标准化前原文)。
|
||||
Returns:
|
||||
每张表的映射、质量和显式跨页父表;needs_review 永不伪装 accepted。
|
||||
每张表的映射、质量、行角色与显式跨页父表;needs_review 永不伪装 accepted。
|
||||
"""
|
||||
document = validate_layout_document(layout)
|
||||
result: list[dict[str, Any]] = []
|
||||
@@ -44,6 +49,27 @@ def map_layout_document_to_schema(
|
||||
cell.cell_id: list(cell.token_ids)
|
||||
for row in table.rows for cell in row.cells
|
||||
}
|
||||
row_payloads = []
|
||||
for row in mapped.rows:
|
||||
row_cells = _row_cell_snapshots(grid, row_index=row.row_index)
|
||||
row_payloads.append({
|
||||
**row.model_dump(mode='json'),
|
||||
'cells': row_cells,
|
||||
'fields': [{
|
||||
**field.model_dump(mode='json'),
|
||||
'token_ids': token_ids_by_cell.get(field.cell_id, []),
|
||||
'evidence_ref': (
|
||||
f'layout:{document.document_id}:p{page.page_no}:'
|
||||
f'{table.table_id}:{field.cell_id}'
|
||||
),
|
||||
} for field in row.fields],
|
||||
})
|
||||
unmapped_nonempty = collect_unmapped_nonempty_columns(
|
||||
grid,
|
||||
header_index=mapped.header_row_index,
|
||||
columns=mapped.columns,
|
||||
rows=mapped.rows,
|
||||
)
|
||||
result.append({
|
||||
'page_no': page.page_no,
|
||||
'table_id': table.table_id,
|
||||
@@ -56,17 +82,10 @@ def map_layout_document_to_schema(
|
||||
+ ([] if table.status == 'accepted' else ['layout_table_not_accepted'])
|
||||
)),
|
||||
'columns': [item.model_dump(mode='json') for item in mapped.columns],
|
||||
'rows': [{
|
||||
**row.model_dump(mode='json'),
|
||||
'fields': [{
|
||||
**field.model_dump(mode='json'),
|
||||
'token_ids': token_ids_by_cell.get(field.cell_id, []),
|
||||
'evidence_ref': (
|
||||
f'layout:{document.document_id}:p{page.page_no}:'
|
||||
f'{table.table_id}:{field.cell_id}'
|
||||
),
|
||||
} for field in row.fields],
|
||||
} for row in mapped.rows],
|
||||
'rows': row_payloads,
|
||||
'row_role_summary': summarize_row_roles(mapped.rows),
|
||||
'unmapped_nonempty_column_indices': unmapped_nonempty,
|
||||
'ignorable_column_headers': list(ignorable_column_headers or []),
|
||||
})
|
||||
return result
|
||||
|
||||
@@ -110,3 +129,19 @@ def layout_table_to_grid(table: LayoutTable) -> HtmlGrid:
|
||||
],
|
||||
cells=cells,
|
||||
)
|
||||
|
||||
|
||||
def _row_cell_snapshots(grid: HtmlGrid, *, row_index: int) -> list[dict[str, str | int]]:
|
||||
"""提取一行各列的脱敏 cell 快照,供未映射列完整性检测使用。"""
|
||||
if row_index < 0 or row_index >= grid.row_count:
|
||||
return []
|
||||
snapshots: list[dict[str, str | int]] = []
|
||||
for column_index, slot in enumerate(grid.rows[row_index]):
|
||||
if slot is None:
|
||||
continue
|
||||
snapshots.append({
|
||||
'column_index': column_index,
|
||||
'cell_id': slot.cell_id,
|
||||
'text': slot.text.strip(),
|
||||
})
|
||||
return snapshots
|
||||
Reference in new issue
Block a user