fix(contract): 继续优化合同审核方案

This commit is contained in:
sophie committed 2026-07-30 11:51:45 +08:00
1 parent 8415653365
commit dce915ea30
12 files changed
+195 -59

No files matched your search

@@ -60,6 +60,7 @@ _CATEGORY_LABELS = {
"force_majeure": "不可抗力",
}
_COMMERCIAL_LIST_TERMS = ("设备名称", "品牌", "型号", "数量", "单价", "总价", "规格", "参数", "配置")
_SCHEDULE_TERMS = _COMMERCIAL_LIST_TERMS + ("清单", "明细", "附件")
_RISK_RANK = {"ok": 0, "low": 1, "medium": 2, "high": 3}
_OBLIGATION_CATEGORIES = frozenset(_ACTIONABLE_DIFF_TERMS)
_METADATA_TERMS = ("合同编号", "合同号", "甲方", "乙方", "买方", "卖方", "供应商", "地址", "联系人", "电话")
@@ -1132,6 +1133,21 @@ def _compare_change_category(old_text: str, new_text: str) -> str:
return local_category if local_category != "other" else _clause_category(f"{old_value}\n{new_value}")
def _compare_change_title(change_type: str, category: str, old_text: str, new_text: str) -> str:
"""
为清单类单边变更生成事实标题,避免结果卡退化为笼统的“合同内容变更”。
核心逻辑:仅依据实际 Diff 文本识别设备、价格或配置清单;其他条款仍沿用业务类别标题,
不把风险规则或模型推测写成合同事实。
"""
blob = f"{old_text}\n{new_text}"
if change_type == "insert" and _contains_any(blob, _SCHEDULE_TERMS):
return "回传合同新增清单"
if change_type == "delete" and _contains_any(blob, _SCHEDULE_TERMS):
return "回传合同删除清单"
return f"{_CATEGORY_LABELS.get(category, '合同内容')}变更"
def structure_contract_clauses(clean_text: str) -> list[dict[str, Any]]:
"""
将清洗后的合同正文切成带稳定序号的条款列表供 Dify 全量遍历。
@@ -1732,7 +1748,7 @@ def analyze_compare(
else "ok"
)
change_type = {"replace": "modify", "delete": "delete", "insert": "insert"}.get(tag, tag)
title = f"{_CATEGORY_LABELS.get(category, '合同内容')}变更"
title = _compare_change_title(change_type, category, old_raw, new_raw)
clauses.append(
{
"clause_no": str(idx),
@@ -12,6 +12,7 @@ from __future__ import annotations
import logging
import re
import unicodedata
from difflib import SequenceMatcher
from typing import Any
from app.services.procurement_contract import pdf_annotation
@@ -42,6 +43,18 @@ _LOCATION_FIELD_LABELS = frozenset({
"安装地点",
"使用地点",
})
_CRITICAL_VALUE_HINTS = (
"金额", "价款", "价税", "单价", "总价", "付款", "支付", "比例", "%",
"日期", "期限", "交货期", "交付期", "数量", "型号", "规格", "税率",
)
_CRITICAL_VALUE_PATTERNS = (
r"\d{4}[年/-]\d{1,2}[月/-]\d{1,2}",
r"\d+(?:\.\d+)?\s*[%%]",
r"(?:人民币|RMB|CNY|USD|¥|¥)\s*\d",
r"\d[\d,]*(?:\.\d{1,2})?\s*(?:元|万元|万元整)",
r"\d+\s*(?:套|台|件|个|只|箱|批|吨|千克|KG|kg|台)",
r"(?=[A-Za-z0-9-]{5,})(?=[A-Za-z0-9-]*[A-Za-z])(?=[A-Za-z0-9-]*\d)[A-Za-z0-9-]+",
)
def _compact_text(value: Any) -> str:
@@ -72,6 +85,27 @@ def _eligible_location_field(item: dict[str, Any]) -> str | None:
return old_label
def _eligible_high_similarity_field(item: dict[str, Any]) -> bool:
"""
判断无稳定字段标签的高相似 modify 是否可进入视觉 OCR 复核。
核心逻辑:仅允许长文本中的少量字符识别差异;金额、日期、比例、数量、型号和
明确的关键字段始终保留确定性 Diff,不能借 OCR 一致自动忽略。
"""
if str(item.get("change_type") or "") != "modify":
return False
old_key = _compact_text(item.get("old_text"))
new_key = _compact_text(item.get("new_text"))
if min(len(old_key), len(new_key)) < 8 or old_key == new_key:
return False
blob = "\n".join(str(item.get(key) or "") for key in ("title", "old_text", "new_text"))
if any(hint in blob for hint in _CRITICAL_VALUE_HINTS):
return False
if any(re.search(pattern, blob, re.IGNORECASE) for pattern in _CRITICAL_VALUE_PATTERNS):
return False
return SequenceMatcher(None, old_key, new_key).ratio() >= 0.85
def _pdf_text_profile(pdf_bytes: bytes) -> dict[str, int] | None:
"""
检查 PDF 是否含可搜索文字层,用于确认双方是否属于混合提取模式。
@@ -185,6 +219,21 @@ def _matching_field_line(lines: list[dict[str, Any]], field_label: str) -> str:
return ""
def _matching_similar_line(lines: list[dict[str, Any]], expected_text: str) -> str:
"""从 OCR 行及相邻行窗口中选出最接近原始差异文本的视觉行,供无标签短差异复核。"""
expected_key = _compact_text(expected_text)
texts = [str(line.get("text") or "").strip() for line in lines if isinstance(line, dict)]
best_text = ""
best_score = 0.0
for window_size in (1, 2, 3):
for start in range(0, max(0, len(texts) - window_size + 1)):
candidate = "".join(texts[start : start + window_size])
score = SequenceMatcher(None, expected_key, _compact_text(candidate)).ratio()
if score > best_score:
best_text, best_score = candidate, score
return best_text[:500] if best_score >= 0.65 else ""
def _line_bounds(line: dict[str, Any]) -> tuple[float, float, float, float] | None:
"""读取 OCR 行像素框;旧版行记录没有 pixel_polygon 时回退到归一化框。"""
raw_polygon = line.get("pixel_polygon") or line.get("polygon")
@@ -479,7 +528,7 @@ def suppress_mixed_extraction_ocr_noise(
returned_ocr_layout: dict[str, Any] | None,
) -> dict[str, Any]:
"""
移除混合提取模式中经双边同源 OCR 证明一致的地点字段和设备清单噪声差异。
移除混合提取模式中经双边同源 OCR 证明一致的地点字段、高相似非关键文本和设备清单噪声差异。
核心逻辑:[STEP 1] 确认一侧为文本 PDF、一侧为扫描 PDF;[STEP 2] 地点字段按稳定标签
定位命中页;[STEP 3] 设备清单按标准表头定位并用坐标重建列;[STEP 4] 双边视觉业务值
@@ -544,9 +593,9 @@ def suppress_mixed_extraction_ocr_noise(
)
return result
# [STEP 2] 先完成地点项页面定位,并识别是否存在设备清单列错位候选项。
# [STEP 2] 定位地点项与高相似非关键文本,并识别设备清单列错位候选项。
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
pending_locations: list[dict[str, Any]] = []
pending_text_candidates: list[dict[str, Any]] = []
diagnostic_items: list[dict[str, Any]] = []
candidate_item_ids: set[int] = set()
original_pages: set[int] = set()
@@ -555,7 +604,8 @@ def suppress_mixed_extraction_ocr_noise(
if not isinstance(item, dict):
continue
field_label = _eligible_location_field(item)
if not field_label:
validation_type = "location_field" if field_label else "high_similarity_text"
if not field_label and not _eligible_high_similarity_field(item):
continue
candidate_item_ids.add(id(item))
original_page = _locate_page(
@@ -573,8 +623,8 @@ def suppress_mixed_extraction_ocr_noise(
diagnostic = {
"clause_no": item.get("clause_no"),
"title": str(item.get("title") or "")[:200],
"validation_type": "location_field",
"field_label": field_label,
"validation_type": validation_type,
"field_label": field_label or "高相似非关键文本",
"original_extraction_mode": str((original_extraction_meta or {}).get("mode") or ""),
"returned_extraction_mode": str((returned_extraction_meta or {}).get("mode") or ""),
"original_page_no": original_page,
@@ -587,9 +637,10 @@ def suppress_mixed_extraction_ocr_noise(
diagnostic.update({"decision": "kept", "reason": "page_not_located"})
_log_diagnostic(review_no, diagnostic)
continue
pending_locations.append({
pending_text_candidates.append({
"item": item,
"field_label": field_label,
"validation_type": validation_type,
"original_page": original_page,
"returned_page": returned_page,
"diagnostic": diagnostic,
@@ -633,16 +684,22 @@ def suppress_mixed_extraction_ocr_noise(
returned_page_ocr = _ocr_pdf_pages(returned_pdf_bytes, returned_pages) if returned_pages else {}
ignored_item_ids: set[int] = set()
# [STEP 3] 地点字段只有双方命中行完全一致时,才把原差异判为 OCR 噪声。
for candidate in pending_locations:
original_visual = _matching_field_line(
original_page_ocr.get(candidate["original_page"], []),
candidate["field_label"],
)
returned_visual = _matching_field_line(
returned_page_ocr.get(candidate["returned_page"], []),
candidate["field_label"],
)
# [STEP 3] 字段行或高相似文本只有双方视觉 OCR 完全一致时,才判为 OCR 噪声。
for candidate in pending_text_candidates:
if candidate["validation_type"] == "location_field":
original_visual = _matching_field_line(
original_page_ocr.get(candidate["original_page"], []), candidate["field_label"]
)
returned_visual = _matching_field_line(
returned_page_ocr.get(candidate["returned_page"], []), candidate["field_label"]
)
else:
original_visual = _matching_similar_line(
original_page_ocr.get(candidate["original_page"], []), candidate["item"].get("old_text") or ""
)
returned_visual = _matching_similar_line(
returned_page_ocr.get(candidate["returned_page"], []), candidate["item"].get("new_text") or ""
)
diagnostic = candidate["diagnostic"]
diagnostic["original_visual_ocr"] = original_visual
diagnostic["returned_visual_ocr"] = returned_visual
@@ -552,6 +552,20 @@ def test_compare_keeps_short_commercial_values_and_contract_terms():
assert result["clauses_json"][0]["change_type"] == "insert", added_text
def test_compare_labels_added_equipment_schedule_as_returned_contract_schedule():
"""新增设备清单应使用事实标题,便于结果卡直接说明回传合同新增了什么类型的内容。"""
result = analyze.analyze_compare(
"第一条 合同正文",
"第一条 合同正文\n设备清单\n设备名称:自动封箱机\n型号:FX-01\n数量:1台",
rules=[],
)
clause = result["clauses_json"][0]
assert clause["change_type"] == "insert" # 关键断言:仅回传合同含该清单,属于新增而非修改。
assert clause["title"] == "回传合同新增清单"
assert "设备名称:自动封箱机" in clause["new_text"]
def test_compare_ignores_document_end_marker_fragment():
"""“以下无正文”等签章页结束语抽取不完整时不应计为合同修改。"""
result = analyze.analyze_compare("(以下无正文)", "(以下", rules=[])
@@ -192,6 +192,29 @@ def test_different_visual_ocr_keeps_location_difference(monkeypatch):
assert diagnostic["items"][0]["reason"] == "visual_ocr_differs"
def test_same_visual_ocr_removes_high_similarity_noncritical_noise(monkeypatch):
"""无标签的少量字符误识别在视觉 OCR 一致时应移除,覆盖截图中的通用文本差异。"""
item = {
"clause_no": "1",
"title": "合同内容变更",
"change_type": "modify",
"risk_level": "ok",
"old_text": "专用控制平台f5工控专用电脑",
"new_text": "专用控制平台15工控专用电脑",
}
result = _run(
monkeypatch,
_compare_result(item),
original_ocr="专用控制平台15工控专用电脑",
returned_ocr="专用控制平台15工控专用电脑",
)
assert result["clauses_json"] == [] # 关键断言:视觉文本一致的非关键 OCR 噪声不显示为改动。
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]
assert diagnostic["ignored"] == 1
assert diagnostic["items"][0]["validation_type"] == "high_similarity_text"
def test_numeric_field_is_never_auto_ignored(monkeypatch):
"""金额等关键数值字段即使双边 OCR 相同,也不得进入地点字段白名单。"""
item = {