feat(shipping-notice): 增强订单抽取与审计功能,支持取消与保留策略

- 在环境配置中新增进度细化、订单提取取消与审计导出相关的开关
- 实现订单抽取运行的取消功能,允许管理员在运行中进行操作
- 引入审计事件的保留策略,支持三年保留期的自动清理
- 更新相关模型与服务,确保新功能的完整性与可追溯性
- 增强文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
hugo committed 2026-07-30 14:52:21 +08:00
1 parent c85997884b
commit 95cdfe66b0
158 files changed
+19005 -1201

No files matched your search

@@ -497,9 +497,9 @@ def _matches_termination_rule(
if not absolute.y0 <= center_y <= absolute.y1:
continue
if str(anchor.get('match_mode') or 'contains') == 'exact':
if text.casefold() == expected.casefold():
if text == expected:
return True
elif expected.casefold() in text.casefold():
elif expected in text:
return True
return False
@@ -1116,8 +1116,8 @@ def _text_in_horizontal_region(
def _normalized_header_text(value: str) -> str:
"""标准化表头候选,允许空格、斜线和标点差异但不执行模糊语义猜测。"""
return re.sub(r'[^a-z0-9]+', '', value.lower())
"""标准化表头候选,允许空格、斜线和标点差异但严格保留大小写。"""
return re.sub(r'[^A-Za-z0-9]+', '', value)
def _group_visual_rows(glyphs: list[tuple[int, PositionedCharacter]]) -> list[list[tuple[int, PositionedCharacter]]]:
@@ -430,9 +430,9 @@ def _not_ready(grid: HtmlGrid, issue: str) -> OpenCVTableGeometryResult:
def _normalized_cell_text(value: Any) -> str:
"""以 NFKC、大小写折叠和字母数字/中日韩字符保留生成文本一致性比较键。"""
"""以 NFKC 和字母数字/中日韩字符保留生成严格大小写的一致性比较键。"""
import re
import unicodedata
text = unicodedata.normalize('NFKC', str(value or '')).casefold()
return re.sub(r'[^0-9a-z\u4e00-\u9fff]+', '', text)
text = unicodedata.normalize('NFKC', str(value or ''))
return re.sub(r'[^0-9A-Za-z\u4e00-\u9fff]+', '', text)
@@ -283,9 +283,11 @@ def _find_anchor_matches(
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()
# Field anchors are part of the frozen Schema/Profile contract; matching
# them case-sensitively prevents one label from being mistaken for another.
folded = row_text
for label in expected:
normalized = re.sub(r'\s+', '', label).casefold()
normalized = re.sub(r'\s+', '', label)
start = 0
while normalized and (position := folded.find(normalized, start)) >= 0:
consumed = compact[position:position + len(normalized)]
@@ -94,9 +94,9 @@ class AnchorRule(OrderProfileModel):
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):
if any(not item for item in aliases) or len(set(aliases)) != len(aliases):
raise ValueError('anchor aliases must be non-empty and unique')
if self.text.casefold() in {item.casefold() for item in aliases}:
if self.text in set(aliases):
raise ValueError('anchor aliases must not repeat anchor text')
return self
@@ -305,13 +305,26 @@ class TableRegionProfile(OrderProfileModel):
return self
class DocumentMatchAnchor(OrderProfileModel):
"""文档匹配锚点以管理员框选的标签和值区域验证关系,禁止全文纯文本命中。"""
anchor_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
label: str = Field(min_length=1, max_length=160)
value: str = Field(min_length=1, max_length=200)
value_position: Literal['right', 'below'] = 'right'
page_no: int | None = Field(default=None, ge=1)
label_region: RelativeRegion | None = None
value_region: RelativeRegion | None = None
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
class DocumentMatchProfile(OrderProfileModel):
"""定义模板唯一匹配所需的静态证据;动态订单业务值不可进入此对象。"""
"""定义模板唯一匹配所需的标签-值证据;动态订单业务值不可进入此对象。"""
document_type: Literal['purchase_order'] = 'purchase_order'
page_pattern: Literal['one_or_more'] = 'one_or_more'
required_anchors: list[AnchorRule] = Field(default_factory=list)
optional_anchors: list[AnchorRule] = Field(default_factory=list)
required_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
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)
@@ -15,6 +15,11 @@ from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfileV2
def _anchor_comparable_text(value: Any) -> str:
"""规范化锚点比较文本,兼容 PDF 字符逐字拼接后丢失的版面空白。"""
return ''.join(str(value or '').casefold().split())
class ProfileMatchCandidate(BaseModel):
"""记录单个冻结 Profile 的非敏感匹配分数和失败原因。"""
@@ -103,19 +108,47 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
)
def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
"""按视觉行重组冻结字符,供标签和值的相对位置校验使用。"""
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 {}
try:
center_y = (float(bbox.get('y0')) + float(bbox.get('y1'))) / 2
height = float(bbox.get('y1')) - float(bbox.get('y0'))
except (TypeError, ValueError):
continue
if lines:
previous = lines[-1]
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:
previous.append(glyph)
continue
lines.append([glyph])
return [
_anchor_comparable_text(''.join(str(item.get('text') or '') for item in sorted(line, key=lambda item: item.get('bbox', {}).get('x0', 0))))
for line in lines
]
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()
candidates = [expected, *[str(item).strip() for item in anchor.get('aliases') or []]]
if not expected or not all(candidates):
"""只在固定标签右侧或下方验证固定值,避免备注中的同文案误命中模板。"""
label = _anchor_comparable_text(anchor.get('label'))
expected = _anchor_comparable_text(anchor.get('value'))
position = str(anchor.get('value_position') or '')
if not label or not expected or position not in {'right', 'below'}:
return False
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:
if anchor.get('page_no') is not None and str(anchor.get('page_no')) != page_no:
continue
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.
@@ -127,21 +160,47 @@ def _anchor_present(
page = pages.get(page_no)
if not isinstance(glyphs, list) or not isinstance(page, dict):
continue
selected = glyphs
region = anchor.get('region')
if isinstance(region, dict):
lines = _page_text_lines(glyphs)
label_region = anchor.get('label_region')
value_region = anchor.get('value_region')
if isinstance(label_region, dict) and isinstance(value_region, dict):
try:
width, height = float(page['width']), float(page['height'])
x0, y0, x1, y1 = float(region['x0']) * width, float(region['y0']) * height, float(region['x1']) * width, float(region['y1']) * height
def region_text(region: dict[str, Any]) -> str:
# Center containment separates adjacent lines. Existing edge-only
# regions keep a narrow same-line overlap fallback below.
selected = [item for item in glyphs if isinstance(item.get('bbox'), dict)
and float(region['x0']) * width <= (float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 <= float(region['x1']) * width
and float(region['y0']) * height <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= float(region['y1']) * height]
if not selected:
overlaps = [item for item in glyphs if isinstance(item.get('bbox'), dict)
and float(item['bbox'].get('x1', 0)) >= float(region['x0']) * width
and float(item['bbox'].get('x0', 0)) <= float(region['x1']) * width
and float(item['bbox'].get('y1', 0)) >= float(region['y0']) * height
and float(item['bbox'].get('y0', 0)) <= float(region['y1']) * height]
if overlaps:
target_y = (float(region['y0']) + float(region['y1'])) * height / 2
reference = min(overlaps, key=lambda item: abs(
(float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 - target_y,
))
reference_box = reference['bbox']
reference_y = (float(reference_box.get('y0', 0)) + float(reference_box.get('y1', 0))) / 2
reference_height = max(1.0, float(reference_box.get('y1', 0)) - float(reference_box.get('y0', 0)))
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)))))
if label in region_text(label_region) and expected in region_text(value_region):
return True
except (KeyError, TypeError, ValueError):
continue
selected = [item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)
and x0 <= (float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 <= x1
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 any(candidate.casefold() == text.casefold() for candidate in candidates):
continue
for index, line in enumerate(lines):
label_index = line.find(label)
if label_index < 0:
continue
if position == 'right' and expected in line[label_index + len(label):]:
return True
if position == 'below' and index + 1 < len(lines) and expected in lines[index + 1]:
return True
elif any(candidate.casefold() in text.casefold() for candidate in candidates):
return True
return False
@@ -168,9 +168,9 @@ def _normalized_character_stream(
def _normalize_text(value: Any) -> str:
"""以 NFKC/casefold 保留字母数字和中日韩字符,忽略版面空白及标点。"""
text = unicodedata.normalize('NFKC', str(value or '')).casefold()
return re.sub(r'[^0-9a-z\u4e00-\u9fff]+', '', text)
"""以 NFKC 保留字母数字和中日韩字符,忽略版面空白及标点但保留大小写。"""
text = unicodedata.normalize('NFKC', str(value or ''))
return re.sub(r'[^0-9A-Za-z\u4e00-\u9fff]+', '', text)
def _bbox_center_within(parent: LayoutBBox, child: LayoutBBox) -> bool: