2233 lines
99 KiB
Python
2233 lines
99 KiB
Python
"""
|
||
backend/app/services/procurement_contract/analyze.py
|
||
|
||
用途:采购合同改稿比对与卖方合同五问检查(文本抽取、清洗、Diff、采购五灯)。
|
||
依赖:stdlib difflib/re/zipfile;可选 python-docx / pdfplumber / pypdf。
|
||
逻辑:review_service 清洗后调用 analyze_compare(红线 Diff + 五灯)或 analyze_solo(五问);
|
||
比对模式以实质变更为主,不再向结果卡堆 OCR 待确认项。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import difflib
|
||
import io
|
||
import re
|
||
import unicodedata
|
||
import zipfile
|
||
from typing import Any
|
||
from xml.etree import ElementTree
|
||
|
||
|
||
SENSITIVE_KEYWORDS = ("付款", "支付", "验收", "违约", "赔偿", "管辖", "仲裁", "质保", "保修", "知识产权", "保密")
|
||
HIGH_KEYWORDS = ("付款", "支付", "违约", "赔偿", "管辖", "仲裁")
|
||
CLAUSE_CATEGORY_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||
("payment", ("付款", "支付", "价款", "发票", "结算", "预付款", "出货款", "验收款", "质保款")),
|
||
("delivery", ("交付", "交货", "运输", "风险转移", "所有权转移")),
|
||
("acceptance", ("验收", "检验", "合格", "异议期")),
|
||
("warranty", ("质保", "保修", "保固", "质量保证", "维修", "更换")),
|
||
("liability", ("违约", "赔偿", "迟延", "逾期", "责任上限", "免责", "损失")),
|
||
("confidentiality", ("保密", "商业秘密", "披露")),
|
||
("ip", ("知识产权", "专利", "著作权", "商标", "侵权")),
|
||
("termination", ("解除", "终止", "自动续期", "单方变更")),
|
||
("dispute", ("争议", "管辖", "仲裁", "适用法律")),
|
||
("force_majeure", ("不可抗力", "情势变更")),
|
||
)
|
||
# 只有命中业务类别且同时出现这些履约要素的 Diff 才进入结果卡。合同名称、主体、
|
||
# 编号、设备型号和单纯的数量/价格清单属于交易信息,不应伪装成法律风险。
|
||
_ACTIONABLE_DIFF_TERMS: dict[str, tuple[str, ...]] = {
|
||
"payment": ("付款", "支付", "结算", "发票", "预付款", "尾款", "款项"),
|
||
"delivery": ("交付", "交货", "运输", "风险转移", "所有权转移", "到货"),
|
||
"acceptance": ("验收", "检验", "不合格", "异议", "整改", "退货"),
|
||
"warranty": ("质保", "保修", "保固", "售后", "维修", "更换"),
|
||
"liability": ("违约", "赔偿", "违约金", "迟延", "逾期", "免责", "责任上限", "损失"),
|
||
"confidentiality": ("保密", "商业秘密", "披露"),
|
||
"ip": ("知识产权", "专利", "著作权", "商标", "侵权"),
|
||
"termination": ("解除", "终止", "自动续期", "单方变更"),
|
||
"dispute": ("争议", "管辖", "仲裁", "适用法律"),
|
||
"force_majeure": ("不可抗力", "情势变更"),
|
||
}
|
||
_CATEGORY_ALIASES = {"jurisdiction": "dispute"}
|
||
_CATEGORY_LABELS = {
|
||
"payment": "付款条件",
|
||
"delivery": "交付条件",
|
||
"acceptance": "验收条件",
|
||
"warranty": "质保与售后",
|
||
"liability": "违约与责任",
|
||
"confidentiality": "保密义务",
|
||
"ip": "知识产权",
|
||
"termination": "解除与续期",
|
||
"dispute": "争议解决",
|
||
"force_majeure": "不可抗力",
|
||
}
|
||
_COMMERCIAL_LIST_TERMS = ("设备名称", "品牌", "型号", "数量", "单价", "总价", "规格", "参数", "配置")
|
||
_RISK_RANK = {"ok": 0, "low": 1, "medium": 2, "high": 3}
|
||
_OBLIGATION_CATEGORIES = frozenset(_ACTIONABLE_DIFF_TERMS)
|
||
_METADATA_TERMS = ("合同编号", "合同号", "甲方", "乙方", "买方", "卖方", "供应商", "地址", "联系人", "电话")
|
||
_CHINESE_NUMERAL_VALUES = {
|
||
"零": 0, "〇": 0, "一": 1, "二": 2, "两": 2, "三": 3, "四": 4,
|
||
"五": 5, "六": 6, "七": 7, "八": 8, "九": 9, "十": 10,
|
||
"百": 100, "千": 1000, "万": 10000,
|
||
}
|
||
_CHINESE_NUMERAL_PATTERN = re.compile(r"[零〇一二两三四五六七八九十百千万]+")
|
||
_STRUCTURAL_PREFIX_PATTERN = re.compile(
|
||
r"^\s*(?:第[一二三四五六七八九十百千万\d]+[条章节]|[一二三四五六七八九十百千万\d]+[、..))])\s*",
|
||
)
|
||
# □/■ 等缺字占位、替换符、私用区(常见于错误 ToUnicode 映射)
|
||
_UNREADABLE_GLYPH_PATTERN = re.compile(r"[\u25a0-\u25ff\ufffd\ue000-\uf8ff]")
|
||
_USEFUL_CHAR_PATTERN = re.compile(r"[\u4e00-\u9fffA-Za-z0-9]")
|
||
_BINARY_PLACEHOLDER_PREFIX = "[binary:"
|
||
_OCR_SUSPICIOUS_PATTERN = re.compile(
|
||
r"[\u2460-\u24ff\u0370-\u03ff\u2190-\u22ff]|"
|
||
r"(?<=[0-9])[OoIl|](?=[0-9,.;:%‰])|(?<=[¥¥0-9,])[OoIl|](?=[0-9])"
|
||
)
|
||
_NUMBER_TOKEN_PATTERN = re.compile(r"\d+(?:[,.]\d+)*(?:\s*(?:%|‰|天|日|个月|月|年|小时))?")
|
||
_SHORT_VALUE_UNIT_PATTERN = re.compile(
|
||
r"\d+(?:[,.]\d+)?\s*(?:%|‰|元|万元|天|日|个月|月|年|小时|台|套|件|个|"
|
||
r"(?:k?w|v|a|hz|mpa|mm|cm|m|m[³3]))\b",
|
||
re.I,
|
||
)
|
||
_MODEL_VALUE_PATTERN = re.compile(
|
||
r"\b(?:"
|
||
r"(?=[A-Za-z0-9]{5,}\b)(?=[A-Za-z0-9]*[A-Za-z])(?=[A-Za-z0-9]*\d)[A-Za-z0-9]+|"
|
||
r"(?=[A-Za-z0-9/_-]{5,}\b)(?=[A-Za-z0-9/_-]*[A-Za-z])(?=[A-Za-z0-9/_-]*\d)"
|
||
r"[A-Za-z0-9]+(?:[-_/][A-Za-z0-9]+)+"
|
||
r")\b",
|
||
)
|
||
_CIRCLED_NUMBER_TRANSLATION = str.maketrans({
|
||
"①": "1", "②": "2", "③": "3", "④": "4", "⑤": "5", "⑥": "6", "⑦": "7", "⑧": "8", "⑨": "9",
|
||
"⑩": "10", "⑪": "11", "⑫": "12", "⑬": "13", "⑭": "14", "⑮": "15", "⑯": "16", "⑰": "17",
|
||
"⑱": "18", "⑲": "19", "⑳": "20", "⒈": "1", "⒉": "2", "⒊": "3", "⒋": "4", "⒌": "5",
|
||
"⒍": "6", "⒎": "7", "⒏": "8", "⒐": "9", "⒑": "10", "⒒": "11", "⒓": "12", "⒔": "13",
|
||
"⒕": "14", "⒖": "15", "⒗": "16", "⒘": "17", "⒙": "18", "⒚": "19", "⒛": "20",
|
||
})
|
||
_OCR_PAGE_MARKER_PATTERN = re.compile(r"!\[page-image-\d+\](?:\([^)]*\))?", re.I)
|
||
_INLINE_PAGE_NUMBER_PATTERN = re.compile(
|
||
r"第\s*\d{1,4}\s*页\s*(?:共\s*\d{1,4}\s*页)?|"
|
||
r"第\s*\d{1,4}\s*页\s*共\s*\d{1,4}\s*页|"
|
||
r"\b\d{1,4}\s*/\s*\d{1,4}\b",
|
||
re.I,
|
||
)
|
||
_HTML_TABLE_PATTERN = re.compile(r"<table\b[^>]*>(.*?)</table>", re.IGNORECASE | re.DOTALL)
|
||
_HTML_TABLE_ROW_PATTERN = re.compile(r"<tr\b[^>]*>(.*?)</tr>", re.IGNORECASE | re.DOTALL)
|
||
_HTML_TABLE_CELL_PATTERN = re.compile(r"<t[dh]\b[^>]*>(.*?)</t[dh]>", re.IGNORECASE | re.DOTALL)
|
||
_HTML_TAG_PATTERN = re.compile(r"<[^>]+>")
|
||
_MATERIAL_TERM_GROUPS: tuple[tuple[str, ...], ...] = (
|
||
("应", "必须", "须", "可以", "可", "有权", "无权", "不得"),
|
||
("甲方", "乙方", "买方", "卖方"),
|
||
("前", "后", "内", "外", "起", "止"),
|
||
("不", "未", "免除", "免责"),
|
||
)
|
||
_POLICY_FINDING_CODES = {
|
||
"payment": "POLICY_PAYMENT_CONDITIONS",
|
||
"delivery": "POLICY_DELIVERY_DEADLINE",
|
||
"warranty": "POLICY_WARRANTY_TERM",
|
||
"dispute": "POLICY_JURISDICTION",
|
||
"liability": "POLICY_DELAY_PENALTY",
|
||
}
|
||
# 采购改稿对照「五盏灯」:只关心这五类是否被改动。
|
||
_FOCUS_TOPICS: tuple[tuple[str, str, tuple[str, ...]], ...] = (
|
||
("payment", "付款条件", ("付款", "支付", "结算", "预付款", "尾款", "验收款", "质保款", "发票")),
|
||
("warranty", "保固", ("质保", "保修", "保固", "质量保证", "售后")),
|
||
("dispute", "管辖地", ("管辖", "人民法院", "仲裁", "争议解决")),
|
||
("delivery", "交货期限", ("交货期限", "交付期限", "交货期", "交付期", "到货")),
|
||
("liability", "违约金", ("逾期交付", "延迟交付", "延期交货", "迟延履行", "违约金", "每延迟一日", "每逾期一日")),
|
||
)
|
||
_DOCUMENT_END_MARKERS = ("以下无正文", "以下无文本", "本页以下无正文")
|
||
_DOCUMENT_END_COMPACT_PATTERN = re.compile(r"以\s*下\s*(?:无\s*正\s*文|无\s*文\s*本)")
|
||
_SIGNATURE_BLOCK_TERMS = ("签署日期", "签订日期", "盖章", "法定代表人", "授权代表")
|
||
_OCR_CONFIRMATION_CATEGORIES = frozenset({"payment", "delivery", "acceptance", "warranty", "liability", "dispute"})
|
||
_FOCUS_CATEGORY_DEFAULT_RISK = {
|
||
"payment": "high",
|
||
"liability": "high",
|
||
"dispute": "high",
|
||
"delivery": "medium",
|
||
"warranty": "medium",
|
||
}
|
||
# 供应商:乙方(卖方)/ 卖方 / 供应商 等标签后的名称
|
||
_SUPPLIER_PATTERNS = (
|
||
re.compile(r"乙方\s*[((]\s*卖方\s*[))]\s*[::]\s*([^\n\r]{2,80})"),
|
||
re.compile(r"卖方\s*[((]\s*乙方\s*[))]\s*[::]\s*([^\n\r]{2,80})"),
|
||
re.compile(r"乙方\s*[::]\s*([^\n\r甲方]{2,80})"),
|
||
re.compile(r"卖方\s*[::]\s*([^\n\r甲方买方]{2,80})"),
|
||
re.compile(r"供应商\s*[::]\s*([^\n\r]{2,80})"),
|
||
)
|
||
# 合同编号:业务合同号(非 CR- 审查编号)
|
||
_CONTRACT_NO_PATTERNS = (
|
||
re.compile(r"合同编号\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/..]{3,63})"),
|
||
re.compile(r"合同号\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/..]{3,63})"),
|
||
re.compile(r"Contract\s*No\.?\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/..]{3,63})", re.I),
|
||
)
|
||
|
||
|
||
def _is_readable_extracted_text(text: str) -> bool:
|
||
"""
|
||
判断抽取文本是否可展示为条款对照(拒绝豆腐字/私用区主导的乱码)。
|
||
|
||
核心逻辑:缺字占位占比 ≥10% 直接否决;清洗后有效中英数字占比须 ≥50%。
|
||
|
||
Args:
|
||
text: PDF/文档抽取引擎返回的文本(可含缺字占位)。
|
||
|
||
Returns:
|
||
True 表示可安全写入 old_text/new_text 供前端对照展示。
|
||
"""
|
||
raw = text or ""
|
||
if raw.startswith(_BINARY_PLACEHOLDER_PREFIX):
|
||
return False
|
||
compact_raw = re.sub(r"\s+", "", raw)
|
||
if not compact_raw:
|
||
return False
|
||
if len(_UNREADABLE_GLYPH_PATTERN.findall(compact_raw)) / len(compact_raw) >= 0.1:
|
||
return False
|
||
cleaned = _clean_extracted_text(raw)
|
||
compact = re.sub(r"\s+", "", cleaned)
|
||
if len(compact) < 4:
|
||
return False
|
||
useful = len(_USEFUL_CHAR_PATTERN.findall(compact))
|
||
return useful / len(compact) >= 0.5
|
||
|
||
|
||
def _clean_extracted_text(text: str) -> str:
|
||
"""
|
||
清洗 PDF 缺字占位与私用区字符,保留可读中文合同正文。
|
||
|
||
Args:
|
||
text: 抽取引擎原始文本。
|
||
|
||
Returns:
|
||
占位符已转为空白、空白已归一化的文本。
|
||
"""
|
||
cleaned = _UNREADABLE_GLYPH_PATTERN.sub(" ", text or "")
|
||
cleaned = re.sub(r"[ \t]+", " ", cleaned)
|
||
cleaned = re.sub(r" *\n *", "\n", cleaned)
|
||
return cleaned.strip()
|
||
|
||
|
||
def _html_table_to_text(match: re.Match[str]) -> str:
|
||
"""将 MinerU HTML 表格压缩成稳定的行文本,避免标签属性参与合同 Diff。"""
|
||
rows: list[str] = []
|
||
for raw_row in _HTML_TABLE_ROW_PATTERN.findall(match.group(1)):
|
||
cells = [
|
||
re.sub(r"\s+", " ", _HTML_TAG_PATTERN.sub("", cell)).strip()
|
||
for cell in _HTML_TABLE_CELL_PATTERN.findall(raw_row)
|
||
]
|
||
cells = [cell for cell in cells if cell]
|
||
if cells:
|
||
rows.append(" | ".join(cells))
|
||
return "\n".join(rows)
|
||
|
||
|
||
def _party_identity_key(line: str) -> str:
|
||
"""提取甲乙方主体名称用于识别签章区重复信息,不修改实际合同正文。"""
|
||
value = re.sub(r"^(?:甲方|乙方|买方|卖方)(?:\s*[((][^))]{0,20}[))])?\s*[::]\s*", "", line.strip())
|
||
value = re.sub(r"\s*[((]\s*以下简称[^))]*[))]", "", value)
|
||
return re.sub(r"\s+", "", value).strip("。;;,,")
|
||
|
||
|
||
def _normalize_ocr_numeric_text(text: str) -> tuple[str, bool]:
|
||
"""归一化高置信 OCR 数字字符,并返回是否仍包含不确定数字字形。"""
|
||
original = str(text or "")
|
||
had_circled_number = bool(re.search(r"[①-⑳⒈-⒛]", original))
|
||
raw = original.translate(_CIRCLED_NUMBER_TRANSLATION)
|
||
raw = unicodedata.normalize("NFKC", raw)
|
||
# [STEP 1] 先把中文比例写成 ‰/%,再做通用中文数字转换,避免「千分之五」丢失比例语义。
|
||
raw = re.sub(
|
||
r"千分之([零〇一二两三四五六七八九十百\d]+(?:\.\d+)?)",
|
||
lambda match: f"{_ratio_phrase_to_number(match.group(1))}‰",
|
||
raw,
|
||
)
|
||
raw = re.sub(
|
||
r"百分之([零〇一二两三四五六七八九十百\d]+(?:点[零〇一二两三四五六七八九\d]+)?(?:\.\d+)?)",
|
||
lambda match: f"{_ratio_phrase_to_number(match.group(1))}%",
|
||
raw,
|
||
)
|
||
normalized = re.sub(r"(?<=\d)[Oo](?=[\d,.;:%‰])|(?<=[¥¥\d,])[Oo](?=\d)", "0", raw)
|
||
normalized = re.sub(r"(?<=\d)[Il|](?=[\d,.;:%‰])|(?<=[¥¥\d,])[Il|](?=\d)", "1", normalized)
|
||
normalized = _CHINESE_NUMERAL_PATTERN.sub(_chinese_numeral_to_digits, normalized)
|
||
uncertain = bool(
|
||
had_circled_number
|
||
or
|
||
re.search(r"[⊥⊤⊙αω廴卫哪叽]", normalized)
|
||
or re.search(r"\d[).]?\s*[~~]\s*(?:月|日|%|‰)", normalized)
|
||
)
|
||
return normalized, uncertain
|
||
|
||
|
||
def _ratio_phrase_to_number(value: str) -> str:
|
||
"""将「五」「零点五」「0.5」等比例短语转为阿拉伯数字字符串。"""
|
||
text = str(value or "").strip()
|
||
if not text:
|
||
return "0"
|
||
if re.fullmatch(r"\d+(?:\.\d+)?", text):
|
||
return text
|
||
text = text.replace("点", ".")
|
||
if "." in text:
|
||
left, right = text.split(".", 1)
|
||
left_match = re.match(_CHINESE_NUMERAL_PATTERN, left) if left else None
|
||
left_digits = _chinese_numeral_to_digits(left_match) if left_match else (left or "0")
|
||
right_digits = "".join(
|
||
str(_CHINESE_NUMERAL_VALUES.get(ch, ch)) if ch in _CHINESE_NUMERAL_VALUES else ch
|
||
for ch in right
|
||
)
|
||
return f"{left_digits}.{right_digits}"
|
||
match = re.match(_CHINESE_NUMERAL_PATTERN, text)
|
||
if match:
|
||
return _chinese_numeral_to_digits(match)
|
||
return text
|
||
|
||
|
||
def extraction_quality(text: str) -> dict[str, Any]:
|
||
"""
|
||
评估合同抽取文本是否足以支撑确定性比对,并返回可审计的质量指标。
|
||
|
||
核心逻辑:综合缺字/私用区、OCR 可疑字符和有效中英数字占比计算分数;该分数只用于
|
||
降低不可靠差异的确定性,不会擅自改写合同中的金额、日期或比例。
|
||
|
||
Args:
|
||
text: 清洗前或清洗后的合同抽取文本。
|
||
|
||
Returns:
|
||
包含 score、level、useful_ratio、suspicious_ratio 和 warning 的字典。
|
||
"""
|
||
raw = str(text or "")
|
||
compact = re.sub(r"\s+", "", raw)
|
||
if not compact or raw.startswith(_BINARY_PLACEHOLDER_PREFIX):
|
||
return {
|
||
"score": 0,
|
||
"level": "unreadable",
|
||
"useful_ratio": 0.0,
|
||
"suspicious_ratio": 1.0,
|
||
"warning": "text_unreadable",
|
||
}
|
||
useful_ratio = len(_USEFUL_CHAR_PATTERN.findall(compact)) / len(compact)
|
||
unreadable_ratio = len(_UNREADABLE_GLYPH_PATTERN.findall(compact)) / len(compact)
|
||
suspicious_ratio = len(_OCR_SUSPICIOUS_PATTERN.findall(compact)) / len(compact)
|
||
score = max(0, min(100, round(useful_ratio * 100 - unreadable_ratio * 180 - suspicious_ratio * 350)))
|
||
if score >= 82 and unreadable_ratio < 0.01 and suspicious_ratio < 0.004:
|
||
level = "high"
|
||
warning = None
|
||
elif score >= 58 and unreadable_ratio < 0.08:
|
||
level = "medium"
|
||
warning = "ocr_noise_detected"
|
||
else:
|
||
level = "low"
|
||
warning = "text_quality_low"
|
||
return {
|
||
"score": score,
|
||
"level": level,
|
||
"useful_ratio": round(useful_ratio, 4),
|
||
"suspicious_ratio": round(suspicious_ratio + unreadable_ratio, 4),
|
||
"warning": warning,
|
||
}
|
||
|
||
|
||
def _safe_comparison_text(text: str) -> str:
|
||
"""
|
||
仅在文本可读时返回清洗后的对照片段;否则返回空串,避免前端展示乱码。
|
||
|
||
Args:
|
||
text: Diff 段落拼接后的原文片段。
|
||
|
||
Returns:
|
||
可读时的清洗文本;不可读时为空字符串。
|
||
"""
|
||
if not _is_readable_extracted_text(text):
|
||
return ""
|
||
return _clean_extracted_text(text)[:1000]
|
||
|
||
|
||
def _chinese_numeral_to_digits(match: re.Match[str]) -> str:
|
||
"""Convert a Chinese number expression to digits for semantic-equivalence comparison only."""
|
||
raw = match.group(0)
|
||
if not raw:
|
||
return raw
|
||
if all(char in {"零", "〇", "一", "二", "两", "三", "四", "五", "六", "七", "八", "九"} for char in raw):
|
||
return "".join(str(_CHINESE_NUMERAL_VALUES[char]) for char in raw)
|
||
total = 0
|
||
section = 0
|
||
number = 0
|
||
for char in raw:
|
||
value = _CHINESE_NUMERAL_VALUES[char]
|
||
if value < 10:
|
||
number = value
|
||
elif value == 10000:
|
||
section = (section + number) * value
|
||
total += section
|
||
section = 0
|
||
number = 0
|
||
else:
|
||
section += (number or 1) * value
|
||
number = 0
|
||
return str(total + section + number)
|
||
|
||
|
||
def _semantic_comparison_key(text: str) -> str:
|
||
"""
|
||
Normalize presentation-only differences before classifying a clause change.
|
||
|
||
This is not a list of special cases: Unicode width, whitespace, punctuation and equivalent
|
||
Chinese/Arabic numeric notation are removed from the comparison key while the original text is
|
||
retained for evidence. A change is `format` only when the complete normalized clause matches.
|
||
"""
|
||
normalized = unicodedata.normalize("NFKC", _clean_extracted_text(text)).lower()
|
||
normalized = _CHINESE_NUMERAL_PATTERN.sub(_chinese_numeral_to_digits, normalized)
|
||
return re.sub(r"[\s\W_]+", "", normalized, flags=re.UNICODE)
|
||
|
||
|
||
def _ocr_comparison_key(text: str) -> str:
|
||
"""生成仅供相似度判断的 OCR 容错键,保留原文作为最终证据。"""
|
||
normalized = unicodedata.normalize("NFKC", _clean_extracted_text(text)).lower()
|
||
normalized = re.sub(r"(?<=\d)[o](?=[\d,.;:%‰])|(?<=[¥¥\d,])[o](?=\d)", "0", normalized)
|
||
normalized = re.sub(r"(?<=\d)[il|](?=[\d,.;:%‰])|(?<=[¥¥\d,])[il|](?=\d)", "1", normalized)
|
||
normalized = _CHINESE_NUMERAL_PATTERN.sub(_chinese_numeral_to_digits, normalized)
|
||
return re.sub(r"[\s\W_]+", "", normalized, flags=re.UNICODE)
|
||
|
||
|
||
def _normalized_number_tokens(text: str) -> list[str]:
|
||
"""
|
||
抽取可明确读取的金额、比例和期限数字,供区分真实数值变化与 OCR 噪声。
|
||
|
||
核心逻辑:先把「千分之五 / 百分之零点五」等中文比例归一成 ‰/% 数字,再抽 token,
|
||
否则母本常见中文违约金改写会被误判为无数字变化的 OCR 噪声。
|
||
"""
|
||
normalized, _ = _normalize_ocr_numeric_text(text)
|
||
normalized = re.sub(r"(?<=\d)[Oo](?=[\d,.;:%‰])|(?<=[¥¥\d,])[Oo](?=\d)", "0", normalized)
|
||
normalized = re.sub(r"(?<=\d)[Il|](?=[\d,.;:%‰])|(?<=[¥¥\d,])[Il|](?=\d)", "1", normalized)
|
||
return [re.sub(r"\s+", "", item) for item in _NUMBER_TOKEN_PATTERN.findall(normalized)]
|
||
|
||
|
||
def _material_terms(text: str) -> set[str]:
|
||
"""提取会改变权利义务方向的主体、否定、时点和强制性用语。"""
|
||
return {
|
||
term
|
||
for group in _MATERIAL_TERM_GROUPS
|
||
for term in group
|
||
if term in str(text or "")
|
||
}
|
||
|
||
|
||
def _latin_tokens(text: str) -> set[str]:
|
||
"""提取较长英文词,用于识别 Know-How 被 OCR 成随机拉丁字符的情况。"""
|
||
return {token.lower() for token in re.findall(r"[A-Za-z]{3,}", str(text or ""))}
|
||
|
||
|
||
def _chinese_character_set(text: str) -> set[str]:
|
||
"""提取中文字符集合,用于高噪声 PDF 的词形保留率判断。"""
|
||
return set(re.findall(r"[\u4e00-\u9fff]", str(text or "")))
|
||
|
||
|
||
def _strip_ocr_list_prefix(text: str) -> str:
|
||
"""移除短列表序号;兼容 `4)` 被 OCR 成 `0 `,但不移除 `30日` 等业务数字。"""
|
||
value = str(text or "")
|
||
value = re.sub(r"^\s*\d{1,2}(?:[.))、..]|\s+)(?=[\u4e00-\u9fff])\s*", "", value)
|
||
return re.sub(r"^0(?=(?:甲方|乙方|买方|卖方|供应商))", "", value)
|
||
|
||
|
||
def _diff_reliability(old_text: str, new_text: str) -> tuple[str, float]:
|
||
"""
|
||
判断一组已对齐文本是实质变化、OCR 噪声还是暂时无法确认。
|
||
|
||
明确可读的数字或权利义务用语变化始终视为 substantive;高相似且关键字段一致的差异
|
||
视为 ocr_noise;高相似但一侧含可疑字符、数字又无法对齐时标为 uncertain。
|
||
"""
|
||
if not old_text or not new_text:
|
||
return "substantive", 1.0
|
||
old_body = _strip_ocr_list_prefix(_STRUCTURAL_PREFIX_PATTERN.sub("", old_text or ""))
|
||
new_body = _strip_ocr_list_prefix(_STRUCTURAL_PREFIX_PATTERN.sub("", new_text or ""))
|
||
old_key = _ocr_comparison_key(old_body)
|
||
new_key = _ocr_comparison_key(new_body)
|
||
similarity = difflib.SequenceMatcher(a=old_key, b=new_key, autojunk=False).ratio()
|
||
old_numbers = _normalized_number_tokens(old_body)
|
||
new_numbers = _normalized_number_tokens(new_body)
|
||
material_changed = _material_terms(old_text) != _material_terms(new_text)
|
||
combined = f"{old_text}\n{new_text}"
|
||
suspicious = bool(
|
||
_OCR_SUSPICIOUS_PATTERN.search(combined)
|
||
or re.search(r"[^\d零〇一二两三四五六七八九十百千万\s]%", combined)
|
||
)
|
||
if similarity >= 0.5 and suspicious and old_numbers != new_numbers:
|
||
return "uncertain", similarity
|
||
if similarity >= 0.55 and suspicious and not material_changed:
|
||
return "uncertain", similarity
|
||
if similarity >= 0.82 and _latin_tokens(old_text) != _latin_tokens(new_text):
|
||
return "uncertain", similarity
|
||
if old_numbers and new_numbers and old_numbers != new_numbers:
|
||
return "substantive", similarity
|
||
if material_changed:
|
||
return "substantive", similarity
|
||
if similarity >= 0.985 and old_numbers == new_numbers:
|
||
return "ocr_noise", similarity
|
||
if similarity >= 0.94 and old_numbers == new_numbers:
|
||
return "ocr_noise", similarity
|
||
return "substantive", similarity
|
||
|
||
|
||
def _looks_like_table_alignment_noise(old_text: str, new_text: str) -> bool:
|
||
"""识别 PDF 表格表头与单元格被不同顺序抽取造成的伪差异。"""
|
||
old_hits = sum(1 for term in _COMMERCIAL_LIST_TERMS if term in str(old_text or ""))
|
||
new_hits = sum(1 for term in _COMMERCIAL_LIST_TERMS if term in str(new_text or ""))
|
||
return max(old_hits, new_hits) >= 4 and min(old_hits, new_hits) <= 1
|
||
|
||
|
||
def _is_truncated_equipment_table_header_noise(old_text: str, new_text: str) -> bool:
|
||
"""
|
||
忽略同一设备表表头被 OCR 截取为不同长度时产生的伪差异。
|
||
|
||
核心逻辑:只接受纯表头,且短表头必须是长表头的有序子集;设备名称、型号、数量、
|
||
单价、总价等任何业务字段值都会使该函数返回 False,仍按真实差异输出。
|
||
|
||
Args:
|
||
old_text: 我方原合同中一个待比较的文本片段。
|
||
new_text: 对方回传合同中与之对齐的文本片段。
|
||
|
||
Returns:
|
||
True 表示仅为设备表表头的 OCR 截断,不生成合同变更记录。
|
||
"""
|
||
header_terms = ("序号",) + _COMMERCIAL_LIST_TERMS
|
||
|
||
def header_sequence(text: str) -> list[str]:
|
||
return [term for term in header_terms if term in text]
|
||
|
||
def is_header_only(text: str) -> bool:
|
||
compact = re.sub(r"\s+|[||,,;;::/\\]", "", text)
|
||
for term in header_terms:
|
||
compact = compact.replace(term, "")
|
||
return not compact
|
||
|
||
old_terms = header_sequence(str(old_text or ""))
|
||
new_terms = header_sequence(str(new_text or ""))
|
||
if min(len(old_terms), len(new_terms)) < 3 or max(len(old_terms), len(new_terms)) < 5:
|
||
return False
|
||
if not is_header_only(old_text) or not is_header_only(new_text):
|
||
return False
|
||
shorter, longer = sorted((old_terms, new_terms), key=len)
|
||
iterator = iter(longer)
|
||
return all(any(candidate == term for candidate in iterator) for term in shorter)
|
||
|
||
|
||
def _is_split_total_row_noise(
|
||
old_text: str,
|
||
new_text: str,
|
||
template_text: str,
|
||
contract_text: str,
|
||
) -> bool:
|
||
"""
|
||
忽略同一表格合计行被一侧拆成标签、另一侧保留金额列时的抽取噪声。
|
||
|
||
核心逻辑:短侧必须只有“合计/总计”标签,长侧必须以该标签开头且含金额;所有金额
|
||
又必须同时出现在两份合同全文中。这样仅忽略列拆分差异,不会吞掉实际金额变更。
|
||
|
||
Args:
|
||
old_text: 我方原合同的单个 Diff 片段。
|
||
new_text: 对方回传合同的单个 Diff 片段。
|
||
template_text: 我方原合同完整正文,用于确认金额事实。
|
||
contract_text: 对方回传合同完整正文,用于确认金额事实。
|
||
|
||
Returns:
|
||
True 表示差异只是合计表格行的列拆分,不生成合同变更记录。
|
||
"""
|
||
old_compact = re.sub(r"\s+|[||,,::]", "", old_text or "")
|
||
new_compact = re.sub(r"\s+|[||,,::]", "", new_text or "")
|
||
labels = ("合计", "总计")
|
||
if old_compact in labels:
|
||
label, expanded = old_compact, new_compact
|
||
elif new_compact in labels:
|
||
label, expanded = new_compact, old_compact
|
||
else:
|
||
return False
|
||
if not expanded.startswith(label) or expanded == label:
|
||
return False
|
||
amount_tokens = _normalized_number_tokens(expanded[len(label):])
|
||
if not amount_tokens:
|
||
return False
|
||
template_numbers = _normalized_number_tokens(template_text)
|
||
contract_numbers = _normalized_number_tokens(contract_text)
|
||
|
||
def has_same_amount(token: str, numbers: set[str]) -> bool:
|
||
# `44,000` and `44000` are the same commercial amount after removing separators.
|
||
normalized_token = re.sub(r"[,.]", "", token)
|
||
return any(re.sub(r"[,.]", "", number) == normalized_token for number in numbers)
|
||
|
||
return all(has_same_amount(token, template_numbers) and has_same_amount(token, contract_numbers) for token in amount_tokens)
|
||
|
||
|
||
def _is_nonsemantic_extraction_fragment_change(old_text: str, new_text: str) -> bool:
|
||
"""
|
||
过滤 Markdown/OCR 单边遗留的极短无语义片段。
|
||
|
||
核心逻辑:只接受一侧为空的 1 个汉字、1 至 2 个 ASCII 字母,或仅由 Markdown 标记
|
||
组成的片段;金额、编号和单位仍由其他规则或正常 Diff 保留,避免过滤业务事实。
|
||
|
||
Args:
|
||
old_text: 我方原合同的单个 Diff 片段。
|
||
new_text: 对方回传合同的单个 Diff 片段。
|
||
|
||
Returns:
|
||
True 表示片段无独立合同语义,应作为解析噪声忽略。
|
||
"""
|
||
if bool(old_text) == bool(new_text):
|
||
return False
|
||
compact = re.sub(r"\s+", "", _clean_extracted_text(new_text or old_text))
|
||
if not compact or re.search(r"\d", compact):
|
||
return False
|
||
if re.fullmatch(r"[>#*_`~|]+", compact):
|
||
return True
|
||
if re.fullmatch(r"[\u4e00-\u9fff][>#*_`~|]?", compact):
|
||
return True
|
||
return bool(re.fullmatch(r"[A-Za-z]{1,2}", compact))
|
||
|
||
|
||
def _is_pure_signature_or_end_noise(old_text: str, new_text: str) -> bool:
|
||
"""
|
||
仅当差异几乎全是签章/文末结束语/抬头主体行时才当作噪声。
|
||
|
||
核心逻辑:含「签署日期/盖章」等词时,先剥掉签章句与纯主体行;若剩余正文无数字差且
|
||
无关键义务词,则忽略。同段违约金/管辖等改写不得被吞掉。
|
||
"""
|
||
combined = f"{old_text}\n{new_text}"
|
||
compact = re.sub(r"\s+", "", combined)
|
||
has_end_marker = _contains_any(combined, _DOCUMENT_END_MARKERS) or bool(
|
||
_DOCUMENT_END_COMPACT_PATTERN.search(combined)
|
||
)
|
||
has_signature = _contains_any(compact, _SIGNATURE_BLOCK_TERMS)
|
||
if not has_end_marker and not has_signature:
|
||
return False
|
||
if _normalized_number_tokens(old_text) != _normalized_number_tokens(new_text):
|
||
return False
|
||
stripped_old = _strip_metadata_lines(_strip_signature_sentences(old_text))
|
||
stripped_new = _strip_metadata_lines(_strip_signature_sentences(new_text))
|
||
if not stripped_old and not stripped_new:
|
||
return True
|
||
if _ocr_comparison_key(stripped_old) == _ocr_comparison_key(stripped_new):
|
||
return True
|
||
remaining = f"{stripped_old}\n{stripped_new}"
|
||
return not _contains_any(
|
||
remaining,
|
||
tuple(SENSITIVE_KEYWORDS) + ("违约金", "质保", "保固", "管辖", "仲裁", "验收", "发票"),
|
||
)
|
||
|
||
|
||
def _is_duplicate_party_signature_change(old_text: str, new_text: str, full_text: str) -> bool:
|
||
"""过滤签章区重复主体名的插入或删除,避免把签署版式当成合同改动。"""
|
||
changed = str(new_text or old_text or "").strip()
|
||
if not changed or (old_text and new_text):
|
||
return False
|
||
if not re.match(r"^(?:甲方|乙方|买方|卖方)(?:\s*[((][^))]{0,20}[))])?\s*[::]", changed):
|
||
return False
|
||
party_key = _party_identity_key(changed)
|
||
if len(party_key) < 4:
|
||
return False
|
||
occurrences = re.findall(re.escape(party_key), re.sub(r"\s+", "", full_text or ""))
|
||
return len(occurrences) >= 2
|
||
|
||
|
||
def _is_truncated_duplicate_supplier_fragment_change(
|
||
old_text: str,
|
||
new_text: str,
|
||
template_text: str,
|
||
contract_text: str,
|
||
) -> bool:
|
||
"""
|
||
过滤签章/页眉中被 OCR 截断的重复供应商名称,避免将其误报为新增条款。
|
||
|
||
核心逻辑:片段必须单边出现、无金额型号或条款关键词,并且两份合同解析出的供应商
|
||
名称高度相似;再确认该片段只是该共同供应商名称的短前缀。供应商主体实际变更时,
|
||
两侧供应商名称不相似,因此不会命中本规则。
|
||
|
||
Args:
|
||
old_text: 我方原合同的单个 Diff 片段。
|
||
new_text: 对方回传合同的单个 Diff 片段。
|
||
template_text: 我方原合同完整正文,用于抽取供应商。
|
||
contract_text: 对方回传合同完整正文,用于抽取供应商。
|
||
|
||
Returns:
|
||
True 表示供应商重复片段是 OCR/版式噪声,不生成合同变更记录。
|
||
"""
|
||
if bool(old_text) == bool(new_text):
|
||
return False
|
||
fragment = _normalize_party_value(new_text or old_text)
|
||
if not 5 <= len(fragment) <= 32:
|
||
return False
|
||
if (
|
||
re.search(r"\d", fragment)
|
||
or _contains_any(fragment, tuple(SENSITIVE_KEYWORDS) + tuple(_COMMERCIAL_LIST_TERMS) + _METADATA_TERMS)
|
||
or _SHORT_VALUE_UNIT_PATTERN.search(fragment)
|
||
or _MODEL_VALUE_PATTERN.search(fragment)
|
||
):
|
||
return False
|
||
|
||
template_supplier = extract_party_fields(template_text).get("supplier_name")
|
||
contract_supplier = extract_party_fields(contract_text).get("supplier_name")
|
||
if not template_supplier or not contract_supplier:
|
||
return False
|
||
supplier_similarity = difflib.SequenceMatcher(
|
||
a=_normalize_party_value(template_supplier),
|
||
b=_normalize_party_value(contract_supplier),
|
||
autojunk=False,
|
||
).ratio()
|
||
if supplier_similarity < 0.82:
|
||
return False
|
||
|
||
supplier = _normalize_party_value(contract_supplier)
|
||
if len(fragment) + 2 > len(supplier):
|
||
return False
|
||
# OCR 常把一个汉字识错,但公司名称前缀仍应保持绝大部分字符顺序一致。
|
||
prefix = supplier[:len(fragment)]
|
||
prefix_similarity = difflib.SequenceMatcher(a=fragment, b=prefix, autojunk=False).ratio()
|
||
return prefix_similarity >= 0.75
|
||
|
||
|
||
def _is_end_section_alignment_noise(old_text: str, new_text: str, full_text: str) -> bool:
|
||
"""识别签署日期被误对齐到正文摘要的尾部跨区错配,保留真实质保事实变化。"""
|
||
has_signature = _contains_any(old_text, _SIGNATURE_BLOCK_TERMS) or _contains_any(new_text, _SIGNATURE_BLOCK_TERMS)
|
||
if not has_signature and not (not old_text or not new_text):
|
||
return False
|
||
other = str(new_text or old_text or "").strip()
|
||
if not other or not _contains_any(other, ("质保", "保修", "保固", "售后")):
|
||
return False
|
||
normalized_other = _ocr_comparison_key(other)
|
||
normalized_full = _ocr_comparison_key(full_text)
|
||
# 同一摘要已在正文出现,说明只是 MinerU 将页脚/摘要移动到了文末,不是新加入条款。
|
||
return bool(normalized_other and normalized_full.count(normalized_other) >= 2)
|
||
|
||
|
||
def _is_short_ocr_garbage_change(old_text: str, new_text: str) -> bool:
|
||
"""
|
||
识别正文中由印章、图形或异常字体映射产生的短乱码插入/删除。
|
||
|
||
核心逻辑:仅检查单侧存在且不超过 24 个字符的片段;合同关键词、字段标签、金额期限、
|
||
数量单位和完整型号均保留。剩余内容若只有少量汉字并夹杂多个短拉丁/数字碎片,则视为
|
||
OCR 噪声。该门禁不得用于两侧都有文本的修改,避免吞掉真实条款改写。
|
||
|
||
Args:
|
||
old_text: 我方原合同对齐片段。
|
||
new_text: 供应商回传合同对齐片段。
|
||
|
||
Returns:
|
||
True 表示该单侧短片段可作为 OCR 噪声忽略。
|
||
"""
|
||
if bool(old_text) == bool(new_text):
|
||
return False
|
||
changed = _clean_extracted_text(new_text or old_text)
|
||
compact = re.sub(r"\s+", "", changed)
|
||
if not compact or len(compact) > 24:
|
||
return False
|
||
|
||
protected_terms = (
|
||
tuple(SENSITIVE_KEYWORDS)
|
||
+ tuple(_COMMERCIAL_LIST_TERMS)
|
||
+ tuple(_METADATA_TERMS)
|
||
+ tuple(term for terms in _ACTIONABLE_DIFF_TERMS.values() for term in terms)
|
||
+ ("合同", "设备", "附件", "金额", "期限", "日期", "名称", "编号", "币种", "人民币", "有限公司")
|
||
)
|
||
if _contains_any(changed, protected_terms):
|
||
return False
|
||
if re.search(r"[::]", changed) or _SHORT_VALUE_UNIT_PATTERN.search(changed) or _MODEL_VALUE_PATTERN.search(changed):
|
||
return False
|
||
|
||
chinese_count = len(re.findall(r"[\u4e00-\u9fff]", compact))
|
||
latin_count = len(re.findall(r"[A-Za-z]", compact))
|
||
alnum_fragments = re.findall(r"[A-Za-z0-9]+", changed)
|
||
short_fragment_count = sum(1 for token in alnum_fragments if len(token) <= 3)
|
||
useful_count = len(_USEFUL_CHAR_PATTERN.findall(compact))
|
||
chinese_ratio = chinese_count / max(1, useful_count)
|
||
return (
|
||
chinese_count <= 3
|
||
and latin_count >= 2
|
||
and short_fragment_count >= 2
|
||
and chinese_ratio < 0.5
|
||
)
|
||
|
||
|
||
def _is_standalone_numbering_fragment_change(old_text: str, new_text: str) -> bool:
|
||
"""
|
||
Ignore an inserted or deleted standalone list number that has no contract semantics.
|
||
|
||
MinerU/PDF paragraph segmentation can detach a table row or clause serial number into its own
|
||
Diff unit. A lone number is not a commercial fact without its adjacent field label or value.
|
||
|
||
Args:
|
||
old_text: Original-contract fragment for one Diff operation.
|
||
new_text: Returned-contract fragment for one Diff operation.
|
||
|
||
Returns:
|
||
True only for a single-sided short Arabic or Chinese ordinal, optionally followed by a delimiter.
|
||
"""
|
||
if bool(old_text) == bool(new_text):
|
||
return False
|
||
changed = _clean_extracted_text(new_text or old_text)
|
||
compact = re.sub(r"\s+", "", changed)
|
||
return bool(re.fullmatch(r"(?:\d{1,3}|[一二三四五六七八九十]{1,3})[、..))\]】]?$", compact))
|
||
|
||
|
||
def _strip_signature_sentences(text: str) -> str:
|
||
"""移除签章与文末结束语句,便于判断同段是否还剩实质义务变更。"""
|
||
parts = [part.strip() for part in re.split(r"\n+|(?<=[。!?;;])", text or "") if part.strip()]
|
||
kept = [
|
||
part
|
||
for part in parts
|
||
if not _contains_any(re.sub(r"\s+", "", part), _SIGNATURE_BLOCK_TERMS)
|
||
and not _contains_any(part, _DOCUMENT_END_MARKERS)
|
||
and not _DOCUMENT_END_COMPACT_PATTERN.search(part)
|
||
]
|
||
return "\n".join(kept)
|
||
|
||
|
||
def _strip_metadata_lines(text: str) -> str:
|
||
"""移除单独的合同主体/编号行,避免签章页错位把抬头当义务变更。"""
|
||
metadata_pattern = re.compile(
|
||
r"^(?:合同编号|合同号|甲方|乙方|买方|卖方|供应商|地址|联系人|电话)\s*[::].*$",
|
||
)
|
||
parts = [part.strip() for part in re.split(r"\n+", text or "") if part.strip()]
|
||
kept = [part for part in parts if not metadata_pattern.match(part)]
|
||
return "\n".join(kept)
|
||
|
||
|
||
def _differing_excerpts(old_text: str, new_text: str) -> tuple[str, str]:
|
||
"""
|
||
在同段多主题时取出真正发生变化的句子,避免类别聚焦只保留未改句。
|
||
|
||
Returns:
|
||
(发出稿摘录, 回传稿摘录),每侧最多约 600 字。
|
||
"""
|
||
old_parts = [part.strip() for part in re.split(r"\n+|(?<=[。!?;;])", old_text or "") if part.strip()]
|
||
new_parts = [part.strip() for part in re.split(r"\n+|(?<=[。!?;;])", new_text or "") if part.strip()]
|
||
old_keys = {_ocr_comparison_key(part) for part in old_parts}
|
||
new_keys = {_ocr_comparison_key(part) for part in new_parts}
|
||
old_diff = [part for part in old_parts if _ocr_comparison_key(part) not in new_keys]
|
||
new_diff = [part for part in new_parts if _ocr_comparison_key(part) not in old_keys]
|
||
if not old_diff and not new_diff:
|
||
return _safe_comparison_text(old_text)[:600], _safe_comparison_text(new_text)[:600]
|
||
return "\n".join(old_diff)[:600], "\n".join(new_diff)[:600]
|
||
|
||
|
||
def _resolve_compare_excerpts(old_raw: str, new_raw: str, category: str) -> tuple[str, str] | None:
|
||
"""
|
||
生成比对展示摘录;若聚焦后两侧相等但全文仍有实质数字/义务差,则回退到差异句。
|
||
|
||
Returns:
|
||
(old_excerpt, new_excerpt);若确认仅为格式/噪声则返回 None(调用方应忽略该 Diff)。
|
||
"""
|
||
focused_old = _focused_diff_text(old_raw, category)
|
||
focused_new = _focused_diff_text(new_raw, category)
|
||
if focused_old and focused_new:
|
||
focused_old_body = _strip_ocr_list_prefix(_STRUCTURAL_PREFIX_PATTERN.sub("", focused_old))
|
||
focused_new_body = _strip_ocr_list_prefix(_STRUCTURAL_PREFIX_PATTERN.sub("", focused_new))
|
||
if _ocr_comparison_key(focused_old_body) == _ocr_comparison_key(focused_new_body):
|
||
numbers_changed = _normalized_number_tokens(old_raw) != _normalized_number_tokens(new_raw)
|
||
material_changed = _material_terms(old_raw) != _material_terms(new_raw)
|
||
if numbers_changed or material_changed:
|
||
return _differing_excerpts(old_raw, new_raw)
|
||
if _ocr_comparison_key(old_raw) != _ocr_comparison_key(new_raw):
|
||
return _differing_excerpts(old_raw, new_raw)
|
||
return None
|
||
if not focused_old and not focused_new:
|
||
return _differing_excerpts(old_raw, new_raw)
|
||
return focused_old, focused_new
|
||
|
||
|
||
def _obligation_risk_for_compare(category: str, blob: str, matched_rule: dict[str, Any]) -> str:
|
||
"""比对模式下为义务变更确定风险等级:优先规则,其次关键词,关键五类至少 medium。"""
|
||
if matched_rule.get("risk_level"):
|
||
return str(matched_rule["risk_level"])
|
||
inferred = _infer_diff_risk(blob)
|
||
floor = _FOCUS_CATEGORY_DEFAULT_RISK.get(_normalized_category(category))
|
||
if not floor:
|
||
return inferred
|
||
if _RISK_RANK.get(inferred, 0) >= _RISK_RANK.get(floor, 0):
|
||
return inferred
|
||
return floor
|
||
|
||
|
||
def _build_focus_lights(clauses: list[dict[str, Any]], contract_text: str) -> list[dict[str, Any]]:
|
||
"""
|
||
根据 Diff 结果生成采购五盏灯状态。
|
||
|
||
状态:changed=回传相对发出稿改动了该主题;unchanged=未改且合同中可检出;missing=合同中未检出该主题。
|
||
"""
|
||
lights: list[dict[str, Any]] = []
|
||
for category, label, terms in _FOCUS_TOPICS:
|
||
topic_changes = [
|
||
item
|
||
for item in clauses
|
||
if isinstance(item, dict)
|
||
and _normalized_category(str(item.get("clause_category") or "")) == category
|
||
and str(item.get("change_type") or "") in {"insert", "delete", "modify"}
|
||
]
|
||
if topic_changes:
|
||
risk = "ok"
|
||
for item in topic_changes:
|
||
level = str(item.get("risk_level") or "ok")
|
||
if _RISK_RANK.get(level, 0) > _RISK_RANK.get(risk, 0):
|
||
risk = level
|
||
lights.append(
|
||
{
|
||
"key": category,
|
||
"label": label,
|
||
"status": "changed",
|
||
"risk_level": risk if risk != "ok" else "medium",
|
||
"change_count": len(topic_changes),
|
||
}
|
||
)
|
||
continue
|
||
detected = bool(_sentences_for_terms(contract_text, terms))
|
||
lights.append(
|
||
{
|
||
"key": category,
|
||
"label": label,
|
||
"status": "unchanged" if detected else "missing",
|
||
"risk_level": "ok" if detected else "medium",
|
||
"change_count": 0,
|
||
}
|
||
)
|
||
return lights
|
||
|
||
|
||
def _paragraph_alignment_key(text: str) -> str:
|
||
"""
|
||
Build a structural alignment key without treating a clause's display number as legal content.
|
||
|
||
Suppliers commonly renumber sections after inserting or removing clauses. The number identifies
|
||
layout order, while the remaining heading/body identifies the business clause; stripping the
|
||
prefix prevents `11、违约责任` and `一、违约责任` from shifting every following comparison.
|
||
"""
|
||
return _ocr_comparison_key(_STRUCTURAL_PREFIX_PATTERN.sub("", text or ""))
|
||
|
||
|
||
def _metadata_difference_is_probably_ocr(old_text: str, new_text: str, similarity: float) -> bool:
|
||
"""判断合同抬头差异更像 OCR/简称噪声,避免要求采购逐条确认基础信息。"""
|
||
combined = f"{old_text}\n{new_text}"
|
||
if _OCR_SUSPICIOUS_PATTERN.search(combined) or re.search(r"[①-⑳⒈-⒛⊥⊤⊙αω廴卫哪叽]", combined):
|
||
return True
|
||
if _normalized_number_tokens(old_text) != _normalized_number_tokens(new_text):
|
||
return False
|
||
old_key = _ocr_comparison_key(old_text)
|
||
new_key = _ocr_comparison_key(new_text)
|
||
if old_key == new_key:
|
||
return True
|
||
old_chars = _chinese_character_set(old_text)
|
||
new_chars = _chinese_character_set(new_text)
|
||
overlap = len(old_chars & new_chars) / max(1, min(len(old_chars), len(new_chars)))
|
||
return similarity >= 0.92 or overlap >= 0.9
|
||
|
||
|
||
def _should_surface_ocr_uncertainty(old_text: str, new_text: str, category: str) -> bool:
|
||
"""
|
||
仅把会影响采购决策的 OCR 不确定性提交人工确认。
|
||
|
||
核心逻辑:付款、交期、质保、违约、管辖等条款的数字或权利义务方向不明确时保留;
|
||
普通错别字、标题、主体简称和非关键段落噪声直接计入已忽略噪声。
|
||
"""
|
||
normalized_category = _normalized_category(category)
|
||
old_numbers = _normalized_number_tokens(old_text)
|
||
new_numbers = _normalized_number_tokens(new_text)
|
||
number_uncertain = old_numbers != new_numbers
|
||
material_uncertain = _material_terms(old_text) != _material_terms(new_text)
|
||
if normalized_category in _OCR_CONFIRMATION_CATEGORIES:
|
||
return number_uncertain or material_uncertain
|
||
blob = f"{old_text}\n{new_text}"
|
||
commercial_numeric = _contains_any(blob, _COMMERCIAL_LIST_TERMS) and number_uncertain
|
||
return commercial_numeric
|
||
|
||
|
||
def _ocr_confirmation_title(category: str) -> str:
|
||
"""生成按采购主题聚合的 OCR 待确认标题。"""
|
||
normalized = _normalized_category(category)
|
||
label = _CATEGORY_LABELS.get(normalized)
|
||
return f"{label} OCR 待确认" if label else "关键交易信息 OCR 待确认"
|
||
|
||
|
||
def _normalize_party_value(value: str) -> str:
|
||
"""清洗当事人/编号抽取结果:去空白与尾部标点。"""
|
||
cleaned = re.sub(r"\s+", "", (value or "").strip())
|
||
cleaned = cleaned.strip("。;;,,、||")
|
||
return cleaned[:128]
|
||
|
||
|
||
def extract_party_fields(contract_text: str) -> dict[str, str | None]:
|
||
"""
|
||
从对方合同正文抽取供应商(乙方/卖方)与业务合同编号。
|
||
|
||
核心逻辑:按优先级匹配常见中文合同抬头标签;取首个有效命中。
|
||
|
||
Args:
|
||
contract_text: 已抽取的合同正文。
|
||
|
||
Returns:
|
||
{"supplier_name": str|None, "contract_no": str|None}
|
||
"""
|
||
text = contract_text or ""
|
||
supplier_name: str | None = None
|
||
for pattern in _SUPPLIER_PATTERNS:
|
||
match = pattern.search(text)
|
||
if not match:
|
||
continue
|
||
candidate = _normalize_party_value(match.group(1))
|
||
# 过滤明显不是公司名的短串或标签残留
|
||
if len(candidate) < 2 or candidate in {"卖方", "乙方", "供应商"}:
|
||
continue
|
||
supplier_name = candidate
|
||
break
|
||
|
||
contract_no: str | None = None
|
||
for pattern in _CONTRACT_NO_PATTERNS:
|
||
match = pattern.search(text)
|
||
if not match:
|
||
continue
|
||
candidate = _normalize_party_value(match.group(1))
|
||
if len(candidate) < 4:
|
||
continue
|
||
contract_no = candidate
|
||
break
|
||
|
||
return {"supplier_name": supplier_name, "contract_no": contract_no}
|
||
|
||
|
||
def _split_paragraphs(text: str) -> list[str]:
|
||
"""
|
||
Split extracted contract text into clause-sized comparable units.
|
||
|
||
PDF extractors often return a whole page as one line. The comparison therefore splits on
|
||
headings and Chinese sentence punctuation, preventing one diff row from containing a full page.
|
||
"""
|
||
normalized = re.sub(r"\r\n?", "\n", _clean_extracted_text(text))
|
||
parts = re.split(
|
||
r"\n\s*\n|\n|(?<=[。!?;])|"
|
||
r"(?=第[一二三四五六七八九十百\d]+[条章节])|"
|
||
r"(?=[一二三四五六七八九十百千万]+[、..])",
|
||
normalized,
|
||
)
|
||
return [
|
||
cleaned
|
||
for part in parts
|
||
if part and part.strip()
|
||
for cleaned in [re.sub(r"\s+", " ", part).strip()]
|
||
if re.sub(r"\s+", "", cleaned).lower() not in {"template", "contract"}
|
||
]
|
||
|
||
|
||
def clean_contract_text(raw_text: str) -> str:
|
||
"""
|
||
将知识库清洗产物进一步整理为适合合同审核的正文。
|
||
|
||
核心逻辑:移除 Markdown 图片、代码围栏、独立页码和重复短页眉/页脚,保留条款编号、
|
||
表格文本及正文换行。该函数不改写金额、日期和比例等具有法律意义的内容。
|
||
|
||
Args:
|
||
raw_text: edkb_system 生成的 Markdown,或本地抽取器返回的文本。
|
||
|
||
Returns:
|
||
可用于条款切分、模板比对和 Dify 全文审核的 UTF-8 文本。
|
||
"""
|
||
text = _clean_extracted_text(raw_text or "")
|
||
# [STEP 1] MinerU 使用 HTML 表格表示版面;合同 Diff 只比较单元格值,不能把 rowspan/colspan 当正文。
|
||
text = _HTML_TABLE_PATTERN.sub(_html_table_to_text, text)
|
||
text = _OCR_PAGE_MARKER_PATTERN.sub("\n", text)
|
||
text = re.sub(r"!\[[^\]]*\]\([^)]*\)", "", text)
|
||
text = re.sub(r"^```[^\n]*$|^```$", "", text, flags=re.M)
|
||
lines = [line.strip() for line in text.splitlines()]
|
||
non_empty = [line for line in lines if line]
|
||
|
||
# [STEP 2] 仅把多次重复且较短的行视为页眉/页脚,避免误删只出现一次的合同标题。
|
||
counts: dict[str, int] = {}
|
||
for line in non_empty:
|
||
normalized = re.sub(r"\s+", "", line)
|
||
if 2 <= len(normalized) <= 60:
|
||
counts[normalized] = counts.get(normalized, 0) + 1
|
||
repeated_noise = {
|
||
line
|
||
for line, count in counts.items()
|
||
if count >= 3 and re.search(r"合同|协议|公司|内部|保密|CONFIDENTIAL", line, flags=re.I)
|
||
}
|
||
|
||
cleaned_lines: list[str] = []
|
||
for line in lines:
|
||
# 页码经常与正文或扫描水印粘在同一行,先移除页码片段再做整行判定。
|
||
line = _INLINE_PAGE_NUMBER_PATTERN.sub(" ", line)
|
||
compact = re.sub(r"\s+", "", line)
|
||
if not compact:
|
||
if cleaned_lines and cleaned_lines[-1] != "":
|
||
cleaned_lines.append("")
|
||
continue
|
||
if compact in repeated_noise:
|
||
continue
|
||
if re.fullmatch(
|
||
r"第?\d{1,4}页(?:共\d{1,4}页)?|\d{1,4}/\d{1,4}|[-—]\d{1,4}[-—]",
|
||
compact,
|
||
flags=re.I,
|
||
):
|
||
continue
|
||
if re.fullmatch(r"[-_=·•]{3,}", compact):
|
||
continue
|
||
# edkb exports the source role as a standalone first line for some documents. It is not
|
||
# part of either contract and must not become a template-difference record.
|
||
if compact.lower() in {"template", "contract"}:
|
||
continue
|
||
# MinerU 可能将签章区的主体名独立成一行;相同公司已在抬头出现时,该行不参与条款 Diff。
|
||
if re.match(r"^(?:甲方|乙方|买方|卖方)(?:\s*[((][^))]{0,20}[))])?\s*[::]", line):
|
||
party_key = _party_identity_key(line)
|
||
previous = re.sub(r"\s+", "", "\n".join(cleaned_lines))
|
||
if len(party_key) >= 4 and party_key in previous:
|
||
continue
|
||
cleaned_lines.append(line)
|
||
|
||
cleaned = "\n".join(cleaned_lines)
|
||
cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
|
||
return cleaned.strip()
|
||
|
||
|
||
def _clause_category(text: str, *, title: str = "", parent_category: str = "") -> str:
|
||
"""按标题、父级标题和正文关键词评分分类,避免偶发跨主题词抢占条款类别。"""
|
||
title_text = str(title or "")
|
||
body_text = str(text or "")
|
||
scores: dict[str, int] = {}
|
||
for category, keywords in CLAUSE_CATEGORY_KEYWORDS:
|
||
title_hits = sum(1 for keyword in keywords if keyword in title_text)
|
||
body_hits = sum(1 for keyword in keywords if keyword in body_text)
|
||
scores[category] = title_hits * 6 + body_hits
|
||
if parent_category and parent_category != "other":
|
||
scores[parent_category] = scores.get(parent_category, 0) + 12
|
||
best_category = max(scores, key=scores.get, default="other")
|
||
return best_category if scores.get(best_category, 0) > 0 else "other"
|
||
|
||
|
||
def _compare_change_category(old_text: str, new_text: str) -> str:
|
||
"""
|
||
按实际变化位置判定对比项类别,避免整句中的背景词抢占分类。
|
||
|
||
核心逻辑:先截取字符级变化附近的上下文,再优先识别期限、比例等数值直接修饰的业务
|
||
对象。例如“6个月质保期”应归入 warranty,而不是被同句“质保款/支付”归入 payment。
|
||
无明确局部线索时回退整段关键词评分。
|
||
|
||
Args:
|
||
old_text: 我方原合同片段。
|
||
new_text: 供应商回传合同片段。
|
||
|
||
Returns:
|
||
稳定的条款类别代码。
|
||
"""
|
||
old_value = str(old_text or "")
|
||
new_value = str(new_text or "")
|
||
matcher = difflib.SequenceMatcher(a=old_value, b=new_value, autojunk=False)
|
||
contexts: list[str] = []
|
||
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
|
||
if tag == "equal":
|
||
continue
|
||
contexts.append(old_value[max(0, i1 - 18):min(len(old_value), i2 + 18)])
|
||
contexts.append(new_value[max(0, j1 - 18):min(len(new_value), j2 + 18)])
|
||
changed_context = "\n".join(contexts) or f"{old_value}\n{new_value}"
|
||
compact = re.sub(r"\s+", "", changed_context)
|
||
|
||
targeted_patterns: tuple[tuple[str, str], ...] = (
|
||
("warranty", r"(?:质保|保修|保固).{0,12}\d|\d+(?:个)?(?:月|年).{0,8}(?:质保|保修|保固)"),
|
||
("liability", r"(?:违约金|赔偿|责任上限|免责).{0,12}\d|\d+(?:%|‰|天|日).{0,8}(?:违约金|赔偿)"),
|
||
("delivery", r"(?:交货|交付|到货).{0,12}\d|\d+(?:天|日|月).{0,8}(?:交货|交付|到货)"),
|
||
("payment", r"(?:付款|支付|账期|预付款|出货款|验收款).{0,12}\d|\d+(?:天|日|%|元).{0,8}(?:付款|支付)"),
|
||
("acceptance", r"(?:验收|检验|整改|退货|更换).{0,12}\d|\d+(?:天|日).{0,8}(?:验收|检验|整改)"),
|
||
)
|
||
for category, pattern in targeted_patterns:
|
||
if re.search(pattern, compact):
|
||
return category
|
||
local_category = _clause_category(changed_context)
|
||
return local_category if local_category != "other" else _clause_category(f"{old_value}\n{new_value}")
|
||
|
||
|
||
def structure_contract_clauses(clean_text: str) -> list[dict[str, Any]]:
|
||
"""
|
||
将清洗后的合同正文切成带稳定序号的条款列表供 Dify 全量遍历。
|
||
|
||
核心逻辑:优先识别“第X条/章”和数字层级标题;无正式编号的段落仍按顺序保留,
|
||
避免知识库式检索只召回部分内容。每条保留 clause_id、编号、标题、分类和正文。
|
||
|
||
Args:
|
||
clean_text: clean_contract_text 的输出。
|
||
|
||
Returns:
|
||
按原文顺序排列的条款字典列表。
|
||
"""
|
||
paragraphs = _split_paragraphs(clean_text)
|
||
clauses: list[dict[str, Any]] = []
|
||
heading_pattern = re.compile(
|
||
r"^(第[一二三四五六七八九十百千万\d]+[条章节])(?:[\s ::、..-]*)(.*)$|"
|
||
r"^((?:\d+\.)+\d*|\d+[、..]|[一二三四五六七八九十百千万]+[、..])\s*(.*)$"
|
||
)
|
||
current: dict[str, Any] | None = None
|
||
parent_category = "other"
|
||
|
||
for paragraph in paragraphs:
|
||
match = heading_pattern.match(paragraph)
|
||
if match:
|
||
if current:
|
||
clauses.append(current)
|
||
clause_no = str(match.group(1) or match.group(3) or "").strip()
|
||
title = str(match.group(2) or match.group(4) or "").strip()
|
||
is_top_level = bool(match.group(1)) or bool(re.fullmatch(r"[一二三四五六七八九十百千万]+[、..]", clause_no))
|
||
category = _clause_category(
|
||
paragraph,
|
||
title=title or paragraph,
|
||
parent_category=parent_category if not is_top_level else "",
|
||
)
|
||
if is_top_level:
|
||
parent_category = category
|
||
elif category == "other":
|
||
category = parent_category
|
||
current = {
|
||
"clause_id": f"clause-{len(clauses) + 1:04d}",
|
||
"clause_no": clause_no,
|
||
"title": title[:120] or clause_no,
|
||
"text": paragraph,
|
||
"category": category,
|
||
}
|
||
continue
|
||
if current and len(current["text"]) + len(paragraph) <= 4000:
|
||
current["text"] = f"{current['text']}\n{paragraph}"
|
||
else:
|
||
if current:
|
||
clauses.append(current)
|
||
current = {
|
||
"clause_id": f"clause-{len(clauses) + 1:04d}",
|
||
"clause_no": f"段落{len(clauses) + 1}",
|
||
"title": paragraph[:40],
|
||
"text": paragraph,
|
||
"category": _clause_category(paragraph, title=paragraph[:40], parent_category=parent_category),
|
||
}
|
||
if current:
|
||
clauses.append(current)
|
||
|
||
for clause in clauses:
|
||
if clause.get("category") == "other":
|
||
clause["category"] = _clause_category(
|
||
str(clause.get("text") or ""),
|
||
title=str(clause.get("title") or ""),
|
||
)
|
||
return clauses
|
||
|
||
|
||
def append_solo_rule_findings(
|
||
result: dict[str, Any],
|
||
contract_text: str,
|
||
*,
|
||
rules: list[dict[str, Any]] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
在模板比对结果上叠加整份合同红线缺项检查。
|
||
|
||
核心逻辑:复用 analyze_solo,仅追加风险项;按规则编号去重,并标记 rule_scan 来源,
|
||
解决比对模式只关注发生变化段落、可能漏掉整份合同缺项的问题。
|
||
"""
|
||
solo = analyze_solo(contract_text, rules=rules)
|
||
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
|
||
existing = {
|
||
(str(item.get("clause_no") or ""), str(item.get("title") or ""))
|
||
for item in clauses
|
||
if isinstance(item, dict)
|
||
}
|
||
for raw in solo.get("clauses_json") or []:
|
||
if not isinstance(raw, dict) or raw.get("risk_level") == "ok":
|
||
continue
|
||
key = (str(raw.get("clause_no") or ""), str(raw.get("title") or ""))
|
||
if key in existing:
|
||
continue
|
||
item = dict(raw)
|
||
item["change_type"] = "rule_scan"
|
||
item["source"] = "rule"
|
||
clauses.append(item)
|
||
existing.add(key)
|
||
result["clauses_json"] = clauses
|
||
return rebuild_result(result)
|
||
|
||
|
||
def _contains_any(text: str, keywords: list[str] | tuple[str, ...]) -> bool:
|
||
"""Return whether any keyword appears in text."""
|
||
return any(k and k in text for k in keywords)
|
||
|
||
|
||
def _level_counter(clauses: list[dict[str, Any]]) -> tuple[int, int, int]:
|
||
"""Count confirmed high/medium/low risks; uncertain evidence is tracked separately."""
|
||
confirmed = [c for c in clauses if c.get("validation_status") != "needs_review"]
|
||
high = sum(1 for c in confirmed if c.get("risk_level") == "high")
|
||
medium = sum(1 for c in confirmed if c.get("risk_level") == "medium")
|
||
low = sum(1 for c in confirmed if c.get("risk_level") == "low")
|
||
return high, medium, low
|
||
|
||
|
||
def _triggered(rule: dict[str, Any], text: str) -> bool:
|
||
"""Evaluate a configured rule; built-in compound rules require their full business condition."""
|
||
keywords = [str(k).strip() for k in (rule.get("keywords") or []) if str(k).strip()]
|
||
code = str(rule.get("code") or "").strip().lower()
|
||
if code == "payment_acceptance_required":
|
||
has_payment = _contains_any(text, ("付款", "支付", "结算", "账期"))
|
||
return not (has_payment and "验收" in text and "发票" in text)
|
||
if code == "acceptance_process_required":
|
||
has_acceptance = "验收" in text
|
||
has_failure_remedy = _contains_any(text, ("不合格", "整改", "退货", "更换", "拒收"))
|
||
return not (has_acceptance and has_failure_remedy)
|
||
if code == "liability_required":
|
||
return not _contains_any(text, ("违约责任", "违约金", "承担赔偿", "损害赔偿"))
|
||
if code == "jurisdiction_required":
|
||
return not _contains_any(text, ("管辖", "仲裁", "人民法院", "争议解决"))
|
||
if code == "warranty_required":
|
||
return not _contains_any(text, ("质保", "保修", "保固", "售后"))
|
||
found = _contains_any(text, keywords)
|
||
trigger_type = str(rule.get("trigger_type") or "keyword_missing")
|
||
if trigger_type == "keyword_present":
|
||
return found
|
||
return not found
|
||
|
||
|
||
def analyze_solo(contract_text: str, *, rules: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||
"""
|
||
对单份供应商合同执行配置规则和采购重点策略检查。
|
||
|
||
核心逻辑:配置规则继续作为管理员可维护的红线;内置采购策略补充判断付款前置条件、
|
||
明确交期、质保期限、管辖地和逾期交付千分之五违约金,避免仅凭关键词宣称通过。
|
||
|
||
Args:
|
||
contract_text: 清洗后的合同正文。
|
||
rules: 管理端启用的风险规则列表。
|
||
|
||
Returns:
|
||
包含规则发现、采购策略发现、质量摘要和报告文本的结构化结果。
|
||
"""
|
||
text = contract_text or ""
|
||
clauses: list[dict[str, Any]] = []
|
||
for rule in rules or []:
|
||
if not _triggered(rule, text):
|
||
clauses.append(
|
||
{
|
||
"clause_no": str(rule.get("code") or rule.get("id") or ""),
|
||
"title": rule.get("title"),
|
||
"clause_category": rule.get("clause_category"),
|
||
"change_type": "pass",
|
||
"risk_level": "ok",
|
||
"detail": "已检测到相关条款表述。",
|
||
"risk_hint": "",
|
||
"suggestion": "",
|
||
"negotiation_text": "",
|
||
}
|
||
)
|
||
continue
|
||
clauses.append(
|
||
{
|
||
"clause_no": str(rule.get("code") or rule.get("id") or ""),
|
||
"title": rule.get("title"),
|
||
"clause_category": rule.get("clause_category"),
|
||
"change_type": "missing",
|
||
"risk_level": rule.get("risk_level") or "medium",
|
||
"detail": rule.get("risk_hint") or "未检测到相关条款。",
|
||
"risk_hint": rule.get("risk_hint") or "",
|
||
"suggestion": rule.get("suggestion") or "",
|
||
"negotiation_text": rule.get("negotiation_text") or "",
|
||
}
|
||
)
|
||
|
||
policy_replaced_codes = {
|
||
"payment": {"payment_acceptance_required"},
|
||
"warranty": {"warranty_required"},
|
||
"dispute": {"jurisdiction_required"},
|
||
"liability": {"liability_required"},
|
||
}
|
||
for finding in _procurement_policy_findings(text):
|
||
category = str(finding["clause_category"])
|
||
clauses = [
|
||
item
|
||
for item in clauses
|
||
if not (
|
||
str(item.get("clause_no") or "").lower() in policy_replaced_codes.get(category, set())
|
||
and item.get("risk_level") != "ok"
|
||
)
|
||
]
|
||
clauses.append(finding)
|
||
|
||
high, medium, low = _level_counter(clauses)
|
||
pass_count = sum(1 for c in clauses if c.get("risk_level") == "ok")
|
||
summary = {
|
||
"mode": "solo",
|
||
"headline": f"单份审核完成:高 {high} / 中 {medium} / 低 {low}",
|
||
"pass_count": pass_count,
|
||
"total_findings": len([c for c in clauses if c.get("risk_level") != "ok"]),
|
||
"review_note": "本结果为采购风险提示,不作为法律意见。",
|
||
}
|
||
return _build_result(summary=summary, clauses=clauses, report_title="采购合同单份审核风险提示报告")
|
||
|
||
|
||
def _policy_finding(
|
||
*,
|
||
category: str,
|
||
title: str,
|
||
risk_level: str,
|
||
detail: str,
|
||
suggestion: str,
|
||
evidence: str = "",
|
||
) -> dict[str, Any]:
|
||
"""构建采购重点策略发现项,字段与配置规则发现保持一致。"""
|
||
return {
|
||
"clause_no": _POLICY_FINDING_CODES[category],
|
||
"title": title,
|
||
"clause_category": category,
|
||
"change_type": "policy_scan" if risk_level != "ok" else "pass",
|
||
"risk_level": risk_level,
|
||
"detail": detail,
|
||
"risk_hint": detail if risk_level != "ok" else "",
|
||
"suggestion": suggestion if risk_level != "ok" else "",
|
||
"negotiation_text": suggestion if risk_level != "ok" else "",
|
||
"evidence": evidence[:600],
|
||
"source": "procurement_policy",
|
||
}
|
||
|
||
|
||
def _uncertain_policy_finding(**kwargs: Any) -> dict[str, Any]:
|
||
"""构建受 OCR 影响的采购策略候选项;保留建议但不计入正式风险统计。"""
|
||
finding = _policy_finding(**kwargs)
|
||
finding["validation_status"] = "needs_review"
|
||
finding["source"] = "procurement_policy_ocr"
|
||
return finding
|
||
|
||
|
||
def _sentences_for_terms(text: str, terms: tuple[str, ...]) -> list[str]:
|
||
"""返回包含指定采购主题词的原文句子,用于规则判断和证据展示。"""
|
||
parts = [part.strip() for part in re.split(r"\n+|(?<=[。!?;;])", text or "") if part.strip()]
|
||
return [part for part in parts if _contains_any(part, terms)]
|
||
|
||
|
||
def _procurement_policy_findings(text: str) -> list[dict[str, Any]]:
|
||
"""
|
||
检查采购最关注的五类合同条件,并输出可解释的确定性发现。
|
||
|
||
当前策略 deliberately 保守:只能在原文存在明确表述时判定通过;未找到或数值不足时
|
||
输出风险,不使用模型推断补齐事实。逾期交付违约金基线为每日合同总价 5‰。
|
||
"""
|
||
findings: list[dict[str, Any]] = []
|
||
|
||
payment = _sentences_for_terms(text, ("付款", "支付", "结算", "预付款", "尾款", "验收款", "质保款"))
|
||
payment_blob = "\n".join(payment)
|
||
payment_context_parts = [part.strip() for part in re.split(r"\n\s*\n", text or "") if part.strip()]
|
||
payment_context = "\n".join(
|
||
part for part in payment_context_parts
|
||
if _contains_any(part, ("付款方式", "预付款", "出货款", "验收款", "质保款"))
|
||
) or payment_blob
|
||
has_payment_acceptance = "验收" in payment_context
|
||
has_payment_invoice = "发票" in payment_context
|
||
has_payment_delivery = _contains_any(payment_context, ("交付", "到货", "货到", "安装", "调试"))
|
||
if not payment:
|
||
findings.append(_policy_finding(
|
||
category="payment",
|
||
title="付款条件缺失",
|
||
risk_level="high",
|
||
detail="未识别到明确付款条款,无法确认预付款比例、付款节点和付款前置条件。",
|
||
suggestion="补充付款节点,并约定尾款以交付、验收合格及收到合规发票为前提。",
|
||
))
|
||
elif not (has_payment_acceptance and has_payment_invoice and has_payment_delivery):
|
||
findings.append(_policy_finding(
|
||
category="payment",
|
||
title="付款前置条件不足",
|
||
risk_level="high",
|
||
detail="付款条款未同时明确交付/到货、验收和发票等关键前置条件。",
|
||
suggestion="将主要款项支付绑定到货、安装调试、验收合格及收到合规发票。",
|
||
evidence=payment_blob,
|
||
))
|
||
|
||
delivery = _sentences_for_terms(text, ("交货期限", "交付期限", "交货期", "交付期", "到货"))
|
||
delivery_blob = "\n".join(delivery)
|
||
normalized_delivery, delivery_uncertain = _normalize_ocr_numeric_text(delivery_blob)
|
||
if re.search(r"\d{4}\s*年", normalized_delivery):
|
||
has_delivery_value = bool(re.search(
|
||
r"\d{4}\s*年\s*\d{1,2}\s*[~~]?\s*月\s*\d{1,2}\s*[~~]?\s*日",
|
||
normalized_delivery,
|
||
))
|
||
else:
|
||
has_delivery_value = bool(re.search(r"\d+\s*(?:个)?(?:工作)?日|\d+\s*天", normalized_delivery))
|
||
if not delivery:
|
||
findings.append(_policy_finding(
|
||
category="delivery",
|
||
title="交货期限不明确",
|
||
risk_level="high",
|
||
detail="未识别到明确日期或可计算的交货期限。",
|
||
suggestion="约定具体交货日期,或以订单/预付款到账日起计算明确工作日数。",
|
||
evidence=delivery_blob,
|
||
))
|
||
elif not has_delivery_value:
|
||
builder = _uncertain_policy_finding if delivery_uncertain else _policy_finding
|
||
findings.append(builder(
|
||
category="delivery",
|
||
title="交货期限 OCR 待确认" if delivery_uncertain else "交货期限不明确",
|
||
risk_level="high",
|
||
detail="交货日期包含 OCR 不确定字符,请查看原文确认。" if delivery_uncertain else "未识别到明确日期或可计算的交货期限。",
|
||
suggestion="确认并录入准确交货日期。" if delivery_uncertain else "约定具体交货日期,或以订单/预付款到账日起计算明确工作日数。",
|
||
evidence=delivery_blob,
|
||
))
|
||
|
||
warranty = _sentences_for_terms(text, ("质保", "保修", "保固", "质量保证"))
|
||
warranty_blob = "\n".join(warranty)
|
||
normalized_warranty, warranty_uncertain = _normalize_ocr_numeric_text(warranty_blob)
|
||
whole_machine_terms: list[int] = []
|
||
for months, years in re.findall(
|
||
r"(?:整机|本设备|设备).{0,30}?(?:(\d+)\s*个?月|(\d+)\s*年)",
|
||
normalized_warranty,
|
||
):
|
||
whole_machine_terms.append(int(months) if months else int(years) * 12)
|
||
warranty_scope = normalized_warranty
|
||
warranty_months = [int(value) for value in re.findall(r"(\d+)\s*个?月", warranty_scope)]
|
||
warranty_years = [int(value) * 12 for value in re.findall(r"(\d+)\s*年", warranty_scope)]
|
||
warranty_terms = whole_machine_terms or warranty_months + warranty_years
|
||
if not warranty:
|
||
findings.append(_policy_finding(
|
||
category="warranty",
|
||
title="质保条款缺失",
|
||
risk_level="high",
|
||
detail="未识别到质保或保修约定。",
|
||
suggestion="补充质保期限、验收合格后的起算点、响应时限及免费维修更换责任。",
|
||
))
|
||
elif not warranty_terms:
|
||
builder = _uncertain_policy_finding if warranty_uncertain else _policy_finding
|
||
findings.append(builder(
|
||
category="warranty",
|
||
title="质保期限 OCR 待确认" if warranty_uncertain else "质保期限不明确",
|
||
risk_level="medium",
|
||
detail="质保期限包含 OCR 不确定字符,请查看原文确认。" if warranty_uncertain else "存在质保表述,但未识别到可执行的期限。",
|
||
suggestion="确认并录入准确的整机质保期限。" if warranty_uncertain else "明确质保期不少于双方确认的采购标准,并从最终验收合格日起算。",
|
||
evidence=warranty_blob,
|
||
))
|
||
elif max(warranty_terms) < 12:
|
||
findings.append(_policy_finding(
|
||
category="warranty",
|
||
title="质保期限偏短",
|
||
risk_level="high",
|
||
detail=f"识别到最长质保期为 {max(warranty_terms)} 个月,低于采购基线 12 个月。",
|
||
suggestion="要求质保期至少 12 个月,并从最终验收合格日起算。",
|
||
evidence=warranty_blob,
|
||
))
|
||
|
||
dispute = _sentences_for_terms(text, ("管辖", "人民法院", "仲裁", "争议解决"))
|
||
dispute_blob = "\n".join(dispute)
|
||
buyer_favorable = _contains_any(dispute_blob, ("甲方所在地", "买方所在地", "采购方所在地"))
|
||
seller_favorable = _contains_any(dispute_blob, ("乙方所在地", "卖方所在地", "供应商所在地"))
|
||
if not dispute:
|
||
findings.append(_policy_finding(
|
||
category="dispute",
|
||
title="争议管辖约定缺失",
|
||
risk_level="medium",
|
||
detail="未识别到法院管辖或仲裁约定。",
|
||
suggestion="约定由买方所在地有管辖权的人民法院处理争议。",
|
||
))
|
||
elif seller_favorable or not buyer_favorable:
|
||
findings.append(_policy_finding(
|
||
category="dispute",
|
||
title="争议管辖对采购方不利或不明确",
|
||
risk_level="high" if seller_favorable else "medium",
|
||
detail="争议解决条款未明确由买方所在地法院管辖。",
|
||
suggestion="修改为由买方所在地有管辖权的人民法院管辖。",
|
||
evidence=dispute_blob,
|
||
))
|
||
|
||
liability = _sentences_for_terms(text, ("逾期交付", "延迟交付", "延期交货", "迟延履行", "违约金", "每延迟一日", "每逾期一日"))
|
||
liability_blob = "\n".join(liability)
|
||
rates: list[float] = []
|
||
liability_uncertain = False
|
||
for sentence in liability:
|
||
normalized_sentence, sentence_uncertain = _normalize_ocr_numeric_text(sentence)
|
||
has_daily_basis = bool(re.search(r"每日|每(?:逾期|延迟|迟延)\s*(?:一|1)\s*日", normalized_sentence))
|
||
if not has_daily_basis:
|
||
continue
|
||
liability_uncertain = liability_uncertain or sentence_uncertain
|
||
for value, unit in re.findall(r"(\d+(?:\.\d+)?)\s*(‰|%)", normalized_sentence):
|
||
rates.append(float(value) / (1000 if unit == "‰" else 100))
|
||
for per_mille_value in re.findall(r"千分之(\d+(?:\.\d+)?)", normalized_sentence):
|
||
rates.append(float(per_mille_value) / 1000)
|
||
if not liability:
|
||
findings.append(_policy_finding(
|
||
category="liability",
|
||
title="逾期交付违约责任缺失",
|
||
risk_level="high",
|
||
detail="未识别到卖方逾期交付违约金约定。",
|
||
suggestion="约定卖方每逾期一日按合同总价 5‰ 支付违约金,并保留损失追偿权。",
|
||
))
|
||
elif not rates:
|
||
builder = _uncertain_policy_finding if liability_uncertain else _policy_finding
|
||
findings.append(builder(
|
||
category="liability",
|
||
title="逾期交付违约金 OCR 待确认" if liability_uncertain else "逾期交付违约金比例不明确",
|
||
risk_level="high",
|
||
detail="每日违约金比例包含 OCR 不确定字符,请查看原文确认。" if liability_uncertain else "存在逾期交付或违约金表述,但未识别到明确的每日计算比例。",
|
||
suggestion="确认每日违约金比例是否达到合同总价 5‰。" if liability_uncertain else "明确卖方每逾期一日按合同总价 5‰ 支付违约金。",
|
||
evidence=liability_blob,
|
||
))
|
||
elif max(rates) < 0.005:
|
||
findings.append(_policy_finding(
|
||
category="liability",
|
||
title="逾期交付违约金低于采购基线",
|
||
risk_level="high",
|
||
detail=f"识别到最高违约金比例约为每日 {max(rates) * 1000:g}‰,低于采购基线 5‰。",
|
||
suggestion="恢复为卖方每逾期一日按合同总价 5‰ 支付违约金。",
|
||
evidence=liability_blob,
|
||
))
|
||
|
||
return findings
|
||
|
||
|
||
def analyze_compare(
|
||
template_text: str,
|
||
contract_text: str,
|
||
*,
|
||
rules: list[dict[str, Any]] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
改稿红线比对:标出回传稿相对发出稿的实质文本差异,并生成采购五盏灯。
|
||
|
||
核心逻辑:段落对齐 Diff → 忽略纯格式/纯签章噪声 → 保留实质变更摘录 →
|
||
对义务类变更打风险与五灯状态。OCR 不确定项只计入质量摘要,不堆进结果卡。
|
||
|
||
Args:
|
||
template_text: 我方发出稿正文。
|
||
contract_text: 卖方回传稿正文。
|
||
rules: 启用中的风险规则列表(可选,用于丰富义务变更标题/建议)。
|
||
|
||
Returns:
|
||
含 summary_json(含 focus_lights)/ clauses_json / report_text 的结构化结果。
|
||
"""
|
||
# [STEP 1] 若任一侧是抽取失败占位符,不再做 Diff,避免把占位串当「变更」
|
||
if template_text.startswith(_BINARY_PLACEHOLDER_PREFIX) or contract_text.startswith(_BINARY_PLACEHOLDER_PREFIX):
|
||
summary = {
|
||
"mode": "compare",
|
||
"headline": "PDF 文本编码不兼容,无法可靠完成合同比对;请上传 Word 或可检索文本的 PDF。",
|
||
"total_changes": 0,
|
||
"text_extraction_warning": "pdf_unreadable",
|
||
"focus_lights": _build_focus_lights([], ""),
|
||
"review_note": "本结果为采购风险提示,不作为法律意见。",
|
||
}
|
||
return _build_result(
|
||
summary=summary,
|
||
clauses=[],
|
||
report_title="合同差异对比报告",
|
||
)
|
||
|
||
template_quality = extraction_quality(template_text)
|
||
contract_quality = extraction_quality(contract_text)
|
||
long_noisy_document = (
|
||
min(len(template_text), len(contract_text)) >= 500
|
||
and min(template_quality["score"], contract_quality["score"]) < 90
|
||
)
|
||
left = _split_paragraphs(template_text)
|
||
right = _split_paragraphs(contract_text)
|
||
left_keys = [_paragraph_alignment_key(item) for item in left]
|
||
right_keys = [_paragraph_alignment_key(item) for item in right]
|
||
matcher = difflib.SequenceMatcher(a=left_keys, b=right_keys, autojunk=False)
|
||
clauses: list[dict[str, Any]] = []
|
||
idx = 0
|
||
unreadable_segments = 0
|
||
ignored_ocr_noise = 0
|
||
uncertain_segments = 0
|
||
|
||
opcodes: list[tuple[str, int, int, int, int]] = []
|
||
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
|
||
# 连续多个条款同时修改时,等长块逐条展开,避免多事实被压成一条。
|
||
if tag == "replace" and i2 - i1 == j2 - j1 and i2 - i1 > 1:
|
||
opcodes.extend(
|
||
("replace", i1 + offset, i1 + offset + 1, j1 + offset, j1 + offset + 1)
|
||
for offset in range(i2 - i1)
|
||
)
|
||
else:
|
||
opcodes.append((tag, i1, i2, j1, j2))
|
||
|
||
for tag, i1, i2, j1, j2 in opcodes:
|
||
if tag == "equal":
|
||
continue
|
||
idx += 1
|
||
old_raw = "\n".join(left[i1:i2]).strip()
|
||
new_raw = "\n".join(right[j1:j2]).strip()
|
||
if old_raw and new_raw and _semantic_comparison_key(old_raw) == _semantic_comparison_key(new_raw):
|
||
continue
|
||
|
||
reliability, similarity = _diff_reliability(old_raw, new_raw)
|
||
combined = f"{old_raw}\n{new_raw}"
|
||
category = _compare_change_category(old_raw, new_raw)
|
||
metadata_change = _is_metadata_only_change(old_raw, new_raw)
|
||
|
||
# [STEP 2] 仅纯签章/文末噪声才丢弃;同段含数字或义务变更必须保留。
|
||
if _is_short_ocr_garbage_change(old_raw, new_raw):
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if _is_standalone_numbering_fragment_change(old_raw, new_raw):
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if _is_truncated_equipment_table_header_noise(old_raw, new_raw):
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if _is_split_total_row_noise(old_raw, new_raw, template_text, contract_text):
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if _is_nonsemantic_extraction_fragment_change(old_raw, new_raw):
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if _is_pure_signature_or_end_noise(old_raw, new_raw):
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if _is_duplicate_party_signature_change(old_raw, new_raw, f"{template_text}\n{contract_text}"):
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if _is_truncated_duplicate_supplier_fragment_change(
|
||
old_raw, new_raw, template_text, contract_text,
|
||
):
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if _is_end_section_alignment_noise(old_raw, new_raw, f"{template_text}\n{contract_text}"):
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if _looks_like_table_alignment_noise(old_raw, new_raw):
|
||
reliability = "uncertain"
|
||
if long_noisy_document and reliability == "substantive":
|
||
old_chars = _chinese_character_set(old_raw)
|
||
new_chars = _chinese_character_set(new_raw)
|
||
overlap = len(old_chars & new_chars) / max(1, min(len(old_chars), len(new_chars)))
|
||
length_ratio = min(len(old_raw), len(new_raw)) / max(1, max(len(old_raw), len(new_raw)))
|
||
numbers_changed = _normalized_number_tokens(old_raw) != _normalized_number_tokens(new_raw)
|
||
if (
|
||
overlap >= 0.82
|
||
and length_ratio >= 0.78
|
||
and _material_terms(old_raw) == _material_terms(new_raw)
|
||
and not numbers_changed
|
||
):
|
||
reliability = "uncertain"
|
||
|
||
if reliability == "ocr_noise":
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if reliability == "uncertain":
|
||
# [STEP 3] 不确定项只计数,不进结果卡,避免采购被待确认列表淹没。
|
||
if metadata_change and _metadata_difference_is_probably_ocr(old_raw, new_raw, similarity):
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if metadata_change:
|
||
reliability = "substantive"
|
||
elif _should_surface_ocr_uncertainty(old_raw, new_raw, category):
|
||
uncertain_segments += 1
|
||
continue
|
||
else:
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
|
||
blob = f"{_clean_extracted_text(old_raw)}\n{_clean_extracted_text(new_raw)}"
|
||
old = _safe_comparison_text(old_raw)
|
||
new = _safe_comparison_text(new_raw)
|
||
if (old_raw or new_raw) and not old and not new:
|
||
unreadable_segments += 1
|
||
change_class = _classify_change(old_text=old_raw, new_text=new_raw, category=category)
|
||
if change_class == "metadata" and long_noisy_document:
|
||
if _metadata_difference_is_probably_ocr(old_raw, new_raw, similarity):
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
if change_class == "obligation" and not _is_actionable_diff(blob, category):
|
||
change_class = "commercial"
|
||
|
||
excerpts = _resolve_compare_excerpts(old_raw, new_raw, category)
|
||
if excerpts is None:
|
||
ignored_ocr_noise += 1
|
||
continue
|
||
focused_old, focused_new = excerpts
|
||
|
||
matched_rule = _rule_for_category(category, rules or []) if change_class == "obligation" else {}
|
||
risk = (
|
||
_obligation_risk_for_compare(category, blob, matched_rule)
|
||
if change_class == "obligation"
|
||
else "ok"
|
||
)
|
||
change_type = {"replace": "modify", "delete": "delete", "insert": "insert"}.get(tag, tag)
|
||
title = f"{_CATEGORY_LABELS.get(category, '合同内容')}变更"
|
||
clauses.append(
|
||
{
|
||
"clause_no": str(idx),
|
||
"title": title,
|
||
"clause_category": _normalized_category(category),
|
||
"change_type": change_type,
|
||
"change_class": change_class,
|
||
"risk_level": risk,
|
||
"old_text": focused_old,
|
||
"new_text": focused_new,
|
||
"comparison_readable": bool(focused_old or focused_new),
|
||
"comparison_confidence": round(similarity, 3),
|
||
"detail": _compare_difference_detail(change_type, category, change_class),
|
||
"risk_hint": _default_risk_hint(risk) if risk != "ok" else "",
|
||
"suggestion": "",
|
||
"negotiation_text": "",
|
||
}
|
||
)
|
||
|
||
clauses = _deduplicate_exact_diffs(clauses)
|
||
confirmed_change_count = len(clauses)
|
||
focus_lights = _build_focus_lights(clauses, contract_text)
|
||
changed_lights = sum(1 for item in focus_lights if item.get("status") == "changed")
|
||
high, medium, low = _level_counter(clauses)
|
||
summary = {
|
||
"mode": "compare",
|
||
"headline": (
|
||
f"合同比对完成:实质变更 {confirmed_change_count} 处"
|
||
f"(高 {high} / 中 {medium} / 低 {low}),关键点改动 {changed_lights} 项"
|
||
),
|
||
"total_changes": confirmed_change_count,
|
||
"focus_lights": focus_lights,
|
||
"comparison_quality": {
|
||
"template": template_quality,
|
||
"contract": contract_quality,
|
||
"ignored_ocr_noise": ignored_ocr_noise,
|
||
"needs_confirmation": 0,
|
||
"confirmation_fragments": uncertain_segments,
|
||
"confirmation_items_shown": 0,
|
||
"confirmation_items_truncated": uncertain_segments,
|
||
"manual_review_suggested": bool(
|
||
uncertain_segments >= 3
|
||
or template_quality.get("level") == "low"
|
||
or contract_quality.get("level") == "low"
|
||
),
|
||
},
|
||
"review_note": "本结果为采购风险提示,不作为法律意见。",
|
||
}
|
||
if unreadable_segments:
|
||
summary["text_extraction_warning"] = "pdf_partial_unreadable"
|
||
elif template_quality["level"] == "low" or contract_quality["level"] == "low":
|
||
summary["text_extraction_warning"] = "text_quality_low"
|
||
elif uncertain_segments >= 3:
|
||
summary["text_extraction_warning"] = "manual_review_suggested"
|
||
if not clauses:
|
||
summary["headline"] = "未检测到实质条款差异。"
|
||
if summary["comparison_quality"]["manual_review_suggested"]:
|
||
summary["headline"] += "文本质量偏低,建议打开原文并排人工确认。"
|
||
return _build_result(summary=summary, clauses=clauses, report_title="合同差异对比报告")
|
||
|
||
|
||
def _match_rule_for_diff(blob: str, rules: list[dict[str, Any]]) -> dict[str, Any]:
|
||
"""Find the first enabled rule whose keywords appear in a diff block."""
|
||
for rule in rules:
|
||
keywords = [str(k).strip() for k in (rule.get("keywords") or []) if str(k).strip()]
|
||
if _contains_any(blob, keywords):
|
||
return rule
|
||
return {}
|
||
|
||
|
||
def _infer_diff_risk(blob: str) -> str:
|
||
"""Infer risk level when no configurable rule matches a diff block."""
|
||
if _contains_any(blob, HIGH_KEYWORDS):
|
||
return "high"
|
||
if _contains_any(blob, SENSITIVE_KEYWORDS):
|
||
return "medium"
|
||
return "low"
|
||
|
||
|
||
def _classify_change(*, old_text: str, new_text: str, category: str) -> str:
|
||
"""
|
||
Classify one aligned difference before any legal risk rule is applied.
|
||
|
||
Returns `format`, `metadata`, `commercial` or `obligation`. Only `obligation` reaches the
|
||
legal-risk classifier; this keeps a generic payment keyword from escalating a renumbered clause.
|
||
"""
|
||
if old_text and new_text and _semantic_comparison_key(old_text) == _semantic_comparison_key(new_text):
|
||
return "format"
|
||
blob = f"{old_text}\n{new_text}"
|
||
if _is_metadata_only_change(old_text, new_text):
|
||
return "metadata"
|
||
if _normalized_category(category) in _OBLIGATION_CATEGORIES:
|
||
return "obligation"
|
||
if _contains_any(blob, _COMMERCIAL_LIST_TERMS):
|
||
return "commercial"
|
||
return "commercial"
|
||
|
||
|
||
def _is_metadata_only_change(old_text: str, new_text: str) -> bool:
|
||
"""Identify standalone party/contract-number fields without treating normal clauses as metadata."""
|
||
lines = [line.strip() for line in f"{old_text}\n{new_text}".splitlines() if line.strip()]
|
||
if not lines:
|
||
return False
|
||
metadata_pattern = re.compile(
|
||
r"^(?:合同编号|合同号|甲方|乙方|买方|卖方|供应商|地址|联系人|电话)\s*[::]",
|
||
)
|
||
return all(bool(metadata_pattern.match(line)) for line in lines)
|
||
|
||
|
||
def _change_class_detail(change_class: str) -> str:
|
||
"""Provide a neutral explanation for a non-legal template difference."""
|
||
if change_class == "format":
|
||
return "仅编号、标点、空白或排版表达不同,未识别到权利义务变化。"
|
||
if change_class == "metadata":
|
||
return "合同主体或基础信息发生变化,请业务确认信息是否正确。"
|
||
return "交易条件或清单信息发生变化,请业务确认价格、数量、规格或交期。"
|
||
|
||
|
||
def _normalized_category(category: str) -> str:
|
||
"""Normalize rule categories that use an older label to the comparison category."""
|
||
return _CATEGORY_ALIASES.get(category, category)
|
||
|
||
|
||
def _is_actionable_diff(blob: str, category: str) -> bool:
|
||
"""
|
||
Decide whether a text difference changes a legal or fulfillment condition.
|
||
|
||
AI trigger context: this filter is deliberately deterministic. It removes document metadata and
|
||
equipment schedules before risk classification so a generic keyword cannot turn a model number
|
||
or contract number into a high-risk clause.
|
||
"""
|
||
normalized = _normalized_category(category)
|
||
terms = _ACTIONABLE_DIFF_TERMS.get(normalized, ())
|
||
if not terms or not _contains_any(blob, terms):
|
||
return False
|
||
compact = re.sub(r"\s+", "", blob)
|
||
commercial_hits = sum(1 for term in _COMMERCIAL_LIST_TERMS if term in compact)
|
||
legal_hits = sum(1 for term in terms if term in compact)
|
||
# A pure equipment/price schedule is a commercial change, unless it also changes a named legal
|
||
# condition such as payment, acceptance, liability or delivery.
|
||
if commercial_hits >= 3 and legal_hits == 0:
|
||
return False
|
||
return True
|
||
|
||
|
||
def _focused_diff_text(text: str, category: str) -> str:
|
||
"""Keep only the changed sentences relevant to one business clause for a readable comparison."""
|
||
safe = _safe_comparison_text(text)
|
||
if not safe:
|
||
return ""
|
||
terms = _ACTIONABLE_DIFF_TERMS.get(_normalized_category(category), ())
|
||
parts = [part.strip() for part in re.split(r"\n+|(?<=[。!?;;])", safe) if part.strip()]
|
||
matched = [part for part in parts if _contains_any(part, terms)]
|
||
selected = matched[:2] or parts[:1]
|
||
excerpt = "\n".join(selected).strip()
|
||
return excerpt[:600]
|
||
|
||
|
||
def _rule_for_category(category: str, rules: list[dict[str, Any]]) -> dict[str, Any]:
|
||
"""Resolve one rule by its declared business category instead of any incidental keyword."""
|
||
normalized = _normalized_category(category)
|
||
for rule in rules:
|
||
rule_category = _normalized_category(str(rule.get("clause_category") or ""))
|
||
if rule_category == normalized:
|
||
return rule
|
||
return {}
|
||
|
||
|
||
def _merge_same_category_diffs(clauses: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||
"""Keep one actionable template-difference card per business category, preserving strongest risk."""
|
||
merged: dict[str, dict[str, Any]] = {}
|
||
order: list[str] = []
|
||
for clause in clauses:
|
||
category = str(clause.get("clause_category") or "other")
|
||
key = f"{_normalized_category(category)}:{str(clause.get('change_class') or 'obligation')}"
|
||
existing = merged.get(key)
|
||
if existing is None:
|
||
merged[key] = clause
|
||
order.append(key)
|
||
continue
|
||
if _RISK_RANK.get(str(clause.get("risk_level") or "low"), 1) > _RISK_RANK.get(str(existing.get("risk_level") or "low"), 1):
|
||
merged[key] = clause
|
||
return [merged[key] for key in order]
|
||
|
||
|
||
def _deduplicate_exact_diffs(clauses: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||
"""仅合并证据完全相同的 Diff,保留同一业务类别下不同付款节点或责任变化。"""
|
||
unique: list[dict[str, Any]] = []
|
||
fingerprints: set[str] = set()
|
||
for clause in clauses:
|
||
fingerprint = _semantic_comparison_key(
|
||
f"{clause.get('change_type') or ''}|{clause.get('old_text') or ''}|{clause.get('new_text') or ''}"
|
||
)
|
||
if fingerprint and fingerprint in fingerprints:
|
||
continue
|
||
if fingerprint:
|
||
fingerprints.add(fingerprint)
|
||
unique.append(clause)
|
||
return unique
|
||
|
||
|
||
def _diff_detail(change_type: str, rule: dict[str, Any]) -> str:
|
||
"""Create a concise diff detail for the report card."""
|
||
if rule:
|
||
return str(rule.get("risk_hint") or "相对模板发生敏感条款变更。")
|
||
if change_type == "delete":
|
||
return "相对模板删除了部分条款。"
|
||
if change_type == "insert":
|
||
return "相对模板新增了部分条款。"
|
||
return "相对模板发生文本修改。"
|
||
|
||
|
||
def _compare_difference_detail(change_type: str, category: str, change_class: str) -> str:
|
||
"""
|
||
为双合同对比生成只描述变化事实的说明,不混入单份审核的规则建议。
|
||
|
||
Args:
|
||
change_type: insert/delete/modify。
|
||
category: 实际变化对应的业务类别。
|
||
change_class: metadata/commercial/obligation 等语义分层。
|
||
|
||
Returns:
|
||
可直接写入结果卡和差异报告的中性说明。
|
||
"""
|
||
action = {"insert": "新增", "delete": "删除", "modify": "修改"}.get(change_type, "调整")
|
||
label = _CATEGORY_LABELS.get(_normalized_category(category))
|
||
if label:
|
||
return f"供应商回传合同{action}了{label}相关内容,请以变更对照为准。"
|
||
if change_class == "metadata":
|
||
return f"供应商回传合同{action}了合同基础信息,请以变更对照为准。"
|
||
if change_class == "commercial":
|
||
return f"供应商回传合同{action}了交易条件或清单信息,请以变更对照为准。"
|
||
return f"供应商回传合同{action}了合同内容,请以变更对照为准。"
|
||
|
||
|
||
def _default_risk_hint(level: str) -> str:
|
||
"""Default risk hint for unmatched diff blocks."""
|
||
if level == "high":
|
||
return "该变更涉及付款、违约、赔偿或管辖等敏感条款,建议重点复核。"
|
||
if level == "medium":
|
||
return "该变更涉及采购履约保障相关条款,建议确认是否接受。"
|
||
return "该变更未命中高风险关键词,可作为一般差异复核。"
|
||
|
||
|
||
def _default_suggestion(level: str) -> str:
|
||
"""Default suggestion for unmatched diff blocks."""
|
||
if level == "high":
|
||
return "建议优先要求供应商恢复模板条款;无法恢复时提交负责人或外部律师复核。"
|
||
if level == "medium":
|
||
return "建议与供应商确认修改原因,并保留对采购方有利的履约保障。"
|
||
return "建议采购确认该差异是否符合本次交易事实。"
|
||
|
||
|
||
def rebuild_result(
|
||
result: dict[str, Any],
|
||
*,
|
||
report_title: str | None = None,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
在规则或 Dify 合并结果变化后重新计算风险统计、摘要和下载报告。
|
||
|
||
Args:
|
||
result: 至少包含 summary_json / clauses_json 的审核结果。
|
||
report_title: 可选报告标题;未传时按审核模式推断。
|
||
|
||
Returns:
|
||
原字典的更新版本,页面统计与 report_text 保持一致。
|
||
"""
|
||
clauses = result.get("clauses_json") if isinstance(result.get("clauses_json"), list) else []
|
||
summary = result.get("summary_json") if isinstance(result.get("summary_json"), dict) else {}
|
||
high, medium, low = _level_counter(clauses)
|
||
mode = str(summary.get("mode") or "solo")
|
||
finding_count = len([
|
||
c for c in clauses
|
||
if isinstance(c, dict)
|
||
and c.get("risk_level") != "ok"
|
||
and c.get("validation_status") != "needs_review"
|
||
])
|
||
if mode == "compare":
|
||
changes = len(
|
||
[
|
||
c
|
||
for c in clauses
|
||
if isinstance(c, dict) and c.get("change_type") in {"insert", "delete", "modify"}
|
||
]
|
||
)
|
||
summary["total_changes"] = changes
|
||
summary["total_findings"] = finding_count
|
||
summary["headline"] = f"合同审核完成:高 {high} / 中 {medium} / 低 {low},模板变更 {changes} 处"
|
||
else:
|
||
summary["total_findings"] = finding_count
|
||
summary["headline"] = f"合同审核完成:高 {high} / 中 {medium} / 低 {low}"
|
||
title = report_title or ("合同差异对比报告" if mode == "compare" else "采购合同全面风险审核报告")
|
||
rebuilt = _build_result(summary=summary, clauses=clauses, report_title=title)
|
||
result.update(rebuilt)
|
||
return result
|
||
|
||
|
||
def _build_result(*, summary: dict[str, Any], clauses: list[dict[str, Any]], report_title: str) -> dict[str, Any]:
|
||
"""构建最终结果;对比模式输出差异事实,单份模式输出风险提示。"""
|
||
high, medium, low = _level_counter(clauses)
|
||
mode = str(summary.get("mode") or "solo")
|
||
if mode == "compare":
|
||
return _build_compare_result(summary=summary, clauses=clauses, report_title=report_title)
|
||
report_lines = [
|
||
report_title,
|
||
"",
|
||
str(summary.get("headline") or ""),
|
||
str(summary.get("review_note") or "本结果为采购风险提示,不作为法律意见。"),
|
||
"",
|
||
"风险提示清单:",
|
||
]
|
||
uncertain_lines: list[str] = []
|
||
for c in clauses[:80]:
|
||
if c.get("risk_level") == "ok":
|
||
continue
|
||
if c.get("validation_status") == "needs_review":
|
||
uncertain_lines.append(f"- [待确认] {c.get('title')}: {c.get('detail')}")
|
||
continue
|
||
report_lines.append(f"- [{c.get('risk_level')}] {c.get('title')}: {c.get('detail')}")
|
||
anchor = c.get("evidence_anchor") if isinstance(c.get("evidence_anchor"), dict) else None
|
||
if anchor and anchor.get("page_no"):
|
||
report_lines.append(f" 位置:原合同第 {anchor.get('page_no')} 页")
|
||
matched_text = re.sub(r"\s+", " ", str(anchor.get("matched_text") or "")).strip()
|
||
if matched_text:
|
||
report_lines.append(f" 原文:{matched_text[:300]}")
|
||
if c.get("suggestion"):
|
||
report_lines.append(f" 建议:{c.get('suggestion')}")
|
||
if c.get("negotiation_text"):
|
||
report_lines.append(f" 沟通话术:{c.get('negotiation_text')}")
|
||
if uncertain_lines:
|
||
report_lines.extend(["", "待确认清单:", *uncertain_lines])
|
||
explicit_changes = summary.get("total_changes")
|
||
return {
|
||
"high_risk_count": high,
|
||
"medium_risk_count": medium,
|
||
"low_risk_count": low,
|
||
"total_change_count": int(
|
||
explicit_changes
|
||
if explicit_changes is not None
|
||
else len([c for c in clauses if c.get("risk_level") != "ok"])
|
||
),
|
||
"summary_json": summary,
|
||
"clauses_json": clauses,
|
||
"report_text": "\n".join(line for line in report_lines if line is not None),
|
||
}
|
||
|
||
|
||
def _build_compare_result(
|
||
*,
|
||
summary: dict[str, Any],
|
||
clauses: list[dict[str, Any]],
|
||
report_title: str,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
生成双合同差异报告,逐项列出原文和回传内容,不输出规则建议或沟通话术。
|
||
|
||
Args:
|
||
summary: 对比摘要及区域、附件信息。
|
||
clauses: 已确认的新增、删除、修改项。
|
||
report_title: 下载报告标题。
|
||
|
||
Returns:
|
||
与通用结果契约兼容的统计、条款和纯文本报告。
|
||
"""
|
||
changes = [
|
||
item for item in clauses
|
||
if isinstance(item, dict) and item.get("change_type") in {"insert", "delete", "modify"}
|
||
]
|
||
high, medium, low = _level_counter(clauses)
|
||
report_lines = [
|
||
report_title,
|
||
"",
|
||
f"共识别差异 {len(changes)} 项(修改 {sum(c.get('change_type') == 'modify' for c in changes)} / "
|
||
f"新增 {sum(c.get('change_type') == 'insert' for c in changes)} / "
|
||
f"删除 {sum(c.get('change_type') == 'delete' for c in changes)})。",
|
||
"说明:本报告用于展示我方原合同与供应商回传合同的文本差异。",
|
||
"",
|
||
"差异项清单:",
|
||
]
|
||
type_labels = {"modify": "修改", "insert": "新增", "delete": "删除"}
|
||
for index, clause in enumerate(changes[:80], start=1):
|
||
report_lines.append(
|
||
f"{index}. [{type_labels.get(str(clause.get('change_type') or ''), '调整')}] "
|
||
f"{clause.get('title') or '合同内容变更'}"
|
||
)
|
||
anchor = clause.get("evidence_anchor") if isinstance(clause.get("evidence_anchor"), dict) else None
|
||
if anchor and anchor.get("page_no"):
|
||
report_lines.append(f" 位置:回传合同第 {anchor.get('page_no')} 页")
|
||
old_text = re.sub(r"\s+", " ", str(clause.get("old_text") or "")).strip()
|
||
new_text = re.sub(r"\s+", " ", str(clause.get("new_text") or "")).strip()
|
||
report_lines.append(f" 我方原文:{old_text or '(无)'}")
|
||
report_lines.append(f" 回传内容:{new_text or '(无)'}")
|
||
if clause.get("detail"):
|
||
report_lines.append(f" 差异说明:{clause.get('detail')}")
|
||
|
||
attachment = summary.get("attachment_comparison")
|
||
if isinstance(attachment, dict):
|
||
added = int(attachment.get("added_pages") or 0)
|
||
removed = int(attachment.get("removed_pages") or 0)
|
||
if added:
|
||
report_lines.extend(["", f"附件提示:回传合同新增附件 {added} 页,附件内容未列入差异。"])
|
||
elif removed:
|
||
report_lines.extend(["", f"附件提示:回传合同减少附件 {removed} 页,附件内容未列入差异。"])
|
||
return {
|
||
"high_risk_count": high,
|
||
"medium_risk_count": medium,
|
||
"low_risk_count": low,
|
||
"total_change_count": len(changes),
|
||
"summary_json": summary,
|
||
"clauses_json": clauses,
|
||
"report_text": "\n".join(report_lines),
|
||
}
|
||
|
||
|
||
def extract_text_from_bytes(filename: str, data: bytes) -> str:
|
||
"""
|
||
从上传合同字节中抽取正文。
|
||
|
||
核心逻辑:txt/md/csv 直接解码;docx 走 python-docx/XML;PDF 抽取后须通过可读性校验,
|
||
否则返回 [binary:…] 占位,供 analyze_compare 短路。
|
||
|
||
Args:
|
||
filename: 原始文件名(用于扩展名与占位提示)。
|
||
data: 文件字节。
|
||
|
||
Returns:
|
||
可读正文,或带 [binary:] 前缀的失败说明。
|
||
"""
|
||
name = (filename or "").lower()
|
||
if name.endswith((".txt", ".md", ".csv")):
|
||
return data.decode("utf-8", errors="ignore")
|
||
if name.endswith(".docx"):
|
||
return _extract_docx_text(data)
|
||
if name.endswith(".pdf"):
|
||
text = _extract_pdf_text(data)
|
||
cleaned = _clean_extracted_text(text)
|
||
# [STEP] 仅「清洗后仍可读」才进入 Diff;否则明确失败,避免乱码进结果卡
|
||
if cleaned and _is_readable_extracted_text(text):
|
||
return cleaned
|
||
return f"[binary:{filename}] PDF 文本编码不兼容或未能提取正文;请上传 Word 或可检索文本的 PDF。"
|
||
text = data.decode("utf-8", errors="ignore").strip()
|
||
if text:
|
||
return text
|
||
return f"[binary:{filename}] 未能提取正文,请上传 Word/PDF 文本版以便完整审查。"
|
||
|
||
|
||
def _extract_docx_text(data: bytes) -> str:
|
||
"""Extract paragraphs from docx, using python-docx when available and zip XML fallback otherwise."""
|
||
try:
|
||
from docx import Document
|
||
|
||
doc = Document(io.BytesIO(data))
|
||
return "\n".join(p.text for p in doc.paragraphs if p.text)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||
xml = zf.read("word/document.xml")
|
||
root = ElementTree.fromstring(xml)
|
||
texts = [node.text for node in root.iter() if node.tag.endswith("}t") and node.text]
|
||
return "\n".join(texts)
|
||
except Exception:
|
||
return data.decode("utf-8", errors="ignore")
|
||
|
||
|
||
def _extract_pdf_text(data: bytes) -> str:
|
||
"""
|
||
Extract the best available raw text from a PDF.
|
||
|
||
The caller cleans missing-glyph placeholders. Keeping the best partially readable result lets
|
||
contracts with an incomplete PDF character map retain usable Chinese clauses.
|
||
"""
|
||
candidates: list[str] = []
|
||
try:
|
||
import pdfplumber
|
||
|
||
with pdfplumber.open(io.BytesIO(data)) as pdf:
|
||
text = "\n".join((page.extract_text() or "") for page in pdf.pages)
|
||
if text.strip():
|
||
candidates.append(text)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
from pypdf import PdfReader
|
||
|
||
reader = PdfReader(io.BytesIO(data))
|
||
text = "\n".join((page.extract_text() or "") for page in reader.pages)
|
||
if text.strip():
|
||
candidates.append(text)
|
||
except Exception:
|
||
pass
|
||
return max(
|
||
candidates,
|
||
key=lambda value: len(re.findall(r"[\u4e00-\u9fffA-Za-z0-9]", _clean_extracted_text(value))),
|
||
default="",
|
||
)
|