feat(shipping-order): 迭代货代订单提取与履约全流程功能
添加订单字段自动标注配置,默认仅关键字段参与自动框选 完善字段规范化逻辑,支持更多日期格式解析 添加订单候选人工采纳、驳回的完整流程,包含API、前端交互与状态管理 完善盲测功能,支持订单级字段真值校验,调整盲测集唯一性约束 加固库存校验逻辑,防止重复预约与数量不一致问题 优化坐标匹配逻辑,支持表格外的锚点定位 新增上传结果未知的状态处理,完善任务状态机 更新多语言文案与文档说明,补充功能细节 修复订单合并、重解析的边缘情况问题 补充相关测试用例,完善质量保障
This commit is contained in:
1 parent
11079910ec
commit
90f77634d6
76 files changed
+5056
-338
No files matched your search
+2
@@ -132,6 +132,8 @@ class CoordinateHeaderFieldRegionSuggestion(CoordinateReconstructionModel):
|
||||
|
||||
region: LayoutBBox
|
||||
text: str = ''
|
||||
field_code: str | None = None
|
||||
confidence: Literal['exact_alias', 'ambiguous', 'unmapped'] = 'unmapped'
|
||||
|
||||
|
||||
class HeaderFieldSuggestion(CoordinateReconstructionModel):
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/order_field_extraction.py
|
||||
|
||||
用途:从冻结的整页 PDF/OCR 字符坐标中确定性提取独立订单级字段。
|
||||
依赖:OrderCoordinateProfileV2、冻结 Schema 字段规则和 LayoutBBox。
|
||||
逻辑:订单工作流先唯一匹配模板,再调用本模块;本模块仅返回可追溯候选,绝不回读资产、数据库或调用模型。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
AnchorRelativeRegion,
|
||||
AnchorRule,
|
||||
OrderCoordinateProfileV2,
|
||||
OrderFieldLayout,
|
||||
RelativeRegion,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
|
||||
|
||||
class OrderFieldExtraction(BaseModel):
|
||||
"""表示单个订单字段的脱敏运行期候选及其最小坐标证据。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
field_id: str
|
||||
field_code: str
|
||||
value: Any = None
|
||||
status: Literal['confirmed', 'needs_review', 'unavailable']
|
||||
source: Literal['pdf_coordinate', 'ocr_coordinate'] | None = None
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
anchor_bbox: LayoutBBox | None = None
|
||||
value_bbox: LayoutBBox | None = None
|
||||
glyph_indices: list[int] = Field(default_factory=list)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def extract_order_fields(
|
||||
*, profile: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_evidence: dict[str, Any],
|
||||
) -> list[OrderFieldExtraction]:
|
||||
"""
|
||||
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
|
||||
|
||||
Args:
|
||||
profile: Run 冻结的 v2 坐标模板,不得包含待重新绑定字段。
|
||||
schema_fields: 以 stable field_id 为键的冻结启用 Schema 字段。
|
||||
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
|
||||
|
||||
Returns:
|
||||
每个已绑定布局对应一个候选,按模板声明顺序返回。
|
||||
"""
|
||||
return [
|
||||
_extract_layout(layout=layout, schema_fields=schema_fields, coordinate_evidence=coordinate_evidence)
|
||||
for layout in profile.order_field_layouts
|
||||
]
|
||||
|
||||
|
||||
def _extract_layout(
|
||||
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
|
||||
) -> OrderFieldExtraction:
|
||||
"""处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。"""
|
||||
config = schema_fields.get(layout.field_id)
|
||||
if config is None or not config.get('enabled', True) or config.get('scope') != 'header':
|
||||
return _unavailable(layout, 'order_field_schema_binding_invalid')
|
||||
pages = coordinate_evidence.get('pages') if isinstance(coordinate_evidence.get('pages'), dict) else {}
|
||||
glyph_pages = coordinate_evidence.get('page_glyphs') if isinstance(coordinate_evidence.get('page_glyphs'), dict) else {}
|
||||
sources = coordinate_evidence.get('sources') if isinstance(coordinate_evidence.get('sources'), dict) else {}
|
||||
page_sources = sources.get('pages') if isinstance(sources.get('pages'), dict) else {}
|
||||
candidates: list[tuple[int, list[dict[str, Any]], float, float, str]] = []
|
||||
for raw_page_no, page in pages.items():
|
||||
try:
|
||||
page_no, width, height = int(raw_page_no), float(page['width']), float(page['height'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if not _layout_applies_to_page(layout, page_no) or width <= 0 or height <= 0:
|
||||
continue
|
||||
glyphs = glyph_pages.get(str(page_no))
|
||||
source = str(page_sources.get(str(page_no)) or '')
|
||||
if isinstance(glyphs, list) and source in {'pdf_coordinate', 'ocr_coordinate'}:
|
||||
valid_glyphs = []
|
||||
for item in glyphs:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
_glyph_bbox(item)
|
||||
except Exception:
|
||||
continue
|
||||
valid_glyphs.append(item)
|
||||
candidates.append((page_no, valid_glyphs, width, height, source))
|
||||
if not candidates:
|
||||
return _unavailable(layout, 'order_field_page_coordinate_evidence_missing')
|
||||
|
||||
results: list[OrderFieldExtraction] = []
|
||||
for page_no, glyphs, width, height, source in candidates:
|
||||
if not _source_allowed(layout, config=config, source=source):
|
||||
results.append(_unavailable(layout, 'order_field_coordinate_source_not_allowed', page_no=page_no, source=source))
|
||||
continue
|
||||
if layout.anchor is None:
|
||||
results.append(_read_value_region(
|
||||
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
|
||||
region=_absolute_relative_region(layout.fallback_value_region, width=width, height=height), anchor_bbox=None,
|
||||
fallback=True,
|
||||
))
|
||||
continue
|
||||
matches = _find_anchor_matches(glyphs, layout.anchor, page_width=width, page_height=height)
|
||||
if not matches:
|
||||
reference_anchor = (
|
||||
_anchor_from_reference_region(
|
||||
glyphs, anchor=layout.anchor, page_width=width, page_height=height,
|
||||
)
|
||||
if _is_placeholder_anchor_text(layout.anchor.text) else None
|
||||
)
|
||||
if reference_anchor is not None:
|
||||
# Legacy manual regions can contain a placeholder label rather than
|
||||
# the PDF text. The reference box is evidence of administrator
|
||||
# intent, but it must remain review-only until the label is fixed.
|
||||
results.append(_read_value_region(
|
||||
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
|
||||
region=_absolute_anchor_region(layout.value_region, reference_anchor),
|
||||
anchor_bbox=reference_anchor, fallback=False,
|
||||
review_issue='order_field_anchor_text_mismatch',
|
||||
))
|
||||
continue
|
||||
results.append(_unavailable(layout, 'order_field_anchor_missing', page_no=page_no, source=source))
|
||||
continue
|
||||
if len(matches) != 1:
|
||||
results.append(OrderFieldExtraction(
|
||||
field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source,
|
||||
page_no=page_no, issues=['order_field_anchor_ambiguous'],
|
||||
))
|
||||
continue
|
||||
anchor_bbox, _indices = matches[0]
|
||||
results.append(_read_value_region(
|
||||
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
|
||||
region=_absolute_anchor_region(layout.value_region, anchor_bbox), anchor_bbox=anchor_bbox, fallback=False,
|
||||
))
|
||||
usable = [item for item in results if item.status != 'unavailable']
|
||||
if len(usable) == 1:
|
||||
return usable[0]
|
||||
if not usable:
|
||||
return results[0] if results else _unavailable(layout, 'order_field_page_coordinate_evidence_missing')
|
||||
values = {repr(item.value) for item in usable if item.value is not None}
|
||||
# Repeated page headers are corroborating evidence, not a second business value.
|
||||
# An ambiguous value on any selected page must still stop automatic acceptance.
|
||||
if len(values) == 1 and not any(item.status == 'needs_review' for item in usable):
|
||||
return usable[0]
|
||||
first = usable[0].model_copy(deep=True)
|
||||
first.status = 'needs_review'
|
||||
first.issues = sorted(set(first.issues + ['order_field_page_value_conflict']))
|
||||
return first
|
||||
|
||||
|
||||
def _read_value_region(
|
||||
*, layout: OrderFieldLayout, config: dict[str, Any], glyphs: list[dict[str, Any]], page_no: int,
|
||||
source: str, region: LayoutBBox, anchor_bbox: LayoutBBox | None, fallback: bool,
|
||||
review_issue: str | None = None,
|
||||
) -> OrderFieldExtraction:
|
||||
"""按视觉行合并值区文字,多行模式先以停止标签截断,再执行 Schema 规范化与校验。
|
||||
|
||||
``right_of_anchor`` 使用锚点右侧的同一连续文本段,而不是严格依赖值框的
|
||||
左边界;这能避免标签后的冒号进入值,也能容忍框选末尾少量字符。
|
||||
"""
|
||||
selected = (
|
||||
_inline_right_of_anchor_glyphs(glyphs=glyphs, anchor_bbox=anchor_bbox, region=region)
|
||||
if layout.value_mode == 'right_of_anchor' and anchor_bbox is not None
|
||||
else [(index, item) for index, item in enumerate(glyphs) if _glyph_center_inside(item, region)]
|
||||
)
|
||||
if layout.value_mode == 'multi_line':
|
||||
selected = _stop_before_anchor(
|
||||
selected, glyphs=glyphs, stop_anchors=layout.stop_anchors, anchor_bbox=anchor_bbox,
|
||||
)
|
||||
text = _render_value(selected, multi_line=layout.value_mode == 'multi_line')
|
||||
if layout.value_mode != 'multi_line':
|
||||
text = text.split('\n', 1)[0].strip()
|
||||
if layout.value_mode == 'right_of_anchor':
|
||||
text = text.lstrip(':: ').strip()
|
||||
if str(config.get('value_type') or '') == 'date':
|
||||
text = _recover_trailing_date_glyph(text=text, glyphs=glyphs, region=region)
|
||||
if not text:
|
||||
return _unavailable(layout, 'order_field_value_missing', page_no=page_no, source=source, anchor_bbox=anchor_bbox, value_bbox=region)
|
||||
try:
|
||||
value = normalize_order_field_value(text, config)
|
||||
except Exception:
|
||||
return _review(layout, 'order_field_normalization_failed', page_no, source, anchor_bbox, region, selected)
|
||||
if value is None or not validate_order_field_value(value, config):
|
||||
return _review(layout, 'order_field_validation_failed', page_no, source, anchor_bbox, region, selected)
|
||||
status: Literal['confirmed', 'needs_review'] = 'needs_review' if fallback or source != 'pdf_coordinate' or review_issue else 'confirmed'
|
||||
issues = ['order_field_fallback_value_region'] if fallback else []
|
||||
if source == 'ocr_coordinate':
|
||||
issues.append('order_field_ocr_coordinate_needs_review')
|
||||
if review_issue:
|
||||
issues.append(review_issue)
|
||||
return OrderFieldExtraction(
|
||||
field_id=layout.field_id, field_code=layout.field_code, value=value, status=status, source=source,
|
||||
page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=region,
|
||||
glyph_indices=[index for index, _item in selected], issues=issues,
|
||||
)
|
||||
|
||||
|
||||
def _inline_right_of_anchor_glyphs(
|
||||
*, glyphs: list[dict[str, Any]], anchor_bbox: LayoutBBox, region: LayoutBBox,
|
||||
) -> list[tuple[int, dict[str, Any]]]:
|
||||
"""读取值框内标签右侧的文本,仅在框尾补齐被截断的同一个词。
|
||||
|
||||
管理员的值框是字段分隔的主证据,不能按整行连续文本扩展。仅当框尾
|
||||
截在英文/数字词中间时,才追加紧邻字符直至一个正常词间隔;这不会吞入
|
||||
下一个字段,即使两个字段落在同一视觉行。
|
||||
|
||||
Args:
|
||||
glyphs: 当前页面冻结的字符坐标。
|
||||
anchor_bbox: 已唯一定位的标签字符联合框。
|
||||
region: 管理员配置的相对值区投影框。
|
||||
|
||||
Returns:
|
||||
值框内文本及其被截断的当前词的原始 glyph 索引和字符。
|
||||
"""
|
||||
anchor_center_y = (anchor_bbox.y0 + anchor_bbox.y1) / 2
|
||||
same_line = [
|
||||
(index, glyph) for index, glyph in enumerate(glyphs)
|
||||
if _glyph_bbox(glyph).x0 >= anchor_bbox.x1
|
||||
and region.y0 <= (_glyph_bbox(glyph).y0 + _glyph_bbox(glyph).y1) / 2 <= region.y1
|
||||
and abs(((_glyph_bbox(glyph).y0 + _glyph_bbox(glyph).y1) / 2) - anchor_center_y)
|
||||
<= max(anchor_bbox.y1 - anchor_bbox.y0, _glyph_bbox(glyph).y1 - _glyph_bbox(glyph).y0) * .55
|
||||
]
|
||||
ordered = sorted(same_line, key=lambda item: _glyph_bbox(item[1]).x0)
|
||||
selected = [item for item in ordered if _glyph_center_inside(item[1], region)]
|
||||
if not selected:
|
||||
return []
|
||||
last_position = next(
|
||||
(position for position in range(len(ordered) - 1, -1, -1) if ordered[position][0] == selected[-1][0]),
|
||||
-1,
|
||||
)
|
||||
previous = _glyph_bbox(selected[-1][1])
|
||||
for item in ordered[last_position + 1:]:
|
||||
bbox = _glyph_bbox(item[1])
|
||||
typical_width = max((previous.x1 - previous.x0 + bbox.x1 - bbox.x0) / 2, .01)
|
||||
# A normal word gap terminates the only permitted overrun. This admits
|
||||
# ``Corporati`` -> ``Corporation`` but not a following address/field.
|
||||
if bbox.x0 - previous.x1 > typical_width * .75:
|
||||
break
|
||||
selected.append(item)
|
||||
previous = bbox
|
||||
return selected
|
||||
|
||||
|
||||
def _recover_trailing_date_glyph(*, text: str, glyphs: list[dict[str, Any]], region: LayoutBBox) -> str:
|
||||
"""补入紧贴日期值框右缘的单个数字,容忍管理员框选少一个字宽但不扩展到下一字段。"""
|
||||
compact = re.sub(r'\s+', '', text)
|
||||
if not re.fullmatch(r'(?:\d{4}[-/.]\d{1,2}[-/.]\d{1,2}|\d{1,2}[-/.]\d{1,2}[-/.]\d{1,3})', compact):
|
||||
return text
|
||||
candidates = []
|
||||
for glyph in glyphs:
|
||||
try:
|
||||
bbox = _glyph_bbox(glyph)
|
||||
except Exception:
|
||||
continue
|
||||
if not str(glyph.get('text') or '').isdigit() or bbox.y1 < region.y0 or bbox.y0 > region.y1:
|
||||
continue
|
||||
glyph_width = max(bbox.x1 - bbox.x0, .01)
|
||||
if 0 <= bbox.x0 - region.x1 <= glyph_width * 1.5:
|
||||
candidates.append((bbox.x0, str(glyph.get('text') or '')))
|
||||
if len(candidates) != 1:
|
||||
return text
|
||||
return f'{text}{candidates[0][1]}'
|
||||
|
||||
|
||||
def _find_anchor_matches(
|
||||
glyphs: list[dict[str, Any]], anchor: AnchorRule, *, page_width: float | None = None, page_height: float | None = None,
|
||||
) -> list[tuple[LayoutBBox, list[int]]]:
|
||||
"""在每个视觉行内执行精确标签匹配,返回去重后的字符联合框。"""
|
||||
expected = [anchor.text, *anchor.aliases]
|
||||
matches: list[tuple[LayoutBBox, list[int]]] = []
|
||||
for row in _visual_rows(list(enumerate(glyphs))):
|
||||
# PDFium does not emit whitespace glyphs consistently, so labels are compared
|
||||
# after whitespace folding while preserving a mapping back to real characters.
|
||||
compact: list[tuple[int, dict[str, Any]]] = [
|
||||
pair for pair in row if str(pair[1].get('text') or '').strip()
|
||||
]
|
||||
row_text = ''.join(str(item.get('text') or '') for _index, item in compact)
|
||||
folded = row_text.casefold()
|
||||
for label in expected:
|
||||
normalized = re.sub(r'\s+', '', label).casefold()
|
||||
start = 0
|
||||
while normalized and (position := folded.find(normalized, start)) >= 0:
|
||||
consumed = compact[position:position + len(normalized)]
|
||||
if len(consumed) == len(normalized) and _anchor_occurrence_is_exact(
|
||||
compact, position=position, length=len(normalized), anchor=anchor,
|
||||
):
|
||||
bbox = _union_bbox([item for _index, item in consumed])
|
||||
if _anchor_bbox_in_reference_region(
|
||||
bbox, anchor=anchor, page_width=page_width, page_height=page_height,
|
||||
):
|
||||
matches.append((bbox, [index for index, _item in consumed]))
|
||||
start = position + max(len(label), 1)
|
||||
unique: dict[tuple[float, float, float, float], tuple[LayoutBBox, list[int]]] = {}
|
||||
for bbox, indices in matches:
|
||||
unique[(bbox.x0, bbox.y0, bbox.x1, bbox.y1)] = (bbox, indices)
|
||||
return list(unique.values())
|
||||
|
||||
|
||||
def _anchor_occurrence_is_exact(
|
||||
row: list[tuple[int, dict[str, Any]]], *, position: int, length: int, anchor: AnchorRule,
|
||||
) -> bool:
|
||||
"""精确模式拒绝嵌入其他字母数字串的标签,contains 模式才允许局部命中。"""
|
||||
if anchor.match_mode != 'exact':
|
||||
return True
|
||||
before = row[position - 1][1] if position else None
|
||||
first = row[position][1]
|
||||
last = row[position + length - 1][1]
|
||||
after = row[position + length][1] if position + length < len(row) else None
|
||||
return not (
|
||||
(before is not None and str(before.get('text') or '').isalnum() and not _glyph_gap_is_word_boundary(before, first))
|
||||
or (after is not None and str(after.get('text') or '').isalnum() and not _glyph_gap_is_word_boundary(last, after))
|
||||
)
|
||||
|
||||
|
||||
def _glyph_gap_is_word_boundary(left: dict[str, Any], right: dict[str, Any]) -> bool:
|
||||
"""PDFium 常省略空白 glyph;相邻字符间的大间隔仍视为精确标签的词边界。"""
|
||||
left_bbox, right_bbox = _glyph_bbox(left), _glyph_bbox(right)
|
||||
typical_width = max(((left_bbox.x1 - left_bbox.x0) + (right_bbox.x1 - right_bbox.x0)) / 2, 0.01)
|
||||
return right_bbox.x0 - left_bbox.x1 > typical_width * 0.75
|
||||
|
||||
|
||||
def _anchor_bbox_in_reference_region(
|
||||
bbox: LayoutBBox, *, anchor: AnchorRule, page_width: float | None, page_height: float | None,
|
||||
) -> bool:
|
||||
"""锚点配置了参考区时只接受该页相对位置内的命中,避免页眉重复标签干扰。"""
|
||||
if anchor.region is None:
|
||||
return True
|
||||
if page_width is None or page_height is None or page_width <= 0 or page_height <= 0:
|
||||
return False
|
||||
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
|
||||
return _glyph_center_inside({'bbox': bbox.model_dump(mode='json')}, region)
|
||||
|
||||
|
||||
def _anchor_from_reference_region(
|
||||
glyphs: list[dict[str, Any]], *, anchor: AnchorRule, page_width: float, page_height: float,
|
||||
) -> LayoutBBox | None:
|
||||
"""为历史占位标签保留参考框内的实际标签几何,且调用方必须降级为人工复核。"""
|
||||
if anchor.region is None:
|
||||
return None
|
||||
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
|
||||
selected = [glyph for glyph in glyphs if _glyph_center_inside(glyph, region)]
|
||||
return _union_bbox(selected) if selected else None
|
||||
|
||||
|
||||
def _is_placeholder_anchor_text(value: str) -> bool:
|
||||
"""仅兼容工作台历史默认名;任何管理员自定义标签不匹配时仍必须失败关闭。"""
|
||||
return re.fullmatch(r'订单字段标签\s*\d*', value.strip()) is not None
|
||||
|
||||
|
||||
def _stop_before_anchor(
|
||||
selected: list[tuple[int, dict[str, Any]]], *, glyphs: list[dict[str, Any]], stop_anchors: list[AnchorRule],
|
||||
anchor_bbox: LayoutBBox | None,
|
||||
) -> list[tuple[int, dict[str, Any]]]:
|
||||
"""多行值仅在当前锚点之后遇到首个停止标签时截断,避免页眉同名标签误伤。"""
|
||||
stop_y: float | None = None
|
||||
for anchor in stop_anchors:
|
||||
for bbox, _indices in _find_anchor_matches(glyphs, anchor):
|
||||
if anchor_bbox is not None and bbox.y0 <= anchor_bbox.y1:
|
||||
continue
|
||||
stop_y = bbox.y0 if stop_y is None else min(stop_y, bbox.y0)
|
||||
return selected if stop_y is None else [item for item in selected if _glyph_bbox(item[1]).y0 < stop_y]
|
||||
|
||||
|
||||
def _render_value(selected: list[tuple[int, dict[str, Any]]], *, multi_line: bool) -> str:
|
||||
"""按 y 聚类、x 排序渲染字符,保留多行字段的换行而不伪造空格。"""
|
||||
rows = _visual_rows(selected)
|
||||
rendered = [_render_visual_row(row) for row in rows]
|
||||
return ('\n' if multi_line else ' ').join(item for item in rendered if item).strip()
|
||||
|
||||
|
||||
def _render_visual_row(row: list[tuple[int, dict[str, Any]]]) -> str:
|
||||
"""以字距推断缺失的 PDF 空白;仅大于常规字符间隔时补一个普通空格。"""
|
||||
rendered: list[str] = []
|
||||
previous: LayoutBBox | None = None
|
||||
for _index, glyph in row:
|
||||
bbox = _glyph_bbox(glyph)
|
||||
if previous is not None:
|
||||
typical_width = max((previous.x1 - previous.x0 + bbox.x1 - bbox.x0) / 2, 0.01)
|
||||
if bbox.x0 - previous.x1 > typical_width * 0.75:
|
||||
rendered.append(' ')
|
||||
rendered.append(str(glyph.get('text') or ''))
|
||||
previous = bbox
|
||||
return ''.join(rendered).strip()
|
||||
|
||||
|
||||
def _visual_rows(items: list[tuple[int, dict[str, Any]]]) -> list[list[tuple[int, dict[str, Any]]]]:
|
||||
"""将 bbox 中心 y 接近的字符归为视觉行,避免扫描页的微小坐标抖动拆行。"""
|
||||
rows: list[list[tuple[int, dict[str, Any]]]] = []
|
||||
for item in sorted(items, key=lambda pair: (_glyph_bbox(pair[1]).y0, _glyph_bbox(pair[1]).x0)):
|
||||
bbox = _glyph_bbox(item[1])
|
||||
if rows:
|
||||
previous = rows[-1]
|
||||
reference = _glyph_bbox(previous[0][1])
|
||||
tolerance = max((reference.y1 - reference.y0), (bbox.y1 - bbox.y0)) * 0.55
|
||||
if abs(((bbox.y0 + bbox.y1) / 2) - ((reference.y0 + reference.y1) / 2)) <= tolerance:
|
||||
previous.append(item)
|
||||
continue
|
||||
rows.append([item])
|
||||
return [sorted(row, key=lambda pair: _glyph_bbox(pair[1]).x0) for row in rows]
|
||||
|
||||
|
||||
def _layout_applies_to_page(layout: OrderFieldLayout, page_no: int) -> bool:
|
||||
"""执行订单字段页域;后续页重复值只在 all_pages 明确声明时作为冲突证据读取。"""
|
||||
return (
|
||||
(layout.page_scope == 'first_page' and page_no == 1)
|
||||
or layout.page_scope == 'all_pages'
|
||||
or (layout.page_scope == 'exact_page' and page_no == layout.page_no)
|
||||
)
|
||||
|
||||
|
||||
def _source_allowed(layout: OrderFieldLayout, *, config: dict[str, Any], source: str) -> bool:
|
||||
"""同时满足布局和 Schema 的坐标来源授权,OCR 永远不提升为 confirmed。"""
|
||||
allowed = set(config.get('allowed_sources') or [])
|
||||
if source not in allowed:
|
||||
return False
|
||||
required_levels = [layout.minimum_evidence_level]
|
||||
if layout.anchor is not None:
|
||||
required_levels.append(layout.anchor.minimum_evidence_level)
|
||||
return not ('coordinate' in required_levels and source != 'pdf_coordinate')
|
||||
|
||||
|
||||
def _absolute_relative_region(region: RelativeRegion | None, *, width: float, height: float) -> LayoutBBox:
|
||||
"""将固定低可靠度归一化页区投影为当前页面绝对框。"""
|
||||
if region is None:
|
||||
raise ValueError('fallback order field region is required')
|
||||
return LayoutBBox(x0=region.x0 * width, y0=region.y0 * height, x1=region.x1 * width, y1=region.y1 * height)
|
||||
|
||||
|
||||
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
|
||||
return LayoutBBox(
|
||||
x0=anchor.x0 + region.x0 * width, y0=anchor.y0 + region.y0 * height,
|
||||
x1=anchor.x0 + region.x1 * width, y1=anchor.y0 + region.y1 * height,
|
||||
)
|
||||
|
||||
|
||||
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:
|
||||
"""判断字符中心是否处于值区,边界字符仍归属到管理员确认的区域。"""
|
||||
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
|
||||
|
||||
|
||||
def _union_bbox(glyphs: list[dict[str, Any]]) -> LayoutBBox:
|
||||
"""求连续标签字符的最小联合框,作为相对值区投影的唯一参考。"""
|
||||
boxes = [_glyph_bbox(item) for item in glyphs]
|
||||
return LayoutBBox(x0=min(item.x0 for item in boxes), y0=min(item.y0 for item in boxes), x1=max(item.x1 for item in boxes), y1=max(item.y1 for item in boxes))
|
||||
|
||||
|
||||
def _unavailable(
|
||||
layout: OrderFieldLayout, issue: str, *, page_no: int | None = None, source: str | None = None,
|
||||
anchor_bbox: LayoutBBox | None = None, value_bbox: LayoutBBox | None = None,
|
||||
) -> OrderFieldExtraction:
|
||||
"""构造无可用坐标证据的失败关闭结果。"""
|
||||
return OrderFieldExtraction(field_id=layout.field_id, field_code=layout.field_code, status='unavailable', source=source, page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox, issues=[issue])
|
||||
|
||||
|
||||
def _review(
|
||||
layout: OrderFieldLayout, issue: str, page_no: int, source: str, anchor_bbox: LayoutBBox | None,
|
||||
value_bbox: LayoutBBox, selected: list[tuple[int, dict[str, Any]]],
|
||||
) -> OrderFieldExtraction:
|
||||
"""构造带最小证据索引的人工复核候选。"""
|
||||
return OrderFieldExtraction(
|
||||
field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source,
|
||||
page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox,
|
||||
glyph_indices=[index for index, _item in selected], issues=[issue],
|
||||
)
|
||||
@@ -62,15 +62,82 @@ class RelativeRegion(OrderProfileModel):
|
||||
return self
|
||||
|
||||
|
||||
class AnchorRelativeRegion(OrderProfileModel):
|
||||
"""表示相对锚点框宽高的值区偏移;允许标签右侧或下方落在锚点外。"""
|
||||
|
||||
# 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)
|
||||
y1: float = Field(ge=-12, le=12)
|
||||
|
||||
@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
|
||||
|
||||
|
||||
class AnchorRule(OrderProfileModel):
|
||||
"""定义模板匹配或行启动使用的稳定静态文字锚点。"""
|
||||
|
||||
anchor_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
text: str = Field(min_length=1, max_length=160)
|
||||
aliases: list[str] = Field(default_factory=list, max_length=16)
|
||||
match_mode: Literal['exact', 'contains'] = 'contains'
|
||||
region: RelativeRegion | None = None
|
||||
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_aliases(self) -> 'AnchorRule':
|
||||
"""只接受有限、去重的精确别名,避免把模糊词表当作自由匹配规则。"""
|
||||
aliases = [item.strip() for item in self.aliases]
|
||||
if any(not item for item in aliases) or len({item.casefold() for item in aliases}) != len(aliases):
|
||||
raise ValueError('anchor aliases must be non-empty and unique')
|
||||
if self.text.casefold() in {item.casefold() for item in aliases}:
|
||||
raise ValueError('anchor aliases must not repeat anchor text')
|
||||
return self
|
||||
|
||||
|
||||
class OrderFieldLayout(OrderProfileModel):
|
||||
"""定义独立订单级字段的锚点和值区;它绝不属于表头或物理明细行。"""
|
||||
|
||||
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
field_id: str = Field(min_length=1, max_length=128)
|
||||
field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
page_scope: Literal['first_page', 'all_pages', 'exact_page'] = 'first_page'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
anchor: AnchorRule | None = None
|
||||
# Anchored values use offsets relative to the anchor bbox; fixed-position
|
||||
# fallback values are stored separately so they cannot be mistaken for anchors.
|
||||
value_region: AnchorRelativeRegion | None = None
|
||||
fallback_value_region: RelativeRegion | None = None
|
||||
value_mode: Literal['single_line', 'multi_line', 'right_of_anchor', 'below_anchor'] = 'single_line'
|
||||
stop_anchors: list[AnchorRule] = Field(default_factory=list)
|
||||
normalizer_key: str | None = Field(default=None, min_length=1, max_length=64)
|
||||
required: bool = False
|
||||
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_order_field_layout(self) -> 'OrderFieldLayout':
|
||||
"""限制无锚点回退为单页值区,并要求多行字段有明确停止证据。"""
|
||||
if self.page_scope == 'exact_page' and self.page_no is None:
|
||||
raise ValueError('exact_page order field requires page_no')
|
||||
if self.page_scope != 'exact_page' and self.page_no is not None:
|
||||
raise ValueError('page_no is only allowed for exact_page order field')
|
||||
if self.anchor is None:
|
||||
if self.page_scope == 'all_pages':
|
||||
raise ValueError('value-only order field must have a bounded page scope')
|
||||
if self.value_region is not None or self.fallback_value_region is None:
|
||||
raise ValueError('value-only order field requires one fallback value region')
|
||||
elif self.value_region is None or self.fallback_value_region is not None:
|
||||
raise ValueError('anchored order field requires one anchor-relative value region')
|
||||
if self.value_mode == 'multi_line' and not self.stop_anchors:
|
||||
raise ValueError('multi-line order field requires stop anchors')
|
||||
return self
|
||||
|
||||
|
||||
class FieldRegion(OrderProfileModel):
|
||||
"""将一个管理员确认的坐标区域绑定至稳定 Schema field_code。"""
|
||||
@@ -141,12 +208,40 @@ class TerminationRule(OrderProfileModel):
|
||||
|
||||
|
||||
class DraftUnboundFieldRegion(OrderProfileModel):
|
||||
"""草稿阶段尚未绑定 Schema 的字段框;运行和发布均不得使用。"""
|
||||
"""草稿阶段尚未绑定 Schema 的字段框;仅迁移遗留项要求重新绑定。"""
|
||||
|
||||
region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$')
|
||||
parent_layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
label: str = Field(min_length=1, max_length=160)
|
||||
region: RelativeRegion
|
||||
requires_rebinding: bool = False
|
||||
|
||||
|
||||
class DraftUnboundOrderFieldLayout(OrderProfileModel):
|
||||
"""Schema 迁移后暂失绑定的订单字段区域;保留证据布局但禁止发布或运行。"""
|
||||
|
||||
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
label: str = Field(min_length=1, max_length=160)
|
||||
page_scope: Literal['first_page', 'all_pages', 'exact_page'] = 'first_page'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
anchor: AnchorRule | None = None
|
||||
value_region: AnchorRelativeRegion | None = None
|
||||
fallback_value_region: RelativeRegion | None = None
|
||||
value_mode: Literal['single_line', 'multi_line', 'right_of_anchor', 'below_anchor'] = 'single_line'
|
||||
stop_anchors: list[AnchorRule] = Field(default_factory=list)
|
||||
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_unbound_order_field_layout(self) -> 'DraftUnboundOrderFieldLayout':
|
||||
"""复用订单字段的区域互斥与页作用域规则,避免迁移草稿保存坏坐标。"""
|
||||
OrderFieldLayout(
|
||||
layout_id=self.layout_id, field_id='draft_unbound', field_code='draft_unbound',
|
||||
page_scope=self.page_scope, page_no=self.page_no, anchor=self.anchor,
|
||||
value_region=self.value_region, fallback_value_region=self.fallback_value_region,
|
||||
value_mode=self.value_mode, stop_anchors=self.stop_anchors,
|
||||
minimum_evidence_level=self.minimum_evidence_level,
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class TableRegionProfile(OrderProfileModel):
|
||||
@@ -230,6 +325,8 @@ class OrderCoordinateProfileV2(OrderProfileModel):
|
||||
version: int = Field(ge=1)
|
||||
document_match: DocumentMatchProfile
|
||||
table_regions: list[TableRegionProfile] = Field(min_length=1)
|
||||
order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list)
|
||||
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderCoordinateProfileV2':
|
||||
@@ -246,6 +343,15 @@ class OrderCoordinateProfileV2(OrderProfileModel):
|
||||
for table in self.table_regions:
|
||||
if not set(table.continuation_rule.required_anchor_ids).issubset(anchor_ids):
|
||||
raise ValueError('cross-page continuation anchor must be a document match anchor')
|
||||
order_layout_ids = [item.layout_id for item in self.order_field_layouts]
|
||||
if len(order_layout_ids) != len(set(order_layout_ids)):
|
||||
raise ValueError('order field layout ids must be unique')
|
||||
order_field_codes = [item.field_code for item in self.order_field_layouts]
|
||||
if len(order_field_codes) != len(set(order_field_codes)):
|
||||
raise ValueError('order field may bind only once')
|
||||
unbound_ids = [item.layout_id for item in self.draft_unbound_order_field_layouts]
|
||||
if len(unbound_ids) != len(set(unbound_ids)) or set(unbound_ids) & set(order_layout_ids):
|
||||
raise ValueError('bound and unbound order field layout ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
if not tables or not pages or not glyph_tables:
|
||||
return ProfileMatchResult(status='evidence_insufficient')
|
||||
|
||||
@@ -57,6 +58,7 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
|
||||
profile = OrderCoordinateProfileV2(
|
||||
profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0),
|
||||
document_match=definition.get('document_match'), table_regions=definition.get('table_regions'),
|
||||
order_field_layouts=definition.get('order_field_layouts') or [],
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
@@ -64,11 +66,15 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
|
||||
if len(tables) < len(profile.table_regions):
|
||||
reasons.append('table_region_count_insufficient')
|
||||
required = profile.document_match.required_anchors
|
||||
required_hits = [_anchor_present(anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, pages=pages) for anchor in required]
|
||||
required_hits = [_anchor_present(
|
||||
anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
) for anchor in required]
|
||||
if not all(required_hits):
|
||||
reasons.append('required_anchor_missing')
|
||||
optional = profile.document_match.optional_anchors
|
||||
optional_hits = sum(_anchor_present(anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, pages=pages) for anchor in optional)
|
||||
optional_hits = sum(_anchor_present(
|
||||
anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
) for anchor in optional)
|
||||
hard_match = not reasons
|
||||
# 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)
|
||||
@@ -92,14 +98,26 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
|
||||
)
|
||||
|
||||
|
||||
def _anchor_present(anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any], pages: dict[str, Any]) -> bool:
|
||||
"""检查静态锚点是否在指定页面区域出现;不读取订单业务字段或 HTML 网格。"""
|
||||
def _anchor_present(
|
||||
anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any],
|
||||
page_glyphs: dict[str, Any], pages: dict[str, Any],
|
||||
) -> bool:
|
||||
"""检查静态锚点是否在整页冻结字符中出现;旧快照才受限回退到表内证据。"""
|
||||
expected = str(anchor.get('text') or '').strip()
|
||||
if not expected:
|
||||
candidates = [expected, *[str(item).strip() for item in anchor.get('aliases') or []]]
|
||||
if not expected or not all(candidates):
|
||||
return False
|
||||
for table in tables:
|
||||
glyphs = glyph_tables.get(str(table.get('table_id') or ''))
|
||||
page = pages.get(str(table.get('page_no') or ''))
|
||||
page_numbers = sorted({str(item.get('page_no') or '') for item in tables if item.get('page_no')})
|
||||
for page_no in page_numbers:
|
||||
glyphs = page_glyphs.get(page_no)
|
||||
# v1 frozen snapshots do not have page glyphs. Preserve historical matching
|
||||
# rather than silently invalidating published profiles, but never merge rows here.
|
||||
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 [])
|
||||
]
|
||||
page = pages.get(page_no)
|
||||
if not isinstance(glyphs, list) or not isinstance(page, dict):
|
||||
continue
|
||||
selected = glyphs
|
||||
@@ -115,8 +133,8 @@ def _anchor_present(anchor: dict[str, Any], *, tables: list[dict[str, Any]], gly
|
||||
and y0 <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= y1]
|
||||
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))))
|
||||
if str(anchor.get('match_mode') or 'contains') == 'exact':
|
||||
if expected.casefold() == text.casefold():
|
||||
if any(candidate.casefold() == text.casefold() for candidate in candidates):
|
||||
return True
|
||||
elif expected.casefold() in text.casefold():
|
||||
elif any(candidate.casefold() in text.casefold() for candidate in candidates):
|
||||
return True
|
||||
return False
|
||||
@@ -175,7 +175,7 @@ def build_mineru_table_snapshot(
|
||||
content=content, mineru=candidate,
|
||||
)
|
||||
snapshot['layout_candidate'] = layout.model_dump(mode='json')
|
||||
# 仅保存表格范围内的原生字符坐标,供管理员确认后的坐标模板在 Run 冻结快照中复现。
|
||||
# 冻结表格与整页字符坐标:明细重建只消费前者,订单级字段只能消费后者。
|
||||
snapshot['coordinate_evidence'] = _table_coordinate_evidence(
|
||||
content=content, tables=tables,
|
||||
)
|
||||
@@ -187,7 +187,7 @@ def build_mineru_table_snapshot(
|
||||
|
||||
|
||||
def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""保存表内字符和内部页尺寸,使 v2 页面相对坐标可在冻结 Run 中精确换算。"""
|
||||
"""保存表内及整页原生字符和页尺寸,分别供明细与订单级字段确定性重放。"""
|
||||
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
|
||||
|
||||
pages = {item.page_no: item for item in extract_native_pdf_pages(content)}
|
||||
@@ -211,9 +211,34 @@ def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]])
|
||||
glyphs.append(item.model_dump(mode='json'))
|
||||
if glyphs:
|
||||
evidence[table_id] = glyphs
|
||||
page_glyphs: dict[str, list[dict[str, Any]]] = {}
|
||||
page_sources: dict[str, str] = {}
|
||||
for page_no, page in pages.items():
|
||||
native_glyphs = [item.model_dump(mode='json') for item in page.characters]
|
||||
if native_glyphs:
|
||||
page_glyphs[str(page_no)] = native_glyphs
|
||||
page_sources[str(page_no)] = 'pdf_coordinate'
|
||||
continue
|
||||
# Only scanned pages without a usable native text layer trigger OCR. OCR failure
|
||||
# intentionally leaves this page without order-field evidence rather than guessing.
|
||||
try:
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
|
||||
|
||||
ocr_lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
|
||||
ocr_glyphs = _ocr_page_characters(ocr_lines)
|
||||
except Exception:
|
||||
ocr_glyphs = []
|
||||
if ocr_glyphs:
|
||||
page_glyphs[str(page_no)] = ocr_glyphs
|
||||
page_sources[str(page_no)] = 'ocr_coordinate'
|
||||
return {
|
||||
'version': 'shipping_order_coordinate_evidence.v1',
|
||||
'tables': evidence,
|
||||
# 订单字段锚点可能位于表格外;只保存同一冻结 PDF 的最小字符证据,不向 Dify 暴露。
|
||||
'page_glyphs': page_glyphs,
|
||||
'sources': {
|
||||
'pages': page_sources,
|
||||
},
|
||||
# Internal runtime metadata only. It is removed with layout_snapshot before Dify input.
|
||||
'pages': {
|
||||
str(page_no): {'width': page.width, 'height': page.height}
|
||||
@@ -222,6 +247,29 @@ def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]])
|
||||
}
|
||||
|
||||
|
||||
def _ocr_page_characters(lines: list[Any]) -> list[dict[str, Any]]:
|
||||
"""把整页 OCR 行均匀拆成字符证据;仅服务订单字段锚点,不参与表格 cell 自动接受。"""
|
||||
result: list[dict[str, Any]] = []
|
||||
source_index = 0
|
||||
for line in lines:
|
||||
text = str(getattr(line, 'text', '') or '').strip()
|
||||
bbox = getattr(line, 'bbox', None)
|
||||
if not text or bbox is None:
|
||||
continue
|
||||
width = (bbox.x1 - bbox.x0) / len(text)
|
||||
if width <= 0:
|
||||
continue
|
||||
for index, character in enumerate(text):
|
||||
if character.isspace():
|
||||
continue
|
||||
result.append({'text': character, 'source_index': source_index, 'bbox': {
|
||||
'x0': bbox.x0 + index * width, 'y0': bbox.y0,
|
||||
'x1': bbox.x0 + (index + 1) * width, 'y1': bbox.y1,
|
||||
}})
|
||||
source_index += 1
|
||||
return result
|
||||
|
||||
|
||||
def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | None = None) -> None:
|
||||
"""就地为 NoticeIntakeResult 的根文件或 EML 附件补充布局快照,失败不阻断文本解析。"""
|
||||
meta = result.meta if isinstance(getattr(result, 'meta', None), dict) else {}
|
||||
|
||||
Reference in new issue
Block a user