fix(contract): 纯图片扫描 PDF 坐标高亮与 OCR 复核

This commit is contained in:
sophie committed 2026-07-29 08:56:13 +08:00
1 parent ca312ea751
commit ce1fd59f61
21 files changed
+1665 -54

No files matched your search

@@ -3,7 +3,7 @@ tests/services/procurement_contract/test_pdf_annotation.py
用途:验证采购合同 PDF 证据锚定、坐标字段和高亮批注输出。
依赖:procurement_contract.pdf_annotation、pypdfium2、pypdf。
逻辑:覆盖文本型 PDF 精确高亮,以及扫描 PDF 按 OCR 分页正文添加页级批注意见。
逻辑:覆盖文本型 PDF 精确高亮、纯图片 PDF OCR 行框高亮,以及无坐标时的页级批注降级。
"""
from __future__ import annotations
@@ -108,6 +108,108 @@ def test_annotate_scanned_pdf_from_ocr_page_text():
assert len(reader.pages[1].get("/Annots", [])) >= 1
def test_annotate_image_only_pdf_from_persisted_ocr_line_boxes():
"""纯图片 PDF 应把归一化 OCR 行框转换成 PDF 坐标并写入矩形高亮。"""
writer = PdfWriter()
writer.add_blank_page(width=600, height=800)
buffer = io.BytesIO()
writer.write(buffer)
item = {
"title": "设备使用地变更",
"change_type": "modify",
"risk_level": "ok",
"detail": "设备使用地发生变化。",
"old_text": "3.设备使用地:一厂。",
"new_text": "3.设备使用地:二厂。",
}
ocr_layout = {
"version": 1,
"coordinate_space": "normalized_top_left",
"pages": [
{
"page_no": 1,
"lines": [
{
"text": "3.设备使用地:一厂。",
"confidence": 0.98,
"polygon": [[0.1, 0.2], [0.5, 0.2], [0.5, 0.24], [0.1, 0.24]],
}
],
}
],
}
anchor = pdf_annotation.locate_ocr_layout_evidence(ocr_layout, item)
assert anchor is not None
assert anchor["page_no"] == 1
assert anchor["method"] == "ocr_bbox_exact"
assert anchor["ocr_polygons"]
annotated = pdf_annotation.build_annotated_pdf_bytes(
buffer.getvalue(),
[item],
ocr_layout=ocr_layout,
)
reader = PdfReader(io.BytesIO(annotated))
annotations = reader.pages[0].get("/Annots", [])
assert len(annotations) == 1
# 关键断言:写入的是矩形 Highlight,而不是只能指示页码的 Text 批注。
assert annotations[0].get_object().get("/Subtype") == "/Highlight"
def test_ocr_line_box_anchor_falls_back_to_stable_field_label():
"""OCR 把一厂错成二厂时,完整句不一致仍应通过稳定字段名定位同一行。"""
item = {
"title": "设备使用地变更",
"change_type": "modify",
"risk_level": "ok",
"old_text": "3.设备使用地:一厂。",
"new_text": "3.设备使用地:二厂。",
}
layout = {
"pages": [
{
"page_no": 2,
"lines": [
{
"text": "3.设备使用地:一厂。",
"polygon": [[0.1, 0.3], [0.4, 0.3], [0.4, 0.34], [0.1, 0.34]],
}
],
}
]
}
anchor = pdf_annotation.locate_ocr_layout_evidence(layout, item)
assert anchor is not None
assert anchor["page_no"] == 2
assert "设备使用地" in anchor["matched_text"]
def test_enrich_anchors_compare_change_even_when_risk_is_ok(monkeypatch):
"""未发现风险的已确认比对改动仍属于标注对象,不能因 risk_level=ok 被跳过。"""
expected_anchor = {"page_no": 1, "rects": [[1, 2, 3, 4]], "method": "exact"}
monkeypatch.setattr(pdf_annotation, "locate_pdf_evidence", lambda *_args, **_kwargs: expected_anchor)
result = {
"summary_json": {},
"clauses_json": [
{
"change_type": "modify",
"risk_level": "ok",
"new_text": "设备使用地:二厂",
}
],
}
enriched = pdf_annotation.enrich_result_with_pdf_anchors(
result,
filename="contract.pdf",
pdf_bytes=b"test",
)
assert enriched["clauses_json"][0]["evidence_anchor"] == expected_anchor
assert enriched["summary_json"]["evidence_anchoring"]["anchored"] == 1
def test_annotate_returns_original_pdf_when_no_finding_can_be_anchored():
"""没有可定位证据时下载仍应成功,返回未加批注的合同副本。"""
pdf_bytes = _sample_pdf_bytes()
@@ -1,9 +1,9 @@
"""
backend/tests/services/procurement_contract/test_preprocessing.py
用途:验证采购合同调用 MinerU 的请求协议、Markdown 读取与故障回退前提。
用途:验证采购合同调用 MinerU 的请求协议、Markdown 读取、OCR 坐标产物与故障回退前提。
依赖:procurement_contract.preprocessing、Flask 最小应用上下文。
逻辑:模拟测试环境 MinerU 的 `/file_parse` 返回,确保 PDF 解析产物可审计且不依赖服务端文件名。
逻辑:模拟测试环境 MinerU 和 edkb 产物,确保 PDF 解析结果与纯图片行坐标可审计、可归档。
"""
from io import BytesIO
@@ -144,3 +144,37 @@ def test_extract_page_texts_uses_mineru_logical_page_when_pdf_has_no_text_layer(
# The logical page is only an anchor fallback; physical attachment page counts remain unavailable.
assert pages == ["兹因甲方向乙方购买设备\n第一条 价格不变。\n本合同一式两份。\n甲方:和信公司"]
assert warning == "PDF native page text unavailable; used MinerU logical page for body boundaries"
def test_ocr_layout_from_edkb_keeps_pdf_page_line_polygons(tmp_path):
"""edkb 已识别的 PDF 整页行框应直接复用,避免合同预处理重复 OCR。"""
raw_layout = tmp_path / "01_raw_layout.json"
raw_layout.write_text(
"""
[
{
"id": "ocr-pdf-page-2",
"page": 2,
"type": "ocr_text",
"text": "OCR_TEXT: 设备使用地:一厂",
"bbox": [0, 0, 1000, 1000],
"meta": {
"page_image": true,
"ocr_lines": [
{
"text": "设备使用地:一厂",
"confidence": 0.98,
"polygon": [[0.1, 0.2], [0.4, 0.2], [0.4, 0.24], [0.1, 0.24]]
}
]
}
}
]
""",
encoding="utf-8",
)
pages = preprocessing._ocr_layout_from_edkb(raw_layout)
assert pages[0]["page_no"] == 2
assert pages[0]["lines"][0]["text"] == "设备使用地:一厂"
assert pages[0]["lines"][0]["polygon"][0] == [0.1, 0.2]
@@ -0,0 +1,307 @@
"""
backend/tests/services/procurement_contract/test_visual_ocr_validation.py
用途:验证混合提取合同的双边同源 OCR 复核只移除地点字段和视觉设备表噪声差异。
依赖:visual_ocr_validation;页面定位和 OCR 在单元测试中替换为确定性结果。
逻辑:构造 compare 差异 → 模拟文字层/扫描件及页面 OCR → 断言移除、保留和诊断分支。
"""
from app.services.procurement_contract import analyze, visual_ocr_validation
def _compare_result(item: dict) -> dict:
"""构造包含一个差异项的最小 compare 结果,便于验证复核后的统计。"""
return {
"summary_json": {
"mode": "compare",
"comparison_quality": {"ignored_ocr_noise": 2},
"focus_lights": [
{
"key": "delivery",
"label": "交期",
"status": "changed",
"risk_level": "medium",
"change_count": 1,
}
],
},
"clauses_json": [item],
}
def _location_modify() -> dict:
"""返回本次真实问题对应的设备使用地 OCR 差异。"""
return {
"clause_no": "1",
"title": "设备使用地变更",
"clause_category": "commercial",
"change_type": "modify",
"risk_level": "ok",
"old_text": "3.设备使用地:一厂。",
"new_text": "3.设备使用地:二。",
}
def _run(monkeypatch, result: dict, *, original_ocr: str, returned_ocr: str) -> dict:
"""固定为文字原合同与扫描回传合同,并注入双方命中页 OCR 行。"""
profiles = iter([
{"page_count": 3, "native_text_pages": 3},
{"page_count": 3, "native_text_pages": 0},
])
monkeypatch.setattr(visual_ocr_validation, "_pdf_text_profile", lambda _data: next(profiles))
monkeypatch.setattr(visual_ocr_validation, "_locate_page", lambda **_kwargs: 2)
page_results = iter([
{2: [{"text": original_ocr}]},
{2: [{"text": returned_ocr}]},
])
monkeypatch.setattr(
visual_ocr_validation,
"_ocr_pdf_pages",
lambda _data, _pages: next(page_results),
)
return visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
result,
review_no="CR-TEST",
original_filename="original.pdf",
original_pdf_bytes=b"original",
original_extraction_meta={"mode": "mineru"},
original_ocr_layout={},
returned_filename="returned.pdf",
returned_pdf_bytes=b"returned",
returned_extraction_meta={"mode": "edkb_system"},
returned_ocr_layout={"pages": []},
)
def _ocr_line(text: str, left: float, top: float, right: float, bottom: float) -> dict:
"""构造带像素框的 OCR 行,模拟 RapidOCR 表格检测结果。"""
return {
"text": text,
"pixel_polygon": [[left, top], [right, top], [right, bottom], [left, bottom]],
}
def _equipment_page_lines(*, model: str = "BC-MD601", quantity: str = "2") -> list[dict]:
"""构造含空品牌列的标准设备表,验证后续列不会左移。"""
return [
_ocr_line("序号", 100, 100, 150, 125),
_ocr_line("设备名称", 220, 100, 330, 125),
_ocr_line("品牌", 400, 100, 455, 125),
_ocr_line("型号", 525, 100, 580, 125),
_ocr_line("数量", 670, 100, 725, 125),
_ocr_line("单价", 805, 100, 860, 125),
_ocr_line("总价", 945, 100, 1000, 125),
_ocr_line("1", 115, 150, 130, 175),
_ocr_line("半自动拉铆钉机", 205, 150, 350, 175),
_ocr_line(model, 500, 150, 610, 175),
_ocr_line(quantity, 690, 150, 705, 175),
_ocr_line("18,600", 790, 150, 875, 175),
_ocr_line("37,200", 930, 150, 1015, 175),
_ocr_line("合计", 430, 200, 485, 225),
]
def _equipment_result() -> dict:
"""构造截图中的型号漏列修改项及其无文本新增伴随项。"""
modify = {
"clause_no": "1",
"title": "合同内容变更",
"change_type": "modify",
"change_class": "commercial",
"risk_level": "ok",
"old_text": "1|半自动拉铆钉机|BC-MD601|2|18,600|37,200",
"new_text": "1|半自动拉铆钉机|2|18,600|37,200",
}
insert = {
"clause_no": "2",
"title": "合同内容变更",
"change_type": "insert",
"change_class": "commercial",
"risk_level": "ok",
"old_text": "",
"new_text": "",
"detail": "供应商回传合同新增了交易条件或清单信息,请以变更对照为准。",
}
result = _compare_result(modify)
result["clauses_json"].append(insert)
return result
def _run_equipment(monkeypatch, *, original_lines: list[dict], returned_lines: list[dict]) -> dict:
"""注入双方第一页设备表 OCR,执行混合提取视觉复核。"""
profiles = iter([
{"page_count": 5, "native_text_pages": 5},
{"page_count": 6, "native_text_pages": 0},
])
monkeypatch.setattr(visual_ocr_validation, "_pdf_text_profile", lambda _data: next(profiles))
monkeypatch.setattr(visual_ocr_validation, "_table_candidate_pages", lambda **_kwargs: {1})
page_results = iter([{1: original_lines}, {1: returned_lines}])
monkeypatch.setattr(
visual_ocr_validation,
"_ocr_pdf_pages",
lambda _data, _pages: next(page_results),
)
return visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
_equipment_result(),
review_no="CR-TABLE",
original_filename="original.pdf",
original_pdf_bytes=b"original",
original_extraction_meta={"mode": "mineru"},
original_ocr_layout={},
returned_filename="returned.pdf",
returned_pdf_bytes=b"returned",
returned_extraction_meta={"mode": "mineru"},
returned_ocr_layout={},
)
def test_same_visual_ocr_removes_location_noise_and_records_diagnostic(monkeypatch):
"""双方视觉 OCR 同为“二”时应移除文本层“一厂 vs 二”的伪差异。"""
result = _run(
monkeypatch,
_compare_result(_location_modify()),
original_ocr="3.设备使用地:二。",
returned_ocr="3.设备使用地:二。",
)
result = analyze.rebuild_result(result)
assert result["clauses_json"] == [] # 关键断言:只移除经双边视觉证明一致的差异。
assert result["summary_json"]["total_changes"] == 0
assert result["total_change_count"] == 0
quality = result["summary_json"]["comparison_quality"]
assert quality["ignored_ocr_noise"] == 3
assert quality["visual_ocr_rechecks"]["ignored"] == 1
assert quality["visual_ocr_rechecks"]["items"][0]["decision"] == "ignored"
assert result["summary_json"]["focus_lights"][0]["status"] == "unchanged"
def test_different_visual_ocr_keeps_location_difference(monkeypatch):
"""双方视觉 OCR 不一致时必须保留差异,避免复核扩大为内容忽略器。"""
result = _run(
monkeypatch,
_compare_result(_location_modify()),
original_ocr="3.设备使用地:一厂。",
returned_ocr="3.设备使用地:二厂。",
)
assert result["clauses_json"] == [_location_modify()]
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["ignored"] == 0
assert diagnostic["kept"] == 1
assert diagnostic["items"][0]["reason"] == "visual_ocr_differs"
def test_numeric_field_is_never_auto_ignored(monkeypatch):
"""金额等关键数值字段即使双边 OCR 相同,也不得进入地点字段白名单。"""
item = {
"change_type": "modify",
"old_text": "合同总价:10000元",
"new_text": "合同总价:20000元",
"risk_level": "high",
}
result = _run(
monkeypatch,
_compare_result(item),
original_ocr="合同总价:20000元",
returned_ocr="合同总价:20000元",
)
assert result["clauses_json"] == [item]
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["checked"] == 0
assert diagnostic["reason"] == "no_eligible_visual_recheck"
def test_insert_and_delete_are_never_auto_ignored(monkeypatch):
"""单侧新增/删除缺少双边对应字段,不执行同源 OCR 自动忽略。"""
item = _location_modify()
item["change_type"] = "insert"
item["old_text"] = ""
result = _run(
monkeypatch,
_compare_result(item),
original_ocr="设备使用地:二厂",
returned_ocr="设备使用地:二厂",
)
assert result["clauses_json"] == [item]
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["checked"] == 0
def test_page_location_failure_keeps_difference_without_running_ocr(monkeypatch):
"""任一侧页码定位失败时保留差异并给出 page_not_located 诊断。"""
profiles = iter([
{"page_count": 3, "native_text_pages": 3},
{"page_count": 3, "native_text_pages": 0},
])
monkeypatch.setattr(visual_ocr_validation, "_pdf_text_profile", lambda _data: next(profiles))
monkeypatch.setattr(visual_ocr_validation, "_locate_page", lambda **_kwargs: None)
monkeypatch.setattr(
visual_ocr_validation,
"_ocr_pdf_pages",
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("OCR must not run")),
)
result = visual_ocr_validation.suppress_mixed_extraction_ocr_noise(
_compare_result(_location_modify()),
review_no="CR-TEST",
original_filename="original.pdf",
original_pdf_bytes=b"original",
original_extraction_meta={"mode": "mineru"},
original_ocr_layout={},
returned_filename="returned.pdf",
returned_pdf_bytes=b"returned",
returned_extraction_meta={"mode": "edkb_system"},
returned_ocr_layout={},
)
assert len(result["clauses_json"]) == 1
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["kept"] == 1
assert diagnostic["items"][0]["reason"] == "page_not_located"
def test_same_visual_equipment_table_removes_modify_and_empty_insert(monkeypatch):
"""双方视觉设备表一致时,型号漏列修改及同表空新增项应一起移除。"""
result = _run_equipment(
monkeypatch,
original_lines=_equipment_page_lines(),
returned_lines=_equipment_page_lines(),
)
result = analyze.rebuild_result(result)
assert result["clauses_json"] == [] # 关键断言:表格线性化产生的两个伪差异同时消失。
assert result["summary_json"]["total_changes"] == 0
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["ignored"] == 2
assert diagnostic["kept"] == 0
assert diagnostic["items"][0]["validation_type"] == "equipment_table"
assert diagnostic["items"][0]["reason"] == "same_visual_equipment_table"
def test_visual_equipment_table_keeps_real_model_change(monkeypatch):
"""型号真实变化会使设备表键不同,修改和新增项均保留。"""
result = _run_equipment(
monkeypatch,
original_lines=_equipment_page_lines(model="BC-MD601"),
returned_lines=_equipment_page_lines(model="BC-MD602"),
)
assert len(result["clauses_json"]) == 2
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["ignored"] == 0
assert diagnostic["items"][0]["reason"] == "visual_table_differs"
def test_visual_equipment_table_keeps_real_quantity_change(monkeypatch):
"""数量真实变化不得被空品牌列容错吞掉。"""
result = _run_equipment(
monkeypatch,
original_lines=_equipment_page_lines(quantity="2"),
returned_lines=_equipment_page_lines(quantity="3"),
)
assert len(result["clauses_json"]) == 2
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["items"][0]["reason"] == "visual_table_differs"