feat(shipping-notice): 收敛订单处理状态与履约门禁
This commit is contained in:
1 parent
bffcd55b40
commit
70dd0051b8
153 files changed
+10916
-4296
No files matched your search
+206
-26
@@ -177,6 +177,7 @@ def reconstruct_coordinate_profile_rows_with_strategy(
|
||||
dynamic_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
|
||||
table_region=table_region, termination_rules=termination_rules,
|
||||
# dynamic 不执行普通排除过滤,但其专用排除区仍授权删除标记。
|
||||
exclusion_regions=dynamic_exclusion_regions or [], line_start_field_code=line_start_field_code,
|
||||
include_deleted=include_deleted, row_reconstruction_mode='dynamic_x_columns',
|
||||
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
|
||||
@@ -567,6 +568,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
_absolute_relative_region(bbox, item)
|
||||
for item in (exclusion_regions or []) if isinstance(item, dict)
|
||||
]
|
||||
marker_authorization_exclusions = exclusions
|
||||
# 直接调用动态候选时,传入的旧式排除区无法区分表头/普通排除;为兼容其
|
||||
# “表头可移动”语义不应用它。统一入口则显式传入 dynamic_exclusion_regions,
|
||||
# 从而保留管理员配置的普通排除区。
|
||||
@@ -583,10 +585,10 @@ def reconstruct_coordinate_profile_rows(
|
||||
continue
|
||||
band_indices = {glyph_index for glyph_index, _glyph in band}
|
||||
marker_indices.update(band_indices)
|
||||
if exclusions and any(
|
||||
if marker_authorization_exclusions and any(
|
||||
_inside_region(glyph.bbox, region)
|
||||
for _glyph_index, glyph in band
|
||||
for region in exclusions
|
||||
for region in marker_authorization_exclusions
|
||||
):
|
||||
authorized_marker_indices.update(band_indices)
|
||||
# [STEP 2] 普通排除区内容与未授权删除文字都不参与字段重建;已授权删除标记保留到行状态判定。
|
||||
@@ -604,7 +606,8 @@ def reconstruct_coordinate_profile_rows(
|
||||
# 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 == 'dynamic_x_columns':
|
||||
return _reconstruct_dynamic_x_columns_profile_rows(
|
||||
return _resolve_shifted_part_number_candidates(
|
||||
rows=_reconstruct_dynamic_x_columns_profile_rows(
|
||||
glyphs=glyphs,
|
||||
table_bbox=bbox,
|
||||
ordered_layouts=ordered_layouts,
|
||||
@@ -612,9 +615,13 @@ def reconstruct_coordinate_profile_rows(
|
||||
include_deleted=include_deleted,
|
||||
line_start_field_code=start_field_code,
|
||||
schema_fields=schema_fields,
|
||||
),
|
||||
glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
|
||||
line_start_field_code=start_field_code,
|
||||
)
|
||||
if row_reconstruction_mode == 'adaptive_record_columns':
|
||||
return _reconstruct_adaptive_record_columns_profile_rows(
|
||||
return _resolve_shifted_part_number_candidates(
|
||||
rows=_reconstruct_adaptive_record_columns_profile_rows(
|
||||
glyphs=glyphs,
|
||||
table_bbox=bbox,
|
||||
ordered_layouts=ordered_layouts,
|
||||
@@ -622,6 +629,9 @@ def reconstruct_coordinate_profile_rows(
|
||||
include_deleted=include_deleted,
|
||||
line_start_field_code=start_field_code,
|
||||
schema_fields=schema_fields,
|
||||
),
|
||||
glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
|
||||
line_start_field_code=start_field_code,
|
||||
)
|
||||
|
||||
relative_y_rows = _reconstruct_relative_y_profile_rows(
|
||||
@@ -636,7 +646,10 @@ def reconstruct_coordinate_profile_rows(
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
if relative_y_rows is not None:
|
||||
return relative_y_rows
|
||||
return _resolve_shifted_part_number_candidates(
|
||||
rows=relative_y_rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
|
||||
line_start_field_code=start_field_code,
|
||||
)
|
||||
|
||||
def values_for(
|
||||
band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any],
|
||||
@@ -730,7 +743,11 @@ def reconstruct_coordinate_profile_rows(
|
||||
current_issues.extend(continuation_issues)
|
||||
next_offset += 1
|
||||
flush()
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
rows = results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
return _resolve_shifted_part_number_candidates(
|
||||
rows=rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
|
||||
line_start_field_code=start_field_code,
|
||||
)
|
||||
|
||||
|
||||
def _project_coordinate_profile_regions(
|
||||
@@ -960,12 +977,23 @@ def _reconstruct_dynamic_x_columns_profile_rows(
|
||||
delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center
|
||||
values: dict[str, str] = {}
|
||||
issues: list[str] = []
|
||||
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 _row_index, band in record
|
||||
)
|
||||
for field in fields:
|
||||
code = str(field['field_code'])
|
||||
saved = _absolute_relative_region(table_bbox, field['region'])
|
||||
# [STEP 3] 整体上移可把宽字段框推过页面顶端;截断页外部分,
|
||||
# 保持 LayoutBBox 的非负原点和正面积契约。
|
||||
shifted_y0 = max(0.0, saved.y0 + delta_y)
|
||||
region = LayoutBBox(
|
||||
x0=saved.x0, y0=saved.y0 + delta_y,
|
||||
x1=saved.x1, y1=saved.y1 + delta_y,
|
||||
x0=saved.x0, y0=shifted_y0,
|
||||
x1=saved.x1, y1=max(shifted_y0 + 1e-6, saved.y1 + delta_y),
|
||||
)
|
||||
selected_bands = [
|
||||
band for _row_index, band in record
|
||||
@@ -990,7 +1018,7 @@ def _reconstruct_dynamic_x_columns_profile_rows(
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _band in record],
|
||||
role='data', issues=issues,
|
||||
role='deleted' if deleted else 'data', issues=issues,
|
||||
))
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
|
||||
@@ -1157,6 +1185,19 @@ def _reconstruct_relative_y_profile_rows(
|
||||
start_region = _absolute_relative_region(table_bbox, start_field['region'])
|
||||
expected_anchor_center = (start_region.y0 + start_region.y1) / 2
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
sample_record = usable_bands[anchors[0]:anchors[1] if len(anchors) > 1 else len(usable_bands)]
|
||||
expected_indices = _calibrate_field_band_indices(
|
||||
fields=fields, sample_record=sample_record, table_bbox=table_bbox,
|
||||
)
|
||||
multiline_fields = {
|
||||
id(field) for field in fields
|
||||
if sum(
|
||||
_regions_overlap_vertically(
|
||||
_absolute_relative_region(table_bbox, field['region']), _band_bbox(band),
|
||||
)
|
||||
for _row_index, band in sample_record
|
||||
) > 1
|
||||
}
|
||||
for anchor_index, start in enumerate(anchors):
|
||||
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands)
|
||||
record = usable_bands[start:end]
|
||||
@@ -1176,23 +1217,56 @@ def _reconstruct_relative_y_profile_rows(
|
||||
x0=saved.x0, y0=saved.y0 + delta_y,
|
||||
x1=saved.x1, y1=saved.y1 + delta_y,
|
||||
)
|
||||
# A visual field box may intentionally span multiple PDF text lines
|
||||
# (for example a wrapped customer part number). The previous
|
||||
# one-band assignment treated that as an ambiguity and dropped the
|
||||
# field, which caused two vertically stacked part-number fields to
|
||||
# become empty or reuse the same prefix. When the configured field
|
||||
# region intersects multiple bands, read all of its own glyphs;
|
||||
# single-band fields retain the calibrated matching behavior.
|
||||
intersecting = [
|
||||
band for _row_index, band in record
|
||||
if _regions_overlap_vertically(region, _band_bbox(band))
|
||||
]
|
||||
if not intersecting:
|
||||
continue
|
||||
raw = _text_in_multiline_region(
|
||||
intersecting, region,
|
||||
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
|
||||
)
|
||||
if id(field) not in multiline_fields:
|
||||
intersecting = [
|
||||
band for _row_index, band in record
|
||||
if _regions_overlap_vertically(region, _band_bbox(band))
|
||||
]
|
||||
raw = _text_in_horizontal_region(intersecting[0], region) if intersecting else ''
|
||||
if code == 'part_number':
|
||||
expected_index = expected_indices.get(id(field), 0)
|
||||
candidates: list[tuple[float, int, str]] = []
|
||||
for candidate_index in range(expected_index, len(record)):
|
||||
candidate_raw = _text_in_horizontal_region(record[candidate_index][1], region)
|
||||
if _is_structured_part_identifier(candidate_raw):
|
||||
compact_candidate = re.sub(r'\s+', '', candidate_raw)
|
||||
candidates.append((
|
||||
_profile_field_band_score(
|
||||
raw=candidate_raw, field_code=code,
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'),
|
||||
),
|
||||
candidate_index, candidate_raw,
|
||||
))
|
||||
if re.search(r'\d', compact_candidate):
|
||||
candidates[-1] = (candidates[-1][0] + .5, *candidates[-1][1:])
|
||||
candidates.sort(key=lambda item: (-item[0], item[1]))
|
||||
if len(candidates) == 1:
|
||||
raw = candidates[0][2]
|
||||
elif len(candidates) > 1:
|
||||
best = candidates[0]
|
||||
if best[0] > candidates[1][0] + .25:
|
||||
raw = best[2]
|
||||
else:
|
||||
issues.append(f'coordinate_profile_field_band_ambiguous:{code}')
|
||||
raw = ''
|
||||
else:
|
||||
# A visual field box may intentionally span multiple PDF text lines
|
||||
# (for example a wrapped customer part number). The previous
|
||||
# one-band assignment treated that as an ambiguity and dropped the
|
||||
# field, which caused two vertically stacked part-number fields to
|
||||
# become empty or reuse the same prefix. When the configured field
|
||||
# region intersects multiple bands, read all of its own glyphs;
|
||||
# single-band fields retain the calibrated matching behavior.
|
||||
intersecting = [
|
||||
band for _row_index, band in record
|
||||
if _regions_overlap_vertically(region, _band_bbox(band))
|
||||
]
|
||||
if not intersecting:
|
||||
continue
|
||||
raw = _text_in_multiline_region(
|
||||
intersecting, region,
|
||||
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
|
||||
)
|
||||
if not raw:
|
||||
continue
|
||||
extracted = extract_profile_field_value(
|
||||
@@ -1890,6 +1964,112 @@ def _profile_field_band_score(*, raw: str, field_code: str, extractor_key: str)
|
||||
return score
|
||||
|
||||
|
||||
def _is_structured_part_identifier(raw: str) -> bool:
|
||||
"""仅将带数字或连接符的料号作为纠偏证据,普通描述词保持原框位。"""
|
||||
value = str(raw or '').strip()
|
||||
compact = re.sub(r'\s+', '', value)
|
||||
return bool(
|
||||
not re.match(r'^(?:revision|rev)\s*:', value, re.IGNORECASE)
|
||||
and
|
||||
re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/-]{2,}', compact)
|
||||
and re.search(r'\d|[._:/-]', compact)
|
||||
)
|
||||
|
||||
|
||||
def _resolve_shifted_part_number_candidates(
|
||||
*, rows: list[CoordinateProfileLogicalRow],
|
||||
glyphs: list[tuple[int, PositionedCharacter]],
|
||||
ordered_layouts: list[dict[str, Any]],
|
||||
table_bbox: LayoutBBox,
|
||||
line_start_field_code: str,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""在多子行模板中跳过描述折行,裁决后续唯一结构化内部料号。
|
||||
|
||||
固定/自适应/动态三种重建都可能先把描述折行绑定到内部料号框;这里复核当前
|
||||
逻辑记录的后续候选,唯一高置信候选才替换,多个候选则保留 Review,避免改变
|
||||
没有折行的其他模板。
|
||||
"""
|
||||
part_fields = [
|
||||
field for layout in ordered_layouts
|
||||
for field in (layout.get('field_regions') or [])
|
||||
if isinstance(field, dict) and str(field.get('field_code') or '') == 'part_number'
|
||||
and isinstance(field.get('region'), dict)
|
||||
]
|
||||
if not part_fields:
|
||||
return rows
|
||||
part_start_offset = min(
|
||||
offset for offset, layout in enumerate(ordered_layouts)
|
||||
if any(field in (layout.get('field_regions') or []) for field in part_fields)
|
||||
)
|
||||
# 主行内的料号没有“预期下一子行”这一语义。只纠正被标在后续子行的字段,
|
||||
# 避免跨到价格、日期或表尾文本中寻找候选,保持已有单行模板的解析边界。
|
||||
if part_start_offset == 0:
|
||||
return rows
|
||||
bands = _group_visual_rows(glyphs)
|
||||
main_fields = ordered_layouts[0].get('field_regions') or []
|
||||
start_field = next(
|
||||
(
|
||||
field for field in main_fields
|
||||
if isinstance(field, dict)
|
||||
and str(field.get('field_code') or '') == line_start_field_code
|
||||
and isinstance(field.get('region'), dict)
|
||||
),
|
||||
None,
|
||||
)
|
||||
start_region = (
|
||||
_absolute_relative_region(table_bbox, start_field['region'])
|
||||
if start_field is not None else None
|
||||
)
|
||||
|
||||
for row_position, row in enumerate(rows):
|
||||
current = str(row.fields.get('part_number') or '').strip()
|
||||
if not current or not row.source_row_indices:
|
||||
continue
|
||||
record_start = min(row.source_row_indices)
|
||||
record_end = (
|
||||
min(min(next_row.source_row_indices) for next_row in rows[row_position + 1:])
|
||||
if row_position + 1 < len(rows) else len(bands)
|
||||
)
|
||||
candidates: list[tuple[float, int, str]] = []
|
||||
# 从该记录中 part_number 的预期子行开始重扫;当前值本身若只是折行描述,
|
||||
# 会被跳过,后续唯一结构化候选才可替换。不能按 source_row_indices 末端起步,
|
||||
# 因为自适应重建可能已把后续候选 band 一并吸收到当前行。
|
||||
expected_index = record_start + part_start_offset
|
||||
scan_start = expected_index
|
||||
for index in range(scan_start, record_end):
|
||||
# 末条记录也必须以视觉上的下一起行锚点截断;后续解析策略可能因
|
||||
# 表尾规则不产出该行,但不能让它泄漏进当前记录的料号候选池。
|
||||
if index > record_start and start_region is not None:
|
||||
start_raw = _text_in_horizontal_region(bands[index], start_region)
|
||||
if is_valid_line_start_value(start_raw):
|
||||
break
|
||||
for field in part_fields:
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
raw = _text_in_horizontal_region(bands[index], region)
|
||||
if raw.strip() == current:
|
||||
continue
|
||||
if not _is_structured_part_identifier(raw):
|
||||
continue
|
||||
score = _profile_field_band_score(
|
||||
raw=raw, field_code='part_number',
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'),
|
||||
)
|
||||
score -= abs(index - expected_index) * .5
|
||||
if re.search(r'\d', re.sub(r'\s+', '', raw)):
|
||||
score += .5
|
||||
candidates.append((score, index, raw))
|
||||
candidates.sort(key=lambda item: (-item[0], item[1]))
|
||||
if len(candidates) == 1:
|
||||
row.fields['part_number'] = candidates[0][2]
|
||||
elif len(candidates) > 1:
|
||||
if candidates[0][0] > candidates[1][0] + .25:
|
||||
row.fields['part_number'] = candidates[0][2]
|
||||
else:
|
||||
row.fields.pop('part_number', None)
|
||||
row.issues.append('coordinate_profile_field_band_ambiguous:part_number')
|
||||
return rows
|
||||
|
||||
|
||||
def _text_in_region(
|
||||
band: list[tuple[int, PositionedCharacter]], region: LayoutBBox,
|
||||
) -> str:
|
||||
|
||||
@@ -380,6 +380,8 @@ def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any])
|
||||
segment.pop('handling', None)
|
||||
segment.pop('target_field_id', None)
|
||||
segment.pop('target_field_code', None)
|
||||
# segment_id 是段记录标识而非拆分逻辑(matcher/normalization/relation),不得进入内容指纹。
|
||||
segment.pop('segment_id', None)
|
||||
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
|
||||
|
||||
|
||||
|
||||
@@ -464,10 +464,13 @@ def _map_data_row(
|
||||
if _is_repeated_header(grid, row_index=row_index, columns=columns, contract=contract):
|
||||
return HtmlMappedRow(row_index=row_index, role='repeated_header')
|
||||
joined = ' '.join(normalized)
|
||||
if 'item deleted' in joined or 'deleted item' in joined or '项目已删除' in joined or '項目已刪除' in joined:
|
||||
# 删除标记是业务内容关键词,不区分大小写;normalize_table_header 保留表头大小写。
|
||||
marker_joined = joined.lower()
|
||||
if 'item deleted' in marker_joined or 'deleted item' in marker_joined or '项目已删除' in joined or '項目已刪除' in joined:
|
||||
return HtmlMappedRow(row_index=row_index, role='deleted')
|
||||
first = next((item for item in normalized if item), '')
|
||||
if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first):
|
||||
# 合计标记同样是业务内容关键词,按小写匹配 'Total'/'TOTAL'/'Subtotal' 等常见大小写。
|
||||
if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first.lower()):
|
||||
return HtmlMappedRow(row_index=row_index, role='summary')
|
||||
if _has_explicit_zero_quantity(row, columns=columns):
|
||||
return HtmlMappedRow(row_index=row_index, role='deleted')
|
||||
@@ -581,7 +584,8 @@ def _is_exclusive_deletion_marker_row(grid: HtmlGrid, row_index: int) -> bool:
|
||||
if not texts:
|
||||
return False
|
||||
markers = {'item deleted', 'deleted item', '项目已删除', '項目已刪除'}
|
||||
return all(text in markers for text in texts)
|
||||
# 删除标记占整行的内容为业务关键词,按小写匹配,避免大小写差异漏判。
|
||||
return all(text.lower() in markers for text in texts)
|
||||
|
||||
|
||||
def _header_candidates(grid: HtmlGrid, *, row_index: int, column_index: int) -> list[str]:
|
||||
|
||||
@@ -32,6 +32,10 @@ def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str
|
||||
if field_code == 'reservation_id':
|
||||
value = validated_reservation_id(text)
|
||||
return {field_code: value} if value else {}
|
||||
if field_code == 'uom':
|
||||
# 单位剔除数字(如 '0 PCS' → 'PCS'),避免相邻数量字段数字串入单位。
|
||||
stripped = re.sub(r'\d+', '', text).strip()
|
||||
return {field_code: stripped} if stripped else {}
|
||||
return {field_code: text}
|
||||
if extractor_key == 'temp_internal_parts':
|
||||
resolved = resolve_composite_part_numbers(text)
|
||||
|
||||
@@ -1383,6 +1383,28 @@ def _bbox_overlap(left: list[float], right: list[float]) -> float:
|
||||
_HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
|
||||
|
||||
|
||||
def _band_headers_match_signature(
|
||||
*, band_tokens: list[str], signature: dict[str, Any] | None,
|
||||
) -> bool:
|
||||
"""判断冻结表头带读到的 token 是否足以代表签名表头。
|
||||
|
||||
只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”,
|
||||
直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行)
|
||||
需要回退到表体顶部的结构搜索。
|
||||
"""
|
||||
expected = [
|
||||
str(token).casefold()
|
||||
for pattern in (signature or {}).get('table_patterns') or []
|
||||
if isinstance(pattern, dict)
|
||||
for token in pattern.get('header_tokens') or []
|
||||
]
|
||||
if not expected or not band_tokens:
|
||||
return False
|
||||
observed = [str(token).casefold() for token in band_tokens]
|
||||
matched = sum(1 for token in expected if token in observed)
|
||||
return matched / len(expected) >= 0.5
|
||||
|
||||
|
||||
def _observe_primary_table_header(
|
||||
*,
|
||||
glyph_tables: dict[str, Any],
|
||||
@@ -1391,7 +1413,13 @@ def _observe_primary_table_header(
|
||||
primary_bbox: list[float] | None,
|
||||
signature: dict[str, Any] | None,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""仅从实际主表 bbox 顶部观测表头,与签名生成保持同一证据口径。"""
|
||||
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。
|
||||
|
||||
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用(保持既有行为,
|
||||
不影响正常模板)。若固定带失准(表体因上方内容折行/加行而上移或下移,带读空或读到
|
||||
错误行),则基于已定位表体顶部做表头行搜索(与压缩快照路径一致的候选行选择逻辑),
|
||||
从而对上移/下移/任意行数位移都健壮,且不依赖上方可变内容。
|
||||
"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return [], [], []
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
|
||||
@@ -1419,11 +1447,28 @@ def _observe_primary_table_header(
|
||||
item for item in positioned_token_spans(header_glyphs, respect_explicit_spaces=False)
|
||||
if _usable_observed_header_token(str(item.get('text') or ''))
|
||||
][:32]
|
||||
tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
|
||||
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
|
||||
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
|
||||
band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
|
||||
table_span = max(primary_bbox[2] - primary_bbox[0], 0.0001)
|
||||
widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
|
||||
return tokens, centers, widths
|
||||
band_widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
|
||||
# 固定带有效 → 直接沿用(对正常模板零影响)。
|
||||
if _band_headers_match_signature(band_tokens=band_tokens, signature=signature):
|
||||
return band_tokens, band_centers, band_widths
|
||||
# 固定带失准(位移场景)→ 基于已定位表体顶部做表头行搜索,选与签名最匹配的一行。
|
||||
candidates = [{
|
||||
'bbox': primary_bbox,
|
||||
'header_candidates': _observe_header_candidates(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox,
|
||||
),
|
||||
}]
|
||||
selected = _select_persisted_header_candidate(candidates=candidates, signature=signature)
|
||||
if selected is not None:
|
||||
header, _ = selected
|
||||
return (
|
||||
[str(token).casefold() for token in header['header_tokens']],
|
||||
header['column_centers'], header['column_width_ratios'],
|
||||
)
|
||||
return band_tokens, band_centers, band_widths
|
||||
|
||||
|
||||
def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None:
|
||||
|
||||
+183
-2
@@ -14,6 +14,15 @@ from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
|
||||
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
|
||||
LayoutBBox,
|
||||
_absolute_relative_region,
|
||||
_group_visual_rows,
|
||||
_inside_horizontal_region,
|
||||
_table_glyphs,
|
||||
_text_in_horizontal_region,
|
||||
coordinate_profile_character_candidates,
|
||||
)
|
||||
|
||||
|
||||
_NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$')
|
||||
@@ -84,12 +93,14 @@ def validate_profile_parse_candidate(
|
||||
fields=header_bound, glyphs=glyphs, page=page,
|
||||
)
|
||||
|
||||
# [STEP 2] Line 字段覆盖
|
||||
# [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报)
|
||||
line_fields = [
|
||||
field for table in profile.table_regions for layout in table.line_layouts
|
||||
for field in layout.field_regions if field.scope == 'line'
|
||||
]
|
||||
line_coverage = _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page)
|
||||
line_coverage = _line_region_coverage_shift_tolerant(
|
||||
profile=profile, glyphs=glyphs, page=page, layout=layout,
|
||||
)
|
||||
|
||||
# [STEP 3] 明细行数启发式
|
||||
line_count = _estimate_line_count(profile=profile, glyphs=glyphs, page=page)
|
||||
@@ -207,6 +218,176 @@ def _field_validation_region(field: Any) -> dict[str, Any] | None:
|
||||
return None
|
||||
|
||||
|
||||
def _line_region_coverage_shift_tolerant(
|
||||
*,
|
||||
profile: OrderCoordinateProfile,
|
||||
glyphs: list[dict[str, Any]],
|
||||
page: dict[str, Any],
|
||||
layout: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""按行重建同源的位移容忍字符窗口与视觉行横向重叠,统计 line 字段覆盖率。
|
||||
|
||||
核心逻辑:legacy 模板把字段区冻结在标注样本的绝对页坐标,但实际物理表可能整体
|
||||
纵向位移;若沿用冻结区域做严格中心包含读取,位移后的字段会读空,导致
|
||||
``profile_parse_line_coverage_insufficient`` 误报。行重建 ``values_for`` 是把字段
|
||||
区域按横向边界投影到所在视觉行(只做 x 重叠、y 来自真实行带),与是否位移无关。
|
||||
此处对齐同一套语义:先按当前表区定位物理表,构造位移容忍的字符窗口,再按视觉行
|
||||
做横向重叠覆盖;定位不到物理表时回退到冻结区域严格读取。
|
||||
|
||||
Args:
|
||||
profile: 当前候选 Profile(含 table_regions)。
|
||||
glyphs: 当前页冻结坐标字符。
|
||||
page: 当前页尺寸。
|
||||
layout: 冻结 layout,含 coordinate_evidence 的 tables/page_glyphs。
|
||||
|
||||
Returns:
|
||||
{coverage_ratio, empty_region_count, total_region_count}。
|
||||
"""
|
||||
if not profile.table_regions:
|
||||
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
|
||||
line_fields = [
|
||||
field for table in profile.table_regions for layout_item in table.line_layouts
|
||||
for field in layout_item.field_regions if field.scope == 'line'
|
||||
]
|
||||
if not line_fields:
|
||||
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
|
||||
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
page_glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
# 定位与主表区(首个含 line_layouts 的表区)重叠且在 page 上的物理表;取重叠面积最大者。
|
||||
primary_region = next(
|
||||
(table for table in profile.table_regions if table.line_layouts), None,
|
||||
)
|
||||
raw_table = _locate_overlapping_raw_table(
|
||||
primary_region=primary_region, layout=layout, page=page, profile=profile,
|
||||
)
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
table_region = primary_region.region.model_dump() if primary_region is not None else None
|
||||
reference_page_frame = _reference_page_frame_mapping(profile, page)
|
||||
reconstruction_page_bbox = {
|
||||
'x0': 0.0, 'y0': 0.0,
|
||||
'x1': float(reference_page_frame['width']) if reference_page_frame is not None else width,
|
||||
'y1': float(reference_page_frame['height']) if reference_page_frame is not None else height,
|
||||
}
|
||||
# 位移容忍字符窗口:表区横向始终有效,纵向扩展至定位到的物理表框。
|
||||
characters, _ = coordinate_profile_character_candidates(
|
||||
table_region=table_region or {},
|
||||
page_size=page, reference_page_frame=reference_page_frame,
|
||||
page_characters=glyphs if isinstance(glyphs, list) else None,
|
||||
table_characters=(
|
||||
page_glyph_tables.get(raw_table.get('table_id'))
|
||||
if raw_table is not None and isinstance(page_glyph_tables.get(raw_table.get('table_id')), list)
|
||||
else None
|
||||
),
|
||||
raw_table_bbox=(raw_table.get('bbox') if raw_table is not None else None),
|
||||
table_id=(raw_table.get('table_id') if raw_table is not None else None),
|
||||
page_no=1, coordinate_transform=None, allow_table_fallback=True,
|
||||
)
|
||||
if not isinstance(characters, list) or not characters:
|
||||
return _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page)
|
||||
|
||||
page_bbox = _LayoutBBox_from_dict(reconstruction_page_bbox)
|
||||
glyphs_in_table = _table_glyphs(characters, page_bbox)
|
||||
visual_rows = _group_visual_rows(glyphs_in_table)
|
||||
non_empty = 0
|
||||
measurable = 0
|
||||
for field in line_fields:
|
||||
relative = field.region.model_dump() if hasattr(field.region, 'model_dump') else field.region
|
||||
if not isinstance(relative, dict):
|
||||
continue
|
||||
measurable += 1
|
||||
absolute = _absolute_relative_region(page_bbox, relative)
|
||||
if _region_is_covered(visual_rows=visual_rows, region=absolute):
|
||||
non_empty += 1
|
||||
total = measurable
|
||||
return {
|
||||
'coverage_ratio': non_empty / total if total else 1.0,
|
||||
'empty_region_count': total - non_empty,
|
||||
'total_region_count': total,
|
||||
}
|
||||
|
||||
|
||||
def _reference_page_frame_mapping(profile: OrderCoordinateProfile, page: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""读取 Profile 冻结的首页参考页框;缺失时返回 None(由调用方回退到页面尺寸)。"""
|
||||
reference = profile.reference_page_frames.get(1)
|
||||
if reference is None:
|
||||
return None
|
||||
return reference.model_dump() if hasattr(reference, 'model_dump') else reference
|
||||
|
||||
|
||||
def _LayoutBBox_from_dict(value: dict[str, Any]) -> Any:
|
||||
"""将页面框 dict 包装为 LayoutBBox,供重建辅助函数读取绝对坐标。"""
|
||||
if isinstance(value, LayoutBBox):
|
||||
return value
|
||||
return LayoutBBox.model_validate(value)
|
||||
|
||||
|
||||
def _locate_overlapping_raw_table(
|
||||
*,
|
||||
primary_region: Any,
|
||||
layout: dict[str, Any],
|
||||
page: dict[str, Any],
|
||||
profile: OrderCoordinateProfile,
|
||||
) -> dict[str, Any] | None:
|
||||
"""在 layout.tables 中找出与主表区纵向交叠且位于当前页、重叠面积最大的物理表。
|
||||
|
||||
命中不到物理表(例如整页字符回退、虚拟页)时返回 None,由调用方维持冻结严格读取,
|
||||
避免把无物理表的场景误判为已定位到明细表。
|
||||
"""
|
||||
if primary_region is None:
|
||||
return None
|
||||
reference_page_frame = _reference_page_frame_mapping(profile, page)
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
projection_width = float(reference_page_frame['width']) if reference_page_frame is not None else width
|
||||
projection_height = float(reference_page_frame['height']) if reference_page_frame is not None else height
|
||||
if projection_width <= 0 or projection_height <= 0:
|
||||
return None
|
||||
relative = primary_region.region.model_dump() if hasattr(primary_region.region, 'model_dump') else primary_region.region
|
||||
if not isinstance(relative, dict):
|
||||
return None
|
||||
try:
|
||||
absolute_region = {
|
||||
'x0': float(relative['x0']) * projection_width,
|
||||
'y0': float(relative['y0']) * projection_height,
|
||||
'x1': float(relative['x1']) * projection_width,
|
||||
'y1': float(relative['y1']) * projection_height,
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
best: dict[str, Any] | None = None
|
||||
best_overlap = 0.0
|
||||
for raw_table in layout.get('tables') or []:
|
||||
if not isinstance(raw_table, dict) or int(raw_table.get('page_no') or 1) != 1:
|
||||
continue
|
||||
bbox = raw_table.get('bbox')
|
||||
if not isinstance(bbox, dict):
|
||||
continue
|
||||
overlap_x = (
|
||||
min(float(bbox.get('x1', 0)), absolute_region['x1'])
|
||||
- max(float(bbox.get('x0', 0)), absolute_region['x0'])
|
||||
)
|
||||
overlap_y = (
|
||||
min(float(bbox.get('y1', 0)), absolute_region['y1'])
|
||||
- max(float(bbox.get('y0', 0)), absolute_region['y0'])
|
||||
)
|
||||
if overlap_x <= 0 or overlap_y <= 0:
|
||||
continue
|
||||
overlap_area = overlap_x * overlap_y
|
||||
if overlap_area > best_overlap:
|
||||
best_overlap = overlap_area
|
||||
best = raw_table
|
||||
return best
|
||||
|
||||
|
||||
def _region_is_covered(visual_rows: list[list[tuple[int, Any]]], region: Any) -> bool:
|
||||
"""判断任一视觉行在字段横向边界内是否出现非空文字,忽略冻结纵向位置。"""
|
||||
for band in visual_rows:
|
||||
selected = [item for item in band if _inside_horizontal_region(item[1].bbox, region)]
|
||||
if _text_in_horizontal_region(selected, region).strip():
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _estimate_line_count(
|
||||
*,
|
||||
profile: OrderCoordinateProfile,
|
||||
|
||||
Reference in new issue
Block a user