Files
syops/backend/app/services/contract_payment/parse_service.py
T

433 lines
19 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/services/contract_payment/parse_service.py
用途:从 DOC/DOCX/PDF/TXT 抽取采购合同关键字段,并生成四个付款阶段的节点草稿。
依赖:标准库正则与日期处理;原文抽取由调用方传入,避免绑定某一种文件解析器。
逻辑:先识别固定字段和付款比例,再校验金额/比例/日期;无法确定的事实进入 needs_review,不猜测。
合同金额以正文抽出的正数为准;OA 的 0 与空值都不是有效总额。同一付款阶段的相同比例重复抽取不报重复。
"""
from __future__ import annotations
from os import unlink
import re
import tempfile
from datetime import date, timedelta
from decimal import Decimal, InvalidOperation
from typing import Any
import requests
from flask import current_app
from app.services.procurement_contract.analyze import extract_text_from_bytes
_DATE_RE = re.compile(r"(20\d{2})[\s_]*[年./-][\s_]*(\d{1,2})[\s_]*[月./-][\s_]*(\d{1,2})[\s_]*日?")
_MONEY_RE = re.compile(r"(?:设备总价款\s*[((]?含税[))]?|人民币合同金额|合同金额|合同总价|含税总价)[::\s¥¥]*([\d,]+(?:\.\d+)?)", re.I)
_PERCENT_RE = re.compile(r"(预付款|定金|出货款|货款|验收款|质保款|保款|尾款)[^。;;\n]{0,140}?(\d+(?:\.\d+)?)\s*%", re.S)
_DELIVERY_RE = re.compile(r"(?:交货期限|约定到货日期|交付期限|交货期)[::\s]*[^。;;\n]{0,60}?(20\d{2}[^\n。;;]*)")
_WARRANTY_RE = re.compile(r"(?:质保期|保修期|保固期|质保款[^。;;\n]{0,100}?)(?:满后|为|:|:)?\s*(\d+)\s*(年|个月|月|天)")
_WARRANTY_PAYMENT_RE = re.compile(
r"(?:从验收(?:合格)?日起算\s*|质保款[^。;;\n]{0,100}?)(\d+)\s*(年|个月|月|天)\s*(?:质保期|保修期|保固期)?[^。;;\n]{0,24}?满后"
)
_CONTRACT_NO_RE = re.compile(r"(?:合同编号|合同号|Contract\s*No\.?)[::\s]*([A-Za-z0-9][A-Za-z0-9\-_/..]{3,63})", re.I)
_PAYMENT_NODE_LABELS = {
"prepayment": "预付款",
"shipment": "出货款",
"acceptance": "验收款",
"warranty": "质保款",
}
_PAYMENT_LABEL_TO_NODE_TYPE = {
"预付款": "prepayment", "定金": "prepayment",
"出货款": "shipment", "货款": "shipment",
"验收款": "acceptance",
"质保款": "warranty", "尾款": "warranty",
}
_PAYMENT_NODE_TYPES = tuple(_PAYMENT_NODE_LABELS)
def _parse_date(value: str | None) -> date | None:
"""
解析常见中文日期。
核心逻辑:只接受明确的年月日文本,避免将不完整期限猜测为业务日期。
Args:
value: 待解析的日期文本,可为空。
Returns:
合法日期;无法识别时返回 None。
"""
if not value:
return None
match = _DATE_RE.search(str(value))
if not match:
return None
try:
return date(int(match.group(1)), int(match.group(2)), int(match.group(3)))
except ValueError:
return None
def _parse_decimal(value: str | None) -> Decimal | None:
"""
解析金额或比例数字,忽略千分位逗号。
Args:
value: 金额或百分比中的数字文本。
Returns:
Decimal 数值;格式非法时返回 None。
"""
if value is None:
return None
try:
return Decimal(str(value).replace(",", "").strip())
except (InvalidOperation, ValueError):
return None
def positive_amount(value: object) -> Decimal | None:
"""把金额归一为大于 0 的 Decimal。
核心逻辑:员工在 OA「合同金额」手填 0 时,0 与空值一样,都不能当成有效总额。
正文抽出的正数才会用于阶段金额,并在台账总额为 0 或空时回写。
Args:
value: OA 字段、正文抽取结果或库里的金额,可为 str、Decimal 或 None。
Returns:
大于 0 的金额;空值、0、负数或非法格式返回 None。
"""
if value is None:
return None
parsed = _parse_decimal(str(value))
if parsed is None or parsed <= 0:
return None
return parsed
def _to_days(value: int, unit: str) -> int:
"""
将质保期限统一为自然日。
核心逻辑:按合同预警域现有约定,将年按 365 天、月按 30 天换算。
Args:
value: 期限数值,必须为非负整数。
unit: 年、月、个月或天。
Returns:
对应自然日数。
"""
if unit == "年":
return value * 365
if unit in {"月", "个月"}:
return value * 30
return value
def unique_parse_issues(issues: list[Any] | None) -> list[str]:
"""
按出现顺序去掉重复的解析问题文案。
核心逻辑:MinerU/OCR 常把付款表重复抽成多段,同一阶段会命中多次;页面只需要
每种原因一条,避免「出货款付款比例重复」连写六遍。空串和纯空白丢弃。
Args:
issues: 解析器或已落库 JSON 中的 issues 列表。
Returns:
去重后的问题文案;入参非法时返回空列表。
"""
if not isinstance(issues, list):
return []
seen: set[str] = set()
result: list[str] = []
for item in issues:
text = str(item or "").strip()
if not text or text in seen:
continue
seen.add(text)
result.append(text)
return result
def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[str]]:
"""
提取四阶段付款比例,并校验阶段完整性及比例合计。
核心逻辑:同一语义阶段只允许一个比例。正文里同一比例被抽到多次(表格/页眉重复)
视为同一事实,不报重复;只有同一阶段出现不同比例才阻断。四阶段须完整且合计 100%。
Args:
body: 已抽取的合同正文。
Returns:
按付款节点归一化的比例,以及阻断自动预警的解析问题。
"""
found: dict[str, list[Decimal]] = {node_type: [] for node_type in _PAYMENT_NODE_TYPES}
issues: list[str] = []
for match in _PERCENT_RE.finditer(body):
label, raw = match.groups()
node_type = _PAYMENT_LABEL_TO_NODE_TYPE[label]
percentage = _parse_decimal(raw)
if percentage is None:
issues.append(f"{label}付款比例无法识别")
continue
found[node_type].append(percentage)
percentages: dict[str, Decimal] = {}
for node_type in _PAYMENT_NODE_TYPES:
values = found[node_type]
if not values:
continue
unique_values = list(dict.fromkeys(values))
if len(unique_values) > 1:
issues.append(f"{_PAYMENT_NODE_LABELS[node_type]}付款比例重复,需人工确认")
continue
percentages[node_type] = unique_values[0]
missing = [node_type for node_type in _PAYMENT_NODE_TYPES if node_type not in percentages]
if missing:
issues.append(f"付款阶段比例无法识别:{'、'.join(_PAYMENT_NODE_LABELS[item] for item in missing)}")
try:
matched = [(m.group(1), m.group(2)) for m in _PERCENT_RE.finditer(body)]
snippet = ""
for label in ("质保款", "验收款", "尾款"):
idx = body.find(label)
if idx >= 0:
snippet = body[max(0, idx - 40):idx + 80].replace("\n", "⏎")
break
current_app.logger.warning(
"合同付款预警:付款比例提取缺失 missing=%s matched=%s 片段=%r",
[_PAYMENT_NODE_LABELS[item] for item in missing], matched, snippet,
)
except Exception:
pass
elif sum(percentages.values(), Decimal("0")) != Decimal("100"):
issues.append("四阶段付款比例合计不等于100%")
return percentages, unique_parse_issues(issues)
def _log_delivery_extraction(body: str) -> None:
"""交货期限无法识别时输出正文片段与日期模式数,便于定位 MinerU/OCR 抽取差异。"""
from flask import current_app
snippet = ""
for token in ("交货期限", "约定到货", "交货期", "交付", "到货", "出货"):
idx = body.find(token)
if idx >= 0:
snippet = body[max(0, idx - 30):idx + 90].replace("\n", " ")
break
current_app.logger.warning(
"合同付款预警:交货期限未能识别;日期模式数=%s 正文片段=%r", len(_DATE_RE.findall(body)), snippet,
)
def _extract_mineru_text(filename: str, data: bytes) -> str:
"""
调用 MinerU 提取 PDF 的 Markdown 正文,作为合同付款条款的首选来源。
核心逻辑:将单份 PDF 上传至内网 MinerU `/file_parse`,只接受成功结果中非空的
`md_content`;Markdown 保留表格、标题与阅读顺序,便于后续规则识别付款比例。服务
未配置、超时或返回异常时返回空字符串,由调用方明确回退旧解析链路。
Args:
filename: 原始合同文件名,必须以 `.pdf` 结尾才会调用 MinerU。
data: 原始 PDF 字节,不允许为空。
Returns:
MinerU 返回的 Markdown 正文;未配置或解析失败时为空字符串。
"""
if not str(filename or "").lower().endswith(".pdf") or not data:
return ""
# 合同付款与采购合同审核解析同一类合同,固定复用审核域唯一的 MinerU 服务配置。
api_url = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_API_URL") or "").strip().rstrip("/")
if not api_url:
return ""
connect_timeout = max(int(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS") or 5), 1)
read_timeout = max(int(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS") or 300), 30)
backend = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_BACKEND") or "pipeline").strip() or "pipeline"
parse_method = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD") or "auto").strip() or "auto"
try:
response = requests.post(
f"{api_url}/file_parse",
data={
"lang_list": "ch",
"backend": backend,
"parse_method": parse_method,
"formula_enable": "false",
},
files=[("files", (filename, data, "application/pdf"))],
timeout=(connect_timeout, read_timeout),
)
response.raise_for_status()
result = response.json()
except (ValueError, requests.RequestException):
return ""
if str(result.get("status") or "").lower() != "completed":
return ""
results = result.get("results")
if not isinstance(results, dict):
return ""
parsed = next((value for value in results.values() if isinstance(value, dict)), None)
return str((parsed or {}).get("md_content") or "").strip()
def _extract_ocr_text(filename: str, data: bytes) -> str:
"""
对扫描 PDF 执行 OCR 兜底。
核心逻辑:仅对 PDF 调用现有 OCR 能力;依赖不可用或解析失败时返回空文本,不伪造合同条款。
Args:
filename: 原始文件名,用于判断文件类型。
data: 原始文件字节。
Returns:
已识别的正文;无结果时为空字符串。
"""
if not str(filename or "").lower().endswith(".pdf"):
return ""
path = ""
try:
from edkb_system.contracts import Context
from edkb_system.skills import loader_pdf, ocr
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as handle:
handle.write(data)
path = handle.name
try:
context = Context(file_type="pdf")
blocks = loader_pdf.run({"file_path": path}, context)
if any(getattr(block, "type", "") == "image" for block in blocks):
blocks = ocr.run(blocks, context)
return "\n".join(
str(getattr(block, "text", "")).strip()
for block in blocks
if getattr(block, "type", "") in {"paragraph", "ocr_text"} and str(getattr(block, "text", "")).strip()
)
finally:
if path:
unlink(path)
except Exception:
return ""
def parse_contract_text(text: str, *, total_amount: Decimal | None = None, delivery_due_date: date | None = None) -> dict[str, Any]:
"""
解析合同正文并生成付款计划草稿。
AI 触发时机:合同附件保存后,需要自动获得付款节点时调用。
参数约束:text 为已抽取正文;不允许用模型猜测缺失日期或比例,结果必须可序列化为 JSON。
口径约定:合同正文抽出的正数金额优先于 OA。OA「合同金额」为 0 或空视为未录入,
不生成“与OA字段不一致”的待确认问题;正文没有正数时才回退 OA 里大于 0 的金额。
两边都没有有效金额时进入待确认,不把 0 当成总额。
Returns:
包含 fields、nodes、status、issues、evidence 的结构化结果。
"""
body = str(text or "")
if body.startswith("[binary:"):
body = ""
issues: list[str] = []
# [STEP 1] 金额:正文正数优先。OA 手填 0 与空值都不是有效总额,不能拿来乘付款比例。
# 正文没有正数时,才用 OA 里大于 0 的金额;两边都没有则金额留空并进入待确认。
amount_match = _MONEY_RE.search(body)
amount_from_contract = positive_amount(amount_match.group(1)) if amount_match else None
total_decimal = positive_amount(total_amount)
# 正文缺失时需回退 OA 交货期限;OA 字段可能以字符串到达(如 "2026-09-10"),
# 归一为 date 避免交付节点在 due_date.isoformat() 处因字符串抛错。
delivery_due_date = _parse_date(delivery_due_date)
amount = amount_from_contract if amount_from_contract is not None else total_decimal
delivery_match = _DELIVERY_RE.search(body)
delivery_from_contract = _parse_date(delivery_match.group(1)) if delivery_match else None
delivery = delivery_from_contract or delivery_due_date
if delivery is None:
# 合同常把日期写在“出货款/交货”句中,补充从付款条款附近抓取日期。
for match in _DATE_RE.finditer(body):
prefix = body[max(0, match.start() - 80):match.start()]
if any(token in prefix for token in ("交货", "交付", "到货", "出货")):
delivery = _parse_date(match.group(0))
break
warranty_days = None
# 付款条款中的期限优先于通用“保固”描述,确保质保款按应付款到期日预警。
warranty_match = _WARRANTY_PAYMENT_RE.search(body) or _WARRANTY_RE.search(body)
if warranty_match:
warranty_days = _to_days(int(warranty_match.group(1)), warranty_match.group(2))
contract_no_match = _CONTRACT_NO_RE.search(body)
contract_no = contract_no_match.group(1).strip(" 。;;,,") if contract_no_match else None
# [STEP 1] 一致性问题不再作为待确认阻断:正文为准,OA 仅在正文缺失时兜底。
# 资金与交货期限的取值已在上面以 amount / delivery 完成,此处只保留“无法识别”类问题。
if amount is None:
issues.append("合同金额无法识别")
if delivery is None:
issues.append("合同交货期限无法识别")
try:
_log_delivery_extraction(body)
except Exception:
pass
percentages, payment_issues = _extract_payment_percentages(body)
issues.extend(payment_issues)
issues = unique_parse_issues(issues)
nodes: list[dict[str, Any]] = []
for code, node_type in (("prepayment", "prepayment"), ("shipment", "shipment"), ("acceptance", "acceptance"), ("warranty", "warranty")):
percentage = percentages.get(node_type)
if percentage is None:
continue
node_amount = (amount * percentage / Decimal("100")).quantize(Decimal("0.01")) if amount is not None else None
# [STEP 1] 预付款和出货款是否已付款由 ERP apa_file 判定;合同只提供节点金额和出货款到期锚点。
anchor_type = (
"erp_payment"
if node_type in {"prepayment", "shipment"}
else "acceptance_archive"
)
due_date = delivery if node_type == "shipment" and delivery else None
nodes.append({
"node_code": code,
"node_type": node_type,
"amount": str(node_amount) if node_amount is not None else None,
"percentage": str(percentage),
"anchor_type": anchor_type,
"offset_days": 0,
"due_date": due_date.isoformat() if due_date else None,
"reminder_days": 0,
"evidence": {"matched_percent": str(percentage)},
})
if not nodes:
issues.append("未识别到预付款、出货款、验收款或质保款比例")
return {
"status": "needs_review" if issues else "parsed",
"fields": {
"contract_no": contract_no,
"total_amount": str(amount) if amount is not None else None,
"delivery_due_date": delivery.isoformat() if delivery else None,
"warranty_period_days": warranty_days,
},
"nodes": nodes,
"issues": issues,
"evidence": {
"parser": "contract-payment-four-stage-rules",
},
}
def parse_contract_bytes(filename: str, data: bytes, *, total_amount: Decimal | None = None, delivery_due_date: date | None = None) -> dict[str, Any]:
"""
从 DOC/DOCX/PDF 原文抽取文本后解析付款计划。
AI 触发时机:合同附件已资产化,需要直接从文件生成付款计划时调用。
核心逻辑:PDF 优先由 MinerU 提取 Markdown;服务不可用时再用统一附件解析器和旧 OCR
回退,最后委托文本解析器形成节点。
Args:
filename: 合同原始文件名,必须保留扩展名以供解析器选择路径。
data: 合同原始字节,不允许传入空字节伪造解析结果。
total_amount: OA 提供的合同总额,仅在正文未识别时作为补充。
delivery_due_date: OA 提供的约定到货日期,仅在正文未识别时作为补充。
Returns:
可 JSON 序列化的付款计划解析结果;不确定事实返回 needs_review。
"""
# [STEP 1] 扫描版 OA 合同没有可用文字层,MinerU 的版面 Markdown 优先于低精度 OCR。
mineru_text = _extract_mineru_text(filename, data)
extractor = "mineru" if mineru_text else "native_text"
text = mineru_text or extract_text_from_bytes(filename, data)
if text.startswith("[binary:"):
# [STEP 2] MinerU 不可用时保持旧 OCR 作为可用性兜底,不把附件同步整体判为失败。
ocr_text = _extract_ocr_text(filename, data)
if ocr_text.strip():
text = ocr_text
extractor = "legacy_ocr"
result = parse_contract_text(text, total_amount=total_amount, delivery_due_date=delivery_due_date)
result.setdefault("evidence", {})["document_extractor"] = extractor
current_app.logger.info(
"合同付款预警:合同正文抽取 extractor=%s mineru_len=%d text_len=%d",
extractor, len(mineru_text or ""), len(text or ""),
)
return result