"""合同审核服务模块 - 提供合同解析、AI审核、报告生成与数据管理"""
import sqlite3
import json
import os
import datetime
import shutil
from pathlib import Path
# ============ 路径配置 ============
BASE_DIR = Path(__file__).parent.resolve()
DB_PATH = str(BASE_DIR / 'contract.db')
CONTRACT_DIR = BASE_DIR / '合同'
REPORT_DIR = BASE_DIR / '报告'
CONTRACT_DIR.mkdir(parents=True, exist_ok=True)
REPORT_DIR.mkdir(parents=True, exist_ok=True)
# ============ API配置(默认值,可在门户「系统设置」里覆盖) ============
API_KEY = "sk-ws-H.EIIIYIL.yjjO.MEQCIH0zxpg4LAQmoSonFkoyOG65fkQZmCqCOTw2qvSb_2LBAiAQM51Jp3TVlJnCXwz6S7ekVlnpLeOAXa_q_NDv-DiN_g"
BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
MODEL = "qwen-plus"
SETTINGS_FILE = BASE_DIR.parent / "综合管理平台" / "settings.json"
def get_llm_config():
"""优先使用门户「系统设置」里保存的大模型配置,其次使用默认值。"""
cfg = {"api_key": API_KEY, "base_url": BASE_URL, "model": MODEL}
try:
with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
llm = data.get("llm") or {}
if llm.get("base_url"):
cfg["base_url"] = str(llm["base_url"]).rstrip("/")
if llm.get("model"):
cfg["model"] = str(llm["model"])
if llm.get("api_key"):
cfg["api_key"] = str(llm["api_key"])
except Exception:
pass
return cfg
def get_db():
"""获取数据库连接"""
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def init_db():
"""初始化数据库表"""
conn = get_db()
conn.execute("""CREATE TABLE IF NOT EXISTS contracts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
file_path TEXT,
upload_date TEXT,
status TEXT DEFAULT 'pending',
contract_type TEXT,
risk_level TEXT,
issues TEXT,
rectifications TEXT,
report_path TEXT,
summary TEXT,
reviewed_at TEXT,
updated_at TEXT
)""")
conn.commit()
conn.close()
# ============ 文件解析 ============
def parse_docx(file_path):
"""解析Word文档"""
from docx import Document
doc = Document(file_path)
paragraphs = [p.text for p in doc.paragraphs if p.text.strip()]
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
txt = cell.text.strip()
if txt:
paragraphs.append(txt)
return "\n".join(paragraphs)
def parse_pdf(file_path):
"""解析PDF文档;扫描件(图片版)自动 OCR"""
import pdf_tools
text = pdf_tools.extract_text(file_path)
# 没有文字层(扫描件/图片版)时,用 OCR 识别
if len(text.strip()) < 20:
ocr_text = _ocr_pdf(file_path)
if ocr_text.strip():
text = ocr_text
return text
def _ocr_pdf(file_path):
"""把 PDF 页面渲染成图片后用 tesseract 中文 OCR"""
try:
import pdf_tools
import io
import pytesseract
from PIL import Image
except Exception:
return ""
# Windows 上如果 Tesseract 没加入 PATH,可通过环境变量指定
_tess = os.getenv("TESSERACT_CMD")
if _tess and os.path.exists(_tess):
pytesseract.pytesseract.tesseract_cmd = _tess
parts = []
for png in pdf_tools.render_pages_png(file_path, scale=200 / 72.0):
img = Image.open(io.BytesIO(png))
try:
t = pytesseract.image_to_string(img, lang="chi_sim+eng")
except Exception:
t = pytesseract.image_to_string(img)
if t.strip():
parts.append(t)
return "\n".join(parts)
def parse_file(file_path):
"""根据文件类型解析合同内容"""
ext = Path(file_path).suffix.lower()
if ext == ".docx":
return parse_docx(file_path)
elif ext == ".pdf":
return parse_pdf(file_path)
elif ext == ".txt":
with open(file_path, "r", encoding="utf-8") as f:
return f.read()
else:
raise ValueError("不支持的文件类型: " + ext)
def docx_to_html(file_path):
"""把 Word 文档转换成 HTML(供浏览器在线预览)"""
import base64
import mammoth
def convert_image(image):
with image.open() as image_bytes:
encoded = base64.b64encode(image_bytes.read()).decode("ascii")
return {"src": "data:" + image.content_type + ";base64," + encoded}
with open(file_path, "rb") as f:
result = mammoth.convert_to_html(f, convert_image=mammoth.images.img_element(convert_image))
return result.value or ""
# ============ AI审核 ============
def review_contract(content):
"""调用AI大模型审核合同,返回结构化审核结果"""
from openai import OpenAI
cfg = get_llm_config()
client = OpenAI(api_key=cfg["api_key"], base_url=cfg["base_url"])
prompt = """你是一位专业的合同审核专家。请从以下五个维度对合同进行全面审查:
1. 基本信息:合同名称、编号、签署日期、当事人信息、合同金额、期限等是否完整明确
2. 权利义务:双方权利义务是否对等,是否存在明显不对等条款
3. 违约责任:违约责任条款是否明确、合理,是否有明确的违约金计算方式
4. 风险条款:是否存在不利于我方的风险条款,是否有隐性风险
5. 缺失条款:是否缺少重要条款(如保密条款、知识产权条款、争议解决条款等)
请以JSON格式返回审核结果,格式如下:
{
"contract_type": "合同类型(如:采购合同、销售合同、服务合同、租赁合同、劳动合同、其他)",
"risk_level": "风险等级(极高/高/中/低/无)",
"summary": "合同整体摘要评价(100-200字)",
"issues": [
{
"dimension": "维度名称(基本信息/权利义务/违约责任/风险条款/缺失条款)",
"severity": "严重程度(极高/高/中/低)",
"description": "问题描述",
"suggestion": "修改建议"
}
]
}
只返回JSON,不要返回其他内容。"""
if len(content) > 30000:
content = content[:30000] + "\n[合同内容过长,已截断]"
response = client.chat.completions.create(
model=cfg["model"],
messages=[
{"role": "system", "content": "你是一位专业的合同审核法律专家,精通各类合同的审查与分析。"},
{"role": "user", "content": prompt + "\n\n合同内容如下:\n\n" + content}
],
temperature=0.3
)
result_text = response.choices[0].message.content.strip()
# Remove markdown code block wrapper if present
if result_text.startswith("```"):
lines = result_text.split("\n")
if lines[0].startswith("```"):
lines = lines[1:]
if lines and lines[-1].strip() == "```":
lines = lines[:-1]
result_text = "\n".join(lines)
result = json.loads(result_text)
return result
# ============ 报告生成 ============
def generate_report(contract_name, review_result, upload_date):
"""生成HTML审核报告"""
issues = review_result.get("issues", [])
risk_level = review_result.get("risk_level", "未知")
contract_type = review_result.get("contract_type", "未知")
summary = review_result.get("summary", "")
risk_colors = {
"极高": "#ff0040",
"高": "#ff6600",
"中": "#ffaa00",
"低": "#88cc00",
"无": "#00ff88"
}
risk_color = risk_colors.get(risk_level, "#888888")
# Count issues by severity
severity_counts = {}
for issue in issues:
sev = issue.get("severity", "中")
severity_counts[sev] = severity_counts.get(sev, 0) + 1
# Count issues by dimension
dimension_counts = {}
for issue in issues:
dim = issue.get("dimension", "其他")
dimension_counts[dim] = dimension_counts.get(dim, 0) + 1
# Build issue cards HTML
issue_cards = ""
for i, issue in enumerate(issues):
sev = issue.get("severity", "中")
sev_color = risk_colors.get(sev, "#888888")
dim = issue.get("dimension", "")
desc = issue.get("description", "")
sugg = issue.get("suggestion", "")
issue_cards += f"""
"""
# Build severity chart
sev_labels = ["极高", "高", "中", "低"]
sev_chart = ""
max_sev = max(severity_counts.values()) if severity_counts else 1
for label in sev_labels:
count = severity_counts.get(label, 0)
height = int(count / max_sev * 100) if max_sev > 0 else 0
color = risk_colors.get(label, "#888888")
sev_chart += f"""
"""
# Build dimension chart
dim_labels = ["基本信息", "权利义务", "违约责任", "风险条款", "缺失条款"]
dim_chart = ""
max_dim = max(dimension_counts.values()) if dimension_counts else 1
for label in dim_labels:
count = dimension_counts.get(label, 0)
height = int(count / max_dim * 100) if max_dim > 0 else 0
dim_chart += f"""
"""
now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
date_prefix = datetime.datetime.now().strftime("%Y%m%d")
report_filename = f"{date_prefix}_{contract_name}_审核报告.html"
report_filename = report_filename.replace(" ", "_").replace("/", "_")
html = f"""
{contract_name} - 合同审核报告
基本信息
合同名称{contract_name}
合同类型{contract_type}
风险等级{risk_level}
问题总数{len(issues)}
上传日期{upload_date}
审核时间{now_str}
问题详情
{issue_cards}
"""
report_path = REPORT_DIR / report_filename
report_path.write_text(html, encoding="utf-8")
return report_filename
# ============ CRUD操作 ============
def _ensure_text(content):
"""检查是否成功提取到文字(扫描件 PDF 没有文字层)"""
if len((content or "").strip()) < 20:
raise ValueError(
"未能从文件中提取到文字:该 PDF 可能是扫描件(图片版),"
"请上传 Word(.docx) 或文字版 PDF 后再审核。"
)
return content
def upload_only(file_name, file_path):
"""上传合同文件:仅保存并解析校验,不做 AI 审核"""
init_db()
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
stored_name = f"{timestamp}_{file_name}"
dest_path = CONTRACT_DIR / stored_name
shutil.copy2(file_path, dest_path)
# 上传阶段只保存文件,解析/OCR 留到点击「AI 审核」时进行,避免上传等待
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
conn = get_db()
conn.execute(
"""INSERT INTO contracts (name, file_path, upload_date, status, updated_at)
VALUES (?, ?, ?, ?, ?)""",
(file_name, str(dest_path), now, "pending", now),
)
conn.commit()
contract_id = conn.execute("SELECT last_insert_rowid()").fetchone()[0]
conn.close()
return get_contract(contract_id)
def _contract_content(contract):
"""读取合同正文(历史数据兼容其他机器的绝对路径)"""
path = contract.get("file_path") or ""
if not path or not os.path.exists(path):
alt = CONTRACT_DIR / Path(path).name
if alt.exists():
path = str(alt)
else:
raise ValueError("合同文件不存在,无法审核")
return _ensure_text(parse_file(path))
def review_and_save(contract_id):
"""调用大模型审核合同,保存结果并生成报告"""
contract = get_contract(contract_id)
if not contract:
return None
content = _contract_content(contract)
result = review_contract(content)
upload_date = contract.get("upload_date") or datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
report_filename = generate_report(contract["name"], result, upload_date)
report_path = REPORT_DIR / report_filename
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
conn = get_db()
conn.execute(
"""UPDATE contracts SET status='reviewed', contract_type=?, risk_level=?, issues=?,
report_path=?, summary=?, reviewed_at=?, updated_at=? WHERE id=?""",
(
result.get("contract_type", ""),
result.get("risk_level", ""),
json.dumps(result.get("issues", []), ensure_ascii=False),
str(report_path),
result.get("summary", ""),
now,
now,
contract_id,
),
)
conn.commit()
conn.close()
return get_contract(contract_id)
def update_review(contract_id, data):
"""手动修改审核结果,并重新生成 HTML 报告"""
contract = get_contract(contract_id)
if not contract:
return None
result = {
"contract_type": data.get("contract_type", contract.get("contract_type", "")),
"risk_level": data.get("risk_level", contract.get("risk_level", "")),
"summary": data.get("summary", contract.get("summary", "")),
"issues": data.get("issues", contract.get("issues", [])),
}
old_report = contract.get("report_path")
upload_date = contract.get("upload_date") or datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
report_filename = generate_report(contract["name"], result, upload_date)
report_path = REPORT_DIR / report_filename
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
conn = get_db()
conn.execute(
"""UPDATE contracts SET contract_type=?, risk_level=?, issues=?, report_path=?,
summary=?, updated_at=? WHERE id=?""",
(
result["contract_type"],
result["risk_level"],
json.dumps(result["issues"], ensure_ascii=False),
str(report_path),
result["summary"],
now,
contract_id,
),
)
conn.commit()
conn.close()
# 删除旧报告文件
if old_report and os.path.exists(old_report) and os.path.abspath(old_report) != os.path.abspath(str(report_path)):
try:
os.remove(old_report)
except Exception:
pass
return get_contract(contract_id)
def list_contracts(date_from=None, date_to=None):
"""查询合同列表"""
init_db()
conn = get_db()
query = "SELECT * FROM contracts WHERE 1=1"
params = []
if date_from:
query += " AND upload_date >= ?"
params.append(date_from)
if date_to:
query += " AND upload_date <= ?"
params.append(date_to + " 23:59:59")
query += " ORDER BY upload_date DESC"
rows = conn.execute(query, params).fetchall()
conn.close()
result = []
for row in rows:
item = dict(row)
try:
item["issues"] = json.loads(item.get("issues", "[]"))
except Exception:
item["issues"] = []
try:
item["rectifications"] = json.loads(item.get("rectifications", "[]"))
except Exception:
item["rectifications"] = []
result.append(item)
return result
def get_contract(contract_id):
"""查询单个合同详情"""
init_db()
conn = get_db()
row = conn.execute("SELECT * FROM contracts WHERE id = ?", (contract_id,)).fetchone()
conn.close()
if not row:
return None
item = dict(row)
try:
item["issues"] = json.loads(item.get("issues", "[]"))
except Exception:
item["issues"] = []
try:
item["rectifications"] = json.loads(item.get("rectifications", "[]"))
except Exception:
item["rectifications"] = []
return item
def update_rectification(contract_id, rectifications):
"""更新整改信息"""
init_db()
conn = get_db()
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
conn.execute(
"UPDATE contracts SET rectifications = ?, updated_at = ? WHERE id = ?",
(json.dumps(rectifications, ensure_ascii=False), now, contract_id)
)
conn.commit()
conn.close()
return get_contract(contract_id)
def delete_contract(contract_id):
"""删除合同及相关文件"""
init_db()
conn = get_db()
row = conn.execute("SELECT file_path, report_path FROM contracts WHERE id = ?", (contract_id,)).fetchone()
if row:
# Delete contract file(兼容历史数据中其他机器的绝对路径)
file_path = row["file_path"]
if file_path and not os.path.exists(file_path):
alt = CONTRACT_DIR / Path(file_path).name
if alt.exists():
file_path = str(alt)
if file_path and os.path.exists(file_path):
os.remove(file_path)
# Delete report file(同样兼容历史绝对路径)
report_path = row["report_path"]
if report_path and not os.path.exists(report_path):
alt = REPORT_DIR / Path(report_path).name
if alt.exists():
report_path = str(alt)
if report_path and os.path.exists(report_path):
os.remove(report_path)
# Delete from database
conn.execute("DELETE FROM contracts WHERE id = ?", (contract_id,))
conn.commit()
conn.close()
def get_statistics(date_from=None, date_to=None):
"""获取统计数据"""
contracts = list_contracts(date_from, date_to)
total = len(contracts)
risk_counts = {"极高": 0, "高": 0, "中": 0, "低": 0, "无": 0}
type_counts = {}
status_counts = {"pending": 0, "reviewed": 0}
for c in contracts:
risk = c.get("risk_level", "")
if risk in risk_counts:
risk_counts[risk] += 1
ctype = c.get("contract_type", "未知")
type_counts[ctype] = type_counts.get(ctype, 0) + 1
status = c.get("status", "pending")
if status in status_counts:
status_counts[status] += 1
total_issues = sum(len(c.get("issues", [])) for c in contracts)
return {
"total": total,
"risk_counts": risk_counts,
"type_counts": type_counts,
"status_counts": status_counts,
"total_issues": total_issues,
"avg_issues": round(total_issues / total, 1) if total > 0 else 0
}
# Initialize database on import
init_db()