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

(cherry picked from commit bdb2c3113efe87604244a24258cd973955dce544)
This commit is contained in:
sophie committed 2026-08-05 10:20:31 +08:00
1 parent 6b96d5a14f
commit 9bcbf9d211
14 files changed
+2717 -87

No files matched your search

@@ -21,6 +21,7 @@ from typing import Any
from flask import current_app
from minio import Minio
from minio.error import S3Error
_LOGGER = logging.getLogger(__name__)
@@ -188,6 +189,17 @@ def restore_review_artifact(review_no: str, relative_path: str) -> Path | None:
finally:
response.close()
response.release_conn()
except S3Error as exc:
if exc.code == "NoSuchKey":
# [STEP 1] 审核执行中可选 OCR 坐标不存在时,归档尚未提交属于预期状态,不刷告警。
_LOGGER.debug(
"[contract-review] artifact manifest not ready review_no=%s path=%s",
review_no,
relative,
)
return None
_LOGGER.warning("[contract-review] artifact restore failed review_no=%s path=%s err=%s", review_no, relative, exc)
return None
except Exception as exc:
_LOGGER.warning("[contract-review] artifact restore failed review_no=%s path=%s err=%s", review_no, relative, exc)
return None
@@ -268,32 +268,108 @@ 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:
def _shared_clause_anchor(old_text: str, new_text: str) -> str:
"""
提取差异两侧共同的稳定条款前缀,供双边 OCR 从同一业务位置开始重建。
核心逻辑:从去标点文本的最长公共前缀中截取最多 48 个字符;若差异发生得过早,
则回退到双方开头的高相似短锚点。锚点仅用于定位,不参与最终“视觉文本完全一致”判定。
Args:
old_text: 原合同抽取条款。
new_text: 回传合同抽取条款,可能包含 OCR 乱码或截断。
Returns:
至少 8 个字符的共同条款锚点;无法可靠提取时返回空字符串。
"""
old_key = _compact_text(old_text)
new_key = _compact_text(new_text)
common_length = 0
for old_char, new_char in zip(old_key, new_key):
if old_char != new_char:
break
common_length += 1
if common_length >= 8:
return old_key[: min(common_length, 48)]
# [STEP 1] 差异若紧邻条款开头,仍允许使用短窗口定位,但必须保证双方前缀高度相似。
max_probe = min(32, len(old_key), len(new_key))
for probe_length in range(max_probe, 7, -1):
if SequenceMatcher(None, old_key[:probe_length], new_key[:probe_length]).ratio() >= 0.9:
return old_key[:probe_length]
return ""
def _matching_similar_line(
lines: list[dict[str, Any]],
expected_text: str,
*,
shared_anchor: str = "",
target_length: int | None = None,
) -> str:
"""
从 OCR 行及相邻行窗口中选出最接近原始差异文本的视觉条款。
核心逻辑:扫描合同中的一个完整条款通常跨越多行,因此窗口会随预期文本长度扩大到八行;
只有与初始差异文本达到最低相似度的窗口才返回,避免误取同页页眉或相邻条款。
核心逻辑:优先用差异两侧共同锚点定位同一条款起始行,再向后拼接至双方统一目标长度;
无共同锚点时才回退相似窗口。候选排序同时考虑相似度和长度覆盖,避免短前缀因乱码侧
expected_text 较短而胜过完整条款。
Args:
lines: 同一 PDF 页面按阅读顺序排列的 OCR 行。
expected_text: 初始 Diff 中该侧的条款文本。
shared_anchor: 双方抽取文本共同前缀;存在时要求候选窗口覆盖该锚点。
target_length: 双方统一的去标点目标长度,避免回传侧乱码截断导致窗口过短。
Returns:
最接近的 OCR 行窗口;无可靠候选时返回空字符串。
"""
expected_key = _compact_text(expected_text)
texts = [str(line.get("text") or "").strip() for line in lines if isinstance(line, dict)]
if not expected_key or not texts:
return ""
desired_length = max(int(target_length or 0), len(expected_key))
anchor_key = _compact_text(shared_anchor)
max_window = min(8, max(3, desired_length // 22 + 2))
# [STEP 1] 从双方共同锚点命中的行开始重建,达到目标长度后停止,避免吞入下一条款。
if len(anchor_key) >= 8:
anchored_candidates: list[tuple[float, float, int, str]] = []
for start in range(len(texts)):
candidate = ""
for end in range(start, min(len(texts), start + max_window)):
candidate += texts[end]
candidate_key = _compact_text(candidate)
anchor_score = SequenceMatcher(
None,
anchor_key,
candidate_key[: max(len(anchor_key), min(len(candidate_key), len(anchor_key) + 8))],
).ratio()
if anchor_key not in candidate_key and anchor_score < 0.82:
continue
coverage = min(len(candidate_key), desired_length) / max(1, desired_length)
similarity = SequenceMatcher(None, expected_key, candidate_key).ratio()
anchored_candidates.append((coverage, similarity, -abs(len(candidate_key) - desired_length), candidate))
if len(candidate_key) >= desired_length:
break
if anchored_candidates:
coverage, similarity, _length_delta, candidate = max(anchored_candidates)
if coverage >= 0.72 and similarity >= 0.5:
return candidate[:500]
# [STEP 2] 无可靠共同锚点时回退全页窗口;长度覆盖优先于微小的相似度优势。
best_text = ""
best_score = 0.0
max_window = min(8, max(3, len(expected_key) // 22 + 2))
best_rank = (0.0, 0.0, -10**9)
for window_size in range(1, max_window + 1):
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.55 else ""
candidate_key = _compact_text(candidate)
score = SequenceMatcher(None, expected_key, candidate_key).ratio()
coverage = min(len(candidate_key), desired_length) / max(1, desired_length)
rank = (score, coverage, -abs(len(candidate_key) - desired_length))
if score >= 0.55 and coverage >= 0.55 and rank > best_rank:
best_text, best_rank = candidate, rank
return best_text[:500]
def _line_bounds(line: dict[str, Any]) -> tuple[float, float, float, float] | None:
@@ -756,11 +832,25 @@ def suppress_mixed_extraction_ocr_noise(
returned_page_ocr.get(candidate["returned_page"], []), candidate["field_label"]
)
else:
shared_anchor = _shared_clause_anchor(
str(candidate["item"].get("old_text") or ""),
str(candidate["item"].get("new_text") or ""),
)
target_length = max(
len(_compact_text(candidate["item"].get("old_text"))),
len(_compact_text(candidate["item"].get("new_text"))),
)
original_visual = _matching_similar_line(
original_page_ocr.get(candidate["original_page"], []), candidate["item"].get("old_text") or ""
original_page_ocr.get(candidate["original_page"], []),
candidate["item"].get("old_text") or "",
shared_anchor=shared_anchor,
target_length=target_length,
)
returned_visual = _matching_similar_line(
returned_page_ocr.get(candidate["returned_page"], []), candidate["item"].get("new_text") or ""
returned_page_ocr.get(candidate["returned_page"], []),
candidate["item"].get("new_text") or "",
shared_anchor=shared_anchor,
target_length=target_length,
)
diagnostic = candidate["diagnostic"]
diagnostic["original_visual_ocr"] = original_visual
@@ -53,6 +53,41 @@ class _MemoryMinio:
return _MemoryResponse(self.objects[(bucket, key)])
class _MissingManifestMinio:
"""模拟审核尚未归档时读取 manifest 返回 NoSuchKey。"""
def get_object(self, _bucket: str, _key: str):
"""始终抛出可被归档恢复逻辑识别的缺失对象异常。"""
raise _MissingKeyError("manifest not ready")
class _MissingKeyError(Exception):
"""提供与 MinIO S3Error 相同的 code 属性,避免单元测试依赖真实服务。"""
code = "NoSuchKey"
class _MissingTarget:
"""模拟审查目录内尚不存在的目标文件。"""
def __init__(self, root):
self.parent = root
self.parents = (root,)
def resolve(self):
return self
def is_file(self) -> bool:
return False
class _MissingRoot:
"""提供 Path 除法语义,避免该日志专项测试依赖 pytest 临时目录。"""
def __truediv__(self, _relative):
return _MissingTarget(self)
def _archive_app() -> Flask:
"""提供合同归档开关和独立存储目录。"""
app = Flask(__name__)
@@ -98,3 +133,25 @@ def test_archive_uploads_all_files_then_manifest_and_restores_missing_file(monke
assert meta["status"] == "archived"
assert storage.objects[("procurement-contract", f"reviews/{review_no}/cleaned/contract/document.md")] == document_data
def test_restore_missing_manifest_is_expected_and_does_not_warn(monkeypatch, caplog):
"""
审核过程中可选 OCR 坐标缺失且 manifest 尚未提交时,应返回 None 而不记录 WARNING。
关键断言:NoSuchKey 是任务完成归档前的正常状态;网络错误和其他 S3 错误仍由生产代码告警。
"""
review_no = "CR-TEST-PENDING"
root = _MissingRoot()
monkeypatch.setattr(artifact_archive, "_archive_client", lambda: _MissingManifestMinio())
monkeypatch.setattr(artifact_archive, "_review_root", lambda _review_no: root)
monkeypatch.setattr(artifact_archive, "S3Error", _MissingKeyError)
with _archive_app().app_context(), caplog.at_level("WARNING"):
restored = artifact_archive.restore_review_artifact(
review_no,
"cleaned/template/ocr_layout.json",
)
assert restored is None
assert not [record for record in caplog.records if record.levelname == "WARNING"]
@@ -42,8 +42,19 @@ def _location_modify() -> dict:
}
def _run(monkeypatch, result: dict, *, original_ocr: str, returned_ocr: str) -> dict:
"""固定为文字原合同与扫描回传合同,并注入双方命中页 OCR 行。"""
def _run(monkeypatch, result: dict, *, original_ocr: str | list[str], returned_ocr: str | list[str]) -> dict:
"""
固定为文字原合同与扫描回传合同,并注入双方命中页 OCR 行。
Args:
monkeypatch: pytest 补丁工具。
result: 待复核的最小 compare 结果。
original_ocr: 原合同单行文本或真实分行 OCR 文本。
returned_ocr: 回传合同单行文本或真实分行 OCR 文本。
Returns:
执行双边同源 OCR 复核后的结果。
"""
profiles = iter([
{"page_count": 3, "native_text_pages": 3},
{"page_count": 3, "native_text_pages": 0},
@@ -51,9 +62,11 @@ def _run(monkeypatch, result: dict, *, original_ocr: str, returned_ocr: str) ->
monkeypatch.setattr(visual_ocr_validation, "_pdf_text_profile", lambda _data: next(profiles))
monkeypatch.setattr(visual_ocr_validation, "_locate_page", lambda **_kwargs: 2)
original_lines = original_ocr if isinstance(original_ocr, list) else [original_ocr]
returned_lines = returned_ocr if isinstance(returned_ocr, list) else [returned_ocr]
page_results = iter([
{2: [{"text": original_ocr}]},
{2: [{"text": returned_ocr}]},
{2: [{"text": text} for text in original_lines]},
{2: [{"text": text} for text in returned_lines]},
])
monkeypatch.setattr(
visual_ocr_validation,
@@ -235,8 +248,8 @@ def test_same_visual_ocr_removes_multiline_warranty_clause_noise(monkeypatch):
result = _run(
monkeypatch,
_compare_result(item),
original_ocr="".join(visual_text),
returned_ocr="".join(visual_text),
original_ocr=visual_text,
returned_ocr=visual_text,
)
result = analyze.rebuild_result(result)
@@ -246,6 +259,78 @@ def test_same_visual_ocr_removes_multiline_warranty_clause_noise(monkeypatch):
assert quality["visual_ocr_rechecks"]["items"][0]["reason"] == "same_visual_ocr"
def test_shared_anchor_rebuilds_full_warranty_clause_when_returned_diff_is_truncated(monkeypatch):
"""
回传抽取乱码只保留条款前缀时,应按双方共同锚点继续拼接后续 OCR 行并移除误报。
关键断言:模拟测试环境 CR-20260804-5DF6 的真实分行结果,回传 expected_text 在“立即派”后截断,
但页面 OCR 后续行仍包含完整售后方式;复核必须重建完整条款,而不是选择短前缀窗口。
"""
item = {
"clause_no": "5",
"title": "质保与售后变更",
"change_type": "modify",
"change_class": "obligation",
"risk_level": "medium",
"old_text": "3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,至迟24小时内,立即派员进行电话、邮件、微信等在线支持或赴现场实地勘查处理,维修价格需符合市场行情。",
"new_text": "3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,至迟24小时内,立即派行邮件缴信士山",
}
visual_lines = [
"3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,",
"至迟24小时内,立即派员进行电话、邮件、微信等在线支持",
"或赴现场实地勘查处理,维修价格需符合市场行情。",
]
result = _run(
monkeypatch,
_compare_result(item),
original_ocr=visual_lines,
returned_ocr=visual_lines,
)
assert result["clauses_json"] == []
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]["items"][0]
assert diagnostic["reason"] == "same_visual_ocr"
assert "电话、邮件、微信" in diagnostic["returned_visual_ocr"]
def test_shared_anchor_keeps_real_multiline_warranty_content_change(monkeypatch):
"""
共同锚点只能用于完整重建;若回传页面确实删除电话支持,视觉文本不一致时必须保留差异。
关键断言:即使数字、期限和条款前缀完全一致,也不能把真实的售后服务方式删除当作 OCR 噪声。
"""
item = {
"clause_no": "5",
"title": "质保与售后变更",
"change_type": "modify",
"change_class": "obligation",
"risk_level": "medium",
"old_text": "3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,至迟24小时内,立即派员进行电话、邮件、微信等在线支持或赴现场实地勘查处理。",
"new_text": "3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,至迟24小时内,立即派员进行邮件、微信等在线支持或赴现场实地勘查处理。",
}
original_lines = [
"3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,",
"至迟24小时内,立即派员进行电话、邮件、微信等在线支持",
"或赴现场实地勘查处理。",
]
returned_lines = [
"3.保固期外,如设备出现故障,乙方也需在接到甲方通知后,",
"至迟24小时内,立即派员进行邮件、微信等在线支持",
"或赴现场实地勘查处理。",
]
result = _run(
monkeypatch,
_compare_result(item),
original_ocr=original_lines,
returned_ocr=returned_lines,
)
assert result["clauses_json"] == [item]
diagnostic = result["summary_json"]["comparison_quality"]["visual_ocr_rechecks"]["items"][0]
assert diagnostic["decision"] == "kept"
assert diagnostic["reason"] == "visual_ocr_differs"
def test_warranty_deadline_change_is_not_eligible_for_auto_ocr_suppression():
"""质保期限等关键数字变化不得因高相似文本而进入自动忽略。"""
item = {