""" backend/tests/test_shipping_document_layout_evaluation.py 用途:验证阶段 L0 人工真值契约和表格/单元格评测指标。 依赖:document_layout.evaluation、布局契约测试构造器。 逻辑:以不可逆构造样本模拟完整命中、漏单元格、字段错配和哈希漂移。 """ from __future__ import annotations from copy import deepcopy import pytest from pydantic import ValidationError from app.services.shipping_notice.document_layout.evaluation import ( PdfOrderQualityMetrics, review_pdf_order_quality_gate, evaluate_layout, ) from tests.test_shipping_document_layout_contract import _document def _annotation() -> dict: """为构造布局生成两页、两表、四单元格的人工真值。""" tables = [] for page_no, suffix, continuation in ((1, 'p1', None), (2, 'p2', 'truth-p1')): cells = [] for column, text, field_code in ((0, 'Part', 'part_number'), (1, 'Qty', 'qty')): x0 = 10 + column * 40 cells.append({ 'annotation_id': f'truth-cell-{suffix}-{column}', 'page_no': page_no, 'table_index': 0, 'row_index': 0, 'column_index': column, 'normalized_bbox': { 'x0': x0 / 100, 'y0': 0.1, 'x1': (x0 + 30) / 100, 'y1': 0.25, }, 'normalized_text': text, 'role': 'header', 'expected_field_code': field_code, }) tables.append({ 'annotation_id': f'truth-{suffix}', 'page_no': page_no, 'table_index': 0, 'normalized_bbox': {'x0': 0.05, 'y0': 0.05, 'x1': 0.95, 'y1': 0.55}, 'cells': cells, 'continuation_of': continuation, }) return { 'schema_version': 'shipping_document_layout_annotation.v1', 'layout_schema_version': 'shipping_document_layout.v1', 'sample_id': 'synthetic-two-page-table', 'content_hash': 'a' * 64, 'categories': ['native_pdf', 'cross_page_table'], 'tables': tables, } def test_evaluation_reports_perfect_layout_and_field_mapping(): """几何、行列和字段映射全部正确时四项指标均为 1。""" mapped = { 'cell-p1-0-0': 'part_number', 'cell-p1-0-1': 'qty', 'cell-p2-0-0': 'part_number', 'cell-p2-0-1': 'qty', } result = evaluate_layout(_annotation(), _document(), mapped_field_codes=mapped) assert result.table_detection_recall == 1 assert result.cell_detection_recall == 1 assert result.cell_position_accuracy == 1 assert result.field_mapping_accuracy == 1 def test_evaluation_separates_detection_position_and_field_errors(): """漏单元格与字段错配必须反映在不同指标,便于定位解析层或映射层问题。""" candidate = _document() candidate['pages'][1]['tables'][0]['rows'][0]['cells'].pop() mapped = { 'cell-p1-0-0': 'qty', 'cell-p1-0-1': 'qty', 'cell-p2-0-0': 'part_number', } result = evaluate_layout(_annotation(), candidate, mapped_field_codes=mapped) assert result.table_detection_recall == 1 assert result.cell_detection_recall == 0.75 assert result.cell_position_accuracy == 1 assert result.field_mapping_accuracy == 0.5 def test_evaluation_rejects_annotation_for_another_file(): """人工真值与候选文件哈希不一致时不得产生误导性指标。""" annotation = deepcopy(_annotation()) annotation['content_hash'] = 'b' * 64 with pytest.raises(ValueError, match='content_hash'): evaluate_layout(annotation, _document()) def test_evaluation_rejects_invalid_annotation_geometry(): """人工真值坐标越界或单元格超出父表时必须在评测前拒绝。""" outside_page = _annotation() outside_page['tables'][0]['normalized_bbox']['x1'] = 1.1 with pytest.raises(ValidationError, match='within 0..1'): evaluate_layout(outside_page, _document()) outside_table = _annotation() outside_table['tables'][0]['cells'][0]['normalized_bbox']['x0'] = 0.01 with pytest.raises(ValidationError, match='within parent table'): evaluate_layout(outside_table, _document()) def _pdf_order_truth(*, categories: list[str], status: str = 'active') -> dict: """构造脱敏 PDF 订单行真值,覆盖删除归属和高风险字段的阶段门禁。""" line = { 'line_id': 'line-00020', 'table_annotation_id': 'table-1', 'line_cell_ids': ['cell-item-00020', 'cell-qty-00020'], 'status': status, 'fields': [{ 'field_code': 'qty', 'value': 30, 'evidence_cell_ids': ['cell-qty-00020'], }], } if status == 'deleted': line['line_id'] = 'line-00010' line['deletion_marker_cell_id'] = 'cell-item-deleted' return { 'schema_version': 'shipping_pdf_order_truth.v1', 'sample_id': f'sample-{status}', 'content_hash': 'c' * 64, 'categories': categories, 'lines': [line], } def test_pdf_order_quality_gate_passes_only_when_all_safety_rules_hold(): """六类样本齐全且零误删、零高风险误放行、零漏复核时才允许进入下一阶段。""" truth = [_pdf_order_truth(categories=[ 'normal_multi_line', 'continued_row', 'deleted_line', 'cross_page_header', 'scanned_ocr', 'unreadable_pdf', ])] gate = review_pdf_order_quality_gate(truth, PdfOrderQualityMetrics( active_truth_lines=1, deleted_truth_lines=1, active_lines_auto_released=1, active_lines_misdeleted=0, high_risk_auto_released_fields=1, incorrect_high_risk_auto_released_fields=0, unreliable_truth_lines=1, unreliable_lines_sent_to_review=1, )) assert gate.passed is True assert gate.reasons == [] def test_pdf_order_quality_gate_blocks_missing_categories_and_unsafe_results(): """缺样本、误删有效行、错误放行或漏转复核中任一项存在时必须阻断阶段推进。""" gate = review_pdf_order_quality_gate( [_pdf_order_truth(categories=['deleted_line'])], { 'active_truth_lines': 1, 'deleted_truth_lines': 1, 'active_lines_auto_released': 0, 'active_lines_misdeleted': 1, 'high_risk_auto_released_fields': 2, 'incorrect_high_risk_auto_released_fields': 1, 'unreliable_truth_lines': 2, 'unreliable_lines_sent_to_review': 1, }, ) assert gate.passed is False assert 'active_order_line_misdeleted' in gate.reasons assert 'incorrect_high_risk_field_auto_released' in gate.reasons assert 'unreliable_order_line_not_sent_to_review' in gate.reasons assert any(reason.startswith('pdf_order_truth_categories_missing:') for reason in gate.reasons) def test_pdf_order_truth_requires_a_marker_for_deleted_line_but_allows_review_truth(): """删除归属缺证据必须拒绝;待复核行保留真值字段,供漏转复核评测使用。""" deleted = _pdf_order_truth(categories=['deleted_line'], status='deleted') deleted['lines'][0].pop('deletion_marker_cell_id') with pytest.raises(ValidationError, match='deletion_marker_cell_id'): review_pdf_order_quality_gate([deleted], { 'active_truth_lines': 0, 'deleted_truth_lines': 1, 'active_lines_auto_released': 0, 'active_lines_misdeleted': 0, 'high_risk_auto_released_fields': 0, 'incorrect_high_risk_auto_released_fields': 0, 'unreliable_truth_lines': 0, 'unreliable_lines_sent_to_review': 0, }) review = _pdf_order_truth(categories=['unreadable_pdf'], status='needs_review') assert review_pdf_order_quality_gate([review], { 'active_truth_lines': 0, 'deleted_truth_lines': 0, 'active_lines_auto_released': 0, 'active_lines_misdeleted': 0, 'high_risk_auto_released_fields': 0, 'incorrect_high_risk_auto_released_fields': 0, 'unreliable_truth_lines': 1, 'unreliable_lines_sent_to_review': 1, }).passed is False