Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
This commit is contained in:
commit
b91954df4a
106 files changed
+43359
No files matched your search
@@ -0,0 +1,553 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""四套系统共享的登录会话校验(Cookie + HMAC 签名)
|
||||
|
||||
设计:
|
||||
- 登录页在综合门户(8080 端口)的 /login
|
||||
- 登录成功后写一个 HMAC 签名的 Cookie(作用域是主机,浏览器对同一 IP 的不同端口共享)
|
||||
- 审计(8000)/风险(8001)/合同(8090) 校验同一个 Cookie,所以登录一次即可访问四个系统
|
||||
- 同时保留 HTTP Basic 兼容,便于脚本和系统内部调用(如门户代理合同接口)
|
||||
"""
|
||||
|
||||
import os
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import secrets
|
||||
import sqlite3
|
||||
import datetime
|
||||
from urllib.parse import quote, urlparse
|
||||
|
||||
from fastapi.responses import JSONResponse, RedirectResponse
|
||||
|
||||
AUTH_USER = os.getenv("AUTH_USER", "")
|
||||
AUTH_PASSWORD = os.getenv("AUTH_PASSWORD", "")
|
||||
SESSION_SECRET = os.getenv("SESSION_SECRET", "")
|
||||
|
||||
SESSION_COOKIE = "audit_session"
|
||||
SESSION_MAX_AGE = 12 * 3600 # 12 小时
|
||||
|
||||
MAX_FAILS = 10
|
||||
FAIL_WINDOW_SECONDS = 600
|
||||
|
||||
# 门户登录地址(默认按访问的 Host 推导,指向 8080 端口)
|
||||
PORTAL_LOGIN_URL = os.getenv("PORTAL_LOGIN_URL", "")
|
||||
|
||||
ENABLED = bool(AUTH_USER and AUTH_PASSWORD and SESSION_SECRET)
|
||||
|
||||
_FAILS = {}
|
||||
|
||||
|
||||
def _b64e(raw: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _b64d(text: str) -> bytes:
|
||||
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
||||
|
||||
|
||||
def _make_token(claims: dict) -> str:
|
||||
payload = json.dumps(
|
||||
{"u": claims.get("username", ""), "d": claims.get("display_name", ""),
|
||||
"r": claims.get("role", ""), "p": claims.get("permissions", []),
|
||||
"exp": int(time.time()) + SESSION_MAX_AGE},
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
sig = hmac.new(SESSION_SECRET.encode("utf-8"), payload, hashlib.sha256).digest()
|
||||
return _b64e(payload) + "." + _b64e(sig)
|
||||
|
||||
|
||||
def session_token(username: str) -> str:
|
||||
"""兼容旧调用:仅带用户名的会话令牌。"""
|
||||
return _make_token({"username": username})
|
||||
|
||||
|
||||
def session_token_for(claims: dict) -> str:
|
||||
"""带角色/权限的会话令牌。"""
|
||||
return _make_token(claims or {})
|
||||
|
||||
|
||||
def session_claims(token: str):
|
||||
if not token or token.count(".") != 1:
|
||||
return None
|
||||
p64, s64 = token.split(".", 1)
|
||||
try:
|
||||
payload = _b64d(p64)
|
||||
sig = _b64d(s64)
|
||||
except Exception:
|
||||
return None
|
||||
expected = hmac.new(SESSION_SECRET.encode("utf-8"), payload, hashlib.sha256).digest()
|
||||
if not hmac.compare_digest(sig, expected):
|
||||
return None
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
except Exception:
|
||||
return None
|
||||
if int(data.get("exp", 0)) < time.time():
|
||||
return None
|
||||
return data
|
||||
|
||||
|
||||
def session_user(token: str):
|
||||
data = session_claims(token)
|
||||
return data.get("u") if data else None
|
||||
|
||||
|
||||
def has_permission(claims, key: str) -> bool:
|
||||
if not claims:
|
||||
return False
|
||||
perms = claims.get("p") or claims.get("permissions") or []
|
||||
if isinstance(perms, str):
|
||||
try:
|
||||
perms = json.loads(perms)
|
||||
except Exception:
|
||||
perms = [perms]
|
||||
return "*" in perms or key in perms
|
||||
|
||||
|
||||
# ===== 密码覆盖文件(在系统设置里修改密码后写入,四套系统共享) =====
|
||||
AUTH_OVERRIDE_FILE = os.getenv(
|
||||
"AUTH_OVERRIDE_FILE",
|
||||
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".auth_override.json"),
|
||||
)
|
||||
_OVERRIDE_CACHE = {"mtime": None, "data": None}
|
||||
|
||||
|
||||
def _load_override():
|
||||
try:
|
||||
st = os.stat(AUTH_OVERRIDE_FILE)
|
||||
except Exception:
|
||||
return None
|
||||
if _OVERRIDE_CACHE["mtime"] == st.st_mtime:
|
||||
return _OVERRIDE_CACHE["data"]
|
||||
try:
|
||||
with open(AUTH_OVERRIDE_FILE, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
_OVERRIDE_CACHE["mtime"] = st.st_mtime
|
||||
_OVERRIDE_CACHE["data"] = data
|
||||
return data
|
||||
|
||||
|
||||
# ===== 多用户 / 角色权限(users.db 四套系统共享,唯一用户库) =====
|
||||
USERS_DB = os.getenv(
|
||||
"USERS_DB",
|
||||
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "综合管理平台", "users.db"),
|
||||
)
|
||||
|
||||
DEFAULT_ROLES = [
|
||||
("admin", "系统管理员", ["*"]),
|
||||
("auditor", "审计人员", ["home", "digital", "audit", "risk", "knowledge"]),
|
||||
("contract", "合同管理员", ["home", "contract", "knowledge"]),
|
||||
("viewer", "只读用户", ["home", "knowledge"]),
|
||||
]
|
||||
|
||||
|
||||
def _now():
|
||||
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _users_conn(create=False):
|
||||
if not create and not os.path.exists(USERS_DB):
|
||||
return None
|
||||
if create:
|
||||
os.makedirs(os.path.dirname(USERS_DB), exist_ok=True)
|
||||
conn = sqlite3.connect(USERS_DB, timeout=10)
|
||||
conn.row_factory = sqlite3.Row
|
||||
if create:
|
||||
conn.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
code TEXT UNIQUE, name TEXT, permissions TEXT, created_at TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE, display_name TEXT,
|
||||
password_hash TEXT, salt TEXT, role_id INTEGER, role_code TEXT,
|
||||
status TEXT DEFAULT '启用', created_at TEXT, last_login TEXT
|
||||
);
|
||||
""")
|
||||
conn.commit()
|
||||
return conn
|
||||
|
||||
|
||||
def _hash_password(password, salt_hex=None):
|
||||
salt = bytes.fromhex(salt_hex) if salt_hex else secrets.token_bytes(16)
|
||||
digest = hashlib.pbkdf2_hmac("sha256", (password or "").encode("utf-8"), salt, 200000)
|
||||
return salt.hex(), digest.hex()
|
||||
|
||||
|
||||
def _verify_password(password, salt_hex, expected_hash):
|
||||
try:
|
||||
salt = bytes.fromhex(salt_hex)
|
||||
digest = hashlib.pbkdf2_hmac("sha256", (password or "").encode("utf-8"), salt, 200000)
|
||||
return hmac.compare_digest(digest.hex(), expected_hash)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _fallback_claims(username):
|
||||
"""环境变量 / 密码覆盖文件登录成功后,默认按系统管理员处理。"""
|
||||
return {
|
||||
"username": username,
|
||||
"display_name": username,
|
||||
"role": "系统管理员",
|
||||
"role_code": "admin",
|
||||
"permissions": ["*"],
|
||||
"source": "env",
|
||||
}
|
||||
|
||||
|
||||
def authenticate(username: str, password: str):
|
||||
"""统一认证:先查 users.db,再回退到环境变量/密码覆盖文件。返回 claims 或 None。"""
|
||||
username = (username or "").strip()
|
||||
if not username:
|
||||
return None
|
||||
# 1) users.db 多用户
|
||||
try:
|
||||
conn = _users_conn()
|
||||
if conn:
|
||||
row = conn.execute("""
|
||||
SELECT u.*, r.code role_code, r.name role_name, r.permissions role_permissions
|
||||
FROM users u LEFT JOIN roles r ON u.role_id = r.id
|
||||
WHERE u.username = ? AND u.status = '启用'
|
||||
""", (username,)).fetchone()
|
||||
if row and _verify_password(password, row["salt"], row["password_hash"]):
|
||||
try:
|
||||
perms = json.loads(row["role_permissions"] or "[]")
|
||||
except Exception:
|
||||
perms = []
|
||||
conn.execute("UPDATE users SET last_login=? WHERE id=?", (_now(), row["id"]))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"] or row["username"],
|
||||
"role": row["role_name"] or "未授权",
|
||||
"role_code": row["role_code"] or "",
|
||||
"permissions": perms,
|
||||
"source": "db",
|
||||
}
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
# 2) 兼容原有单账号环境变量 / 密码覆盖文件
|
||||
if _check_static(username, password):
|
||||
return _fallback_claims(username)
|
||||
return None
|
||||
|
||||
|
||||
def _check_static(username, password) -> bool:
|
||||
override = _load_override()
|
||||
if override and override.get("username") and override.get("salt") and override.get("password_hash"):
|
||||
if not secrets.compare_digest(username or "", override["username"]):
|
||||
return False
|
||||
return _verify_password(password, override["salt"], override["password_hash"])
|
||||
return secrets.compare_digest(username or "", AUTH_USER) and secrets.compare_digest(
|
||||
password or "", AUTH_PASSWORD
|
||||
)
|
||||
|
||||
|
||||
def ensure_seed_users():
|
||||
"""首次部署时初始化角色,并按环境变量/覆盖文件创建管理员账号。"""
|
||||
conn = _users_conn(create=True)
|
||||
if conn is None:
|
||||
return {"ok": False, "error": "无法创建用户库"}
|
||||
for code, name, perms in DEFAULT_ROLES:
|
||||
exists = conn.execute("SELECT 1 FROM roles WHERE code=?", (code,)).fetchone()
|
||||
if not exists:
|
||||
conn.execute("INSERT INTO roles(code,name,permissions,created_at) VALUES (?,?,?,?)",
|
||||
(code, name, json.dumps(perms, ensure_ascii=False), _now()))
|
||||
admin_role = conn.execute("SELECT id FROM roles WHERE code='admin'").fetchone()
|
||||
admin_role_id = admin_role["id"] if admin_role else None
|
||||
user_count = conn.execute("SELECT COUNT(*) c FROM users").fetchone()["c"]
|
||||
if user_count == 0:
|
||||
override = _load_override()
|
||||
if override and override.get("username") and override.get("salt") and override.get("password_hash"):
|
||||
username = override["username"]
|
||||
salt, pwd_hash = override["salt"], override["password_hash"]
|
||||
elif AUTH_USER and AUTH_PASSWORD:
|
||||
username = AUTH_USER
|
||||
salt, pwd_hash = _hash_password(AUTH_PASSWORD)
|
||||
else:
|
||||
# 未配置 AUTH_USER/AUTH_PASSWORD 时,不再内置固定口令;
|
||||
# 生成随机初始密码并打印一次,要求部署者立即修改。
|
||||
username = "admin"
|
||||
generated = secrets.token_urlsafe(12)
|
||||
salt, pwd_hash = _hash_password(generated)
|
||||
print(f"[初始化] 未配置 AUTH_USER/AUTH_PASSWORD,已创建管理员 admin,"
|
||||
f"初始密码:{generated}(请立即修改并配置 .env)", flush=True)
|
||||
conn.execute("""INSERT INTO users(username,display_name,password_hash,salt,role_id,role_code,
|
||||
status,created_at) VALUES (?,?,?,?,?,?,?,?)""",
|
||||
(username, "系统管理员", pwd_hash, salt, admin_role_id, "admin", "启用", _now()))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {"ok": True, "db": USERS_DB}
|
||||
|
||||
|
||||
def list_roles():
|
||||
conn = _users_conn()
|
||||
if not conn:
|
||||
ensure_seed_users()
|
||||
conn = _users_conn()
|
||||
rows = [dict(r) for r in conn.execute("SELECT * FROM roles ORDER BY id").fetchall()]
|
||||
conn.close()
|
||||
for r in rows:
|
||||
try:
|
||||
r["permissions"] = json.loads(r.get("permissions") or "[]")
|
||||
except Exception:
|
||||
r["permissions"] = []
|
||||
return rows
|
||||
|
||||
|
||||
def list_users():
|
||||
conn = _users_conn()
|
||||
if not conn:
|
||||
ensure_seed_users()
|
||||
conn = _users_conn()
|
||||
rows = conn.execute("""
|
||||
SELECT u.id,u.username,u.display_name,u.role_id,u.role_code,u.status,u.created_at,u.last_login,
|
||||
r.name role_name
|
||||
FROM users u LEFT JOIN roles r ON u.role_id=r.id ORDER BY u.id
|
||||
""").fetchall()
|
||||
conn.close()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def save_user(data):
|
||||
"""创建/更新用户;password 为空则不改密码。"""
|
||||
conn = _users_conn(create=True)
|
||||
username = (data.get("username") or "").strip()
|
||||
if not username:
|
||||
raise ValueError("用户名不能为空")
|
||||
role_id = data.get("role_id")
|
||||
role = conn.execute("SELECT * FROM roles WHERE id=?", (role_id,)).fetchone() if role_id else None
|
||||
role_code = role["code"] if role else data.get("role_code", "viewer")
|
||||
if not role:
|
||||
role = conn.execute("SELECT * FROM roles WHERE code=?", (role_code,)).fetchone()
|
||||
role_id = role["id"] if role else None
|
||||
now = _now()
|
||||
uid = data.get("id")
|
||||
password = data.get("password") or ""
|
||||
if uid:
|
||||
if password:
|
||||
salt, pwd_hash = _hash_password(password)
|
||||
conn.execute("""UPDATE users SET display_name=?,role_id=?,role_code=?,status=?,
|
||||
password_hash=?,salt=? WHERE id=?""",
|
||||
(data.get("display_name", ""), role_id, role_code,
|
||||
data.get("status", "启用"), pwd_hash, salt, uid))
|
||||
else:
|
||||
conn.execute("UPDATE users SET display_name=?,role_id=?,role_code=?,status=? WHERE id=?",
|
||||
(data.get("display_name", ""), role_id, role_code,
|
||||
data.get("status", "启用"), uid))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return uid
|
||||
if not password:
|
||||
raise ValueError("新建用户必须设置密码")
|
||||
salt, pwd_hash = _hash_password(password)
|
||||
cur = conn.execute("""INSERT INTO users(username,display_name,password_hash,salt,role_id,role_code,
|
||||
status,created_at) VALUES (?,?,?,?,?,?,?,?)""",
|
||||
(username, data.get("display_name") or username, pwd_hash, salt,
|
||||
role_id, role_code, data.get("status", "启用"), now))
|
||||
conn.commit()
|
||||
uid = cur.lastrowid
|
||||
conn.close()
|
||||
return uid
|
||||
|
||||
|
||||
def delete_user(uid):
|
||||
conn = _users_conn()
|
||||
if not conn:
|
||||
return False
|
||||
row = conn.execute("SELECT * FROM users WHERE id=?", (uid,)).fetchone()
|
||||
if not row:
|
||||
conn.close()
|
||||
return False
|
||||
if row["role_code"] == "admin":
|
||||
admins = conn.execute("SELECT COUNT(*) c FROM users WHERE role_code='admin' AND status='启用'").fetchone()["c"]
|
||||
if admins <= 1:
|
||||
conn.close()
|
||||
raise ValueError("不能删除最后一个系统管理员")
|
||||
conn.execute("DELETE FROM users WHERE id=?", (uid,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
|
||||
def reset_user_password(uid, password):
|
||||
if not password:
|
||||
raise ValueError("密码不能为空")
|
||||
conn = _users_conn()
|
||||
if not conn:
|
||||
return False
|
||||
salt, pwd_hash = _hash_password(password)
|
||||
conn.execute("UPDATE users SET password_hash=?,salt=? WHERE id=?", (pwd_hash, salt, uid))
|
||||
conn.commit()
|
||||
affected = conn.total_changes
|
||||
conn.close()
|
||||
return affected > 0
|
||||
|
||||
|
||||
def check_credentials(username: str, password: str) -> bool:
|
||||
return authenticate(username, password) is not None
|
||||
|
||||
|
||||
def basic_ok(request) -> bool:
|
||||
header = request.headers.get("authorization", "")
|
||||
if not header.lower().startswith("basic "):
|
||||
return False
|
||||
try:
|
||||
decoded = base64.b64decode(header[6:]).decode("utf-8")
|
||||
except Exception:
|
||||
return False
|
||||
user, _, password = decoded.partition(":")
|
||||
return check_credentials(user, password)
|
||||
|
||||
|
||||
def login_url(request) -> str:
|
||||
if PORTAL_LOGIN_URL:
|
||||
return PORTAL_LOGIN_URL
|
||||
host = (request.headers.get("host") or "").split(":")[0] or "localhost"
|
||||
return f"http://{host}:8080/login"
|
||||
|
||||
|
||||
def client_ip(request) -> str:
|
||||
return request.client.host if request.client else "unknown"
|
||||
|
||||
|
||||
def login_fail_count(ip: str) -> int:
|
||||
now = time.time()
|
||||
fails = [t for t in _FAILS.get(ip, []) if now - t < FAIL_WINDOW_SECONDS]
|
||||
_FAILS[ip] = fails
|
||||
return len(fails)
|
||||
|
||||
|
||||
def record_fail(ip: str) -> None:
|
||||
_FAILS.setdefault(ip, []).append(time.time())
|
||||
|
||||
|
||||
def clear_fails(ip: str) -> None:
|
||||
_FAILS.pop(ip, None)
|
||||
|
||||
|
||||
def safe_next(next_url: str, request) -> str:
|
||||
"""只允许跳回本站地址,避免开放重定向"""
|
||||
if not next_url:
|
||||
return "/"
|
||||
if next_url.startswith("/") and not next_url.startswith("//"):
|
||||
return next_url
|
||||
try:
|
||||
parsed = urlparse(next_url)
|
||||
host = (request.headers.get("host") or "").split(":")[0]
|
||||
if parsed.scheme == "http" and parsed.hostname == host:
|
||||
return next_url
|
||||
except Exception:
|
||||
pass
|
||||
return "/"
|
||||
|
||||
|
||||
def guard(request, extra_exempt=()):
|
||||
"""未登录时返回响应;已登录/免登录返回 None"""
|
||||
if not ENABLED:
|
||||
return None
|
||||
|
||||
path = request.url.path
|
||||
if path.startswith("/api/health"):
|
||||
return None
|
||||
for prefix in extra_exempt:
|
||||
if path == prefix or path.startswith(prefix):
|
||||
return None
|
||||
|
||||
if session_user(request.cookies.get(SESSION_COOKIE)):
|
||||
return None
|
||||
if basic_ok(request):
|
||||
return None
|
||||
|
||||
if path.startswith("/api/"):
|
||||
return JSONResponse(
|
||||
status_code=401,
|
||||
content={"detail": "未登录", "login": login_url(request)},
|
||||
)
|
||||
|
||||
target = login_url(request) + "?next=" + quote(str(request.url), safe="")
|
||||
return RedirectResponse(target, status_code=302)
|
||||
|
||||
|
||||
LOGIN_HTML = """<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>登录 · XX大学附属医院审计管理平台</title>
|
||||
<style>
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;
|
||||
background:linear-gradient(135deg,#0f2027 0%,#203a43 45%,#2c5364 100%);
|
||||
font-family:"Microsoft YaHei","PingFang SC","Helvetica Neue",sans-serif;color:#e8f4ff}
|
||||
.login-card{width:min(92vw,410px);background:rgba(255,255,255,.06);backdrop-filter:blur(12px);
|
||||
border:1px solid rgba(120,220,255,.25);border-radius:18px;padding:38px 34px;
|
||||
box-shadow:0 20px 60px rgba(0,0,0,.45)}
|
||||
.brand{text-align:center;margin-bottom:24px}
|
||||
.brand h1{font-size:21px;margin:0 0 8px;letter-spacing:1px;color:#9fe8ff;font-weight:700}
|
||||
.brand p{margin:0;font-size:13px;color:#9fb8c8;letter-spacing:3px}
|
||||
label{display:block;font-size:13px;color:#a9c4d4;margin:14px 0 6px}
|
||||
input{width:100%;padding:12px 14px;border-radius:10px;border:1px solid rgba(140,220,255,.28);
|
||||
background:rgba(0,0,0,.25);color:#eaf7ff;font-size:15px;outline:none}
|
||||
input:focus{border-color:#4fd1ff;box-shadow:0 0 0 3px rgba(79,209,255,.15)}
|
||||
button{width:100%;margin-top:24px;padding:12px;border:0;border-radius:10px;
|
||||
background:linear-gradient(90deg,#0ea5e9,#22d3ee);color:#03202c;font-size:16px;
|
||||
font-weight:700;cursor:pointer;letter-spacing:3px}
|
||||
button:hover{filter:brightness(1.08)}
|
||||
.error{margin-top:14px;padding:10px 12px;border-radius:8px;background:rgba(255,80,80,.15);
|
||||
border:1px solid rgba(255,120,120,.4);color:#ffb4b4;font-size:13px;text-align:center}
|
||||
.footer{margin-top:22px;text-align:center;font-size:12px;color:#7d97a8}
|
||||
.pwd-wrap{position:relative}
|
||||
.pwd-wrap input{padding-right:48px}
|
||||
.pwd-eye{position:absolute;right:8px;top:50%;transform:translateY(-50%);width:36px;height:36px;
|
||||
border:0;background:transparent;color:#9fb8c8;font-size:17px;cursor:pointer;border-radius:8px;line-height:1}
|
||||
.pwd-eye:hover{color:#4fd1ff;background:rgba(79,209,255,.08)}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<form class="login-card" method="post" action="/api/login">
|
||||
<div class="brand">
|
||||
<h1>XX大学附属医院</h1>
|
||||
<p>审 计 管 理 平 台</p>
|
||||
</div>
|
||||
<input type="hidden" name="next" value="{{NEXT}}">
|
||||
<label for="username">账号</label>
|
||||
<input id="username" name="username" autocomplete="username" placeholder="请输入账号" required autofocus>
|
||||
<label for="password">密码</label>
|
||||
<div class="pwd-wrap">
|
||||
<input id="password" name="password" type="password" autocomplete="current-password" placeholder="请输入密码" required>
|
||||
<button type="button" class="pwd-eye" onclick="togglePwd('password', this)" aria-label="显示密码"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></button>
|
||||
</div>
|
||||
<button type="submit">登 录</button>
|
||||
{{ERROR_BLOCK}}
|
||||
<div class="footer">请使用管理员分配的账号登录</div>
|
||||
</form>
|
||||
<script>
|
||||
function togglePwd(id, btn) {
|
||||
var el = document.getElementById(id);
|
||||
if (!el) return;
|
||||
var show = el.type === 'password';
|
||||
el.type = show ? 'text' : 'password';
|
||||
btn.innerHTML = show ? '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>' : '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
|
||||
btn.setAttribute('aria-label', show ? '隐藏密码' : '显示密码');
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
def login_page_html(next_url: str = "/", error: str = "") -> str:
|
||||
import html as _html
|
||||
|
||||
err = f'<div class="error">{_html.escape(error)}</div>' if error else ""
|
||||
return LOGIN_HTML.replace("{{NEXT}}", _html.escape(next_url or "/")).replace(
|
||||
"{{ERROR_BLOCK}}", err
|
||||
)
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,function(){"use strict";var s=Object.freeze({__proto__:null,get Colors(){return dn},get Decimation(){return fn},get Filler(){return Dn},get Legend(){return Tn},get SubTitle(){return In},get Title(){return En},get Tooltip(){return Un}});function t(){}const F=(()=>{let t=0;return()=>t++})();function P(t){return null==t}function O(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function A(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function p(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function g(t,e){return p(t)?t:e}function T(t,e){return void 0===t?e:t}const V=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,B=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function k(t,e,i,s){let a,n,o;if(O(t))if(n=t.length,s)for(a=n-1;0<=a;a--)e.call(i,t[a],a);else for(a=0;a<n;a++)e.call(i,t[a],a);else if(A(t))for(o=Object.keys(t),n=o.length,a=0;a<n;a++)e.call(i,t[o[a]],o[a])}function W(t,e){let i,s,a,n;if(!t||!e||t.length!==e.length)return!1;for(i=0,s=t.length;i<s;++i)if(a=t[i],n=e[i],a.datasetIndex!==n.datasetIndex||a.index!==n.index)return!1;return!0}function N(e){if(O(e))return e.map(N);if(A(e)){const i=Object.create(null),s=Object.keys(e),a=s.length;let t=0;for(;t<a;++t)i[s[t]]=N(e[s[t]]);return i}return e}function H(t){return-1===["__proto__","prototype","constructor"].indexOf(t)}function j(t,e,i,s){var a;H(t)&&(a=e[t],i=i[t],A(a)&&A(i)?Y(a,i,s):e[t]=N(i))}function Y(i,t,s){var a,e=O(t)?t:[t],n=e.length;if(!A(i))return i;const o=(s=s||{}).merger||j;for(let t=0;t<n;++t)if(A(a=e[t])){const O=Object.keys(a);for(let t=0,e=O.length;t<e;++t)o(O[t],i,a,s)}return i}function $(t,e){return Y(t,e,{merger:U})}function U(t,e,i){var s;H(t)&&(s=e[t],i=i[t],A(s)&&A(i)?$(s,i):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=N(i)))}const X={"":t=>t,x:t=>t.x,y:t=>t.y};function q(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s=s.endsWith("\\")?s.slice(0,-1)+".":(i.push(s),"");return i}function m(t,e){const i=X[e]||(X[e]=function(){const i=q(e);return t=>{for(const e of i){if(""===e)break;t=t&&t[e]}return t}}());return i(t)}function K(t){return t.charAt(0).toUpperCase()+t.slice(1)}const G=t=>void 0!==t,u=t=>"function"==typeof t,Z=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function J(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const S=Math.PI,_=2*S,Q=_+S,tt=Number.POSITIVE_INFINITY,et=S/180,D=S/2,it=S/4,st=2*S/3,r=Math.log10,y=Math.sign;function at(t,e,i){return Math.abs(t-e)<i}function nt(t){var e=Math.round(t),e=(t=at(t,e,t/1e3)?e:t,Math.pow(10,Math.floor(r(t)))),t=t/e;return(t<=1?1:t<=2?2:t<=5?5:10)*e}function ot(t){const e=[],i=Math.sqrt(t);let s;for(s=1;s<i;s++)t%s==0&&(e.push(s),e.push(t/s));return i===(0|i)&&e.push(i),e.sort((t,e)=>t-e).pop(),e}function rt(t){return!isNaN(parseFloat(t))&&isFinite(t)}function lt(t,e){var i=Math.round(t);return i-e<=t&&t<=i+e}function ht(t,e,i){let s,a,n;for(s=0,a=t.length;s<a;s++)n=t[s][i],isNaN(n)||(e.min=Math.min(e.min,n),e.max=Math.max(e.max,n))}function L(t){return t*(S/180)}function ct(t){return t*(180/S)}function dt(i){if(p(i)){let t=1,e=0;for(;Math.round(i*t)/t!==i;)t*=10,e++;return e}}function ut(t,e){var i=e.x-t.x,e=e.y-t.y,t=Math.sqrt(i*i+e*e);let s=Math.atan2(e,i);return s<-.5*S&&(s+=_),{angle:s,distance:t}}function gt(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function ft(t,e){return(t-e+Q)%_-S}function v(t){return(t%_+_)%_}function pt(t,e,i,s){var t=v(t),e=v(e),i=v(i),a=v(e-t),n=v(i-t),o=v(t-e),r=v(t-i);return t===e||t===i||s&&e===i||n<a&&o<r}function C(t,e,i){return Math.max(e,Math.min(i,t))}function mt(t){return C(t,-32768,32767)}function c(t,e,i,s=1e-6){return t>=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function bt(e,i,t){t=t||(t=>e[t]<i);let s,a=e.length-1,n=0;for(;1<a-n;)t(s=n+a>>1)?n=s:a=s;return{lo:n,hi:a}}const f=(i,s,a,t)=>bt(i,a,t?t=>{var e=i[t][s];return e<a||e===a&&i[t+1][s]===a}:t=>i[t][s]<a),xt=(e,i,s)=>bt(e,s,t=>e[t][i]>=s);function vt(t,e,i){let s=0,a=t.length;for(;s<a&&t[s]<e;)s++;for(;a>s&&t[a-1]>i;)a--;return 0<s||a<t.length?t.slice(s,a):t}const _t=["push","pop","shift","splice","unshift"];function yt(a,t){a._chartjs?a._chartjs.listeners.push(t):(Object.defineProperty(a,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[t]}}),_t.forEach(t=>{const i="_onData"+K(t),s=a[t];Object.defineProperty(a,t,{configurable:!0,enumerable:!1,value(...e){var t=s.apply(this,e);return a._chartjs.listeners.forEach(t=>{"function"==typeof t[i]&&t[i](...e)}),t}})}))}function Mt(e,t){var i=e._chartjs;if(i){const s=i.listeners,a=s.indexOf(Line truncated
|
||||
@@ -0,0 +1,701 @@
|
||||
"""合同审核服务模块 - 提供合同解析、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"""
|
||||
<div class="issue-card" style="border-left-color:{sev_color}">
|
||||
<div class="issue-header">
|
||||
<span class="issue-num">问题 {i + 1}</span>
|
||||
<span class="issue-dim">{dim}</span>
|
||||
<span class="issue-sev" style="background:{sev_color}">{sev}</span>
|
||||
</div>
|
||||
<div class="issue-body">
|
||||
<p><strong>描述:</strong>{desc}</p>
|
||||
<p><strong>建议:</strong>{sugg}</p>
|
||||
</div>
|
||||
</div>"""
|
||||
|
||||
# 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"""
|
||||
<div class="bar-item">
|
||||
<div class="bar-value">{count}</div>
|
||||
<div class="bar" style="height:{max(height, 2)}%;background:{color}"></div>
|
||||
<div class="bar-label">{label}</div>
|
||||
</div>"""
|
||||
|
||||
# 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"""
|
||||
<div class="bar-item">
|
||||
<div class="bar-value">{count}</div>
|
||||
<div class="bar" style="height:{max(height, 2)}%"></div>
|
||||
<div class="bar-label">{label}</div>
|
||||
</div>"""
|
||||
|
||||
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"""<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{contract_name} - 合同审核报告</title>
|
||||
<style>
|
||||
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
|
||||
body {{
|
||||
font-family: 'Noto Sans SC', 'Microsoft YaHei', sans-serif;
|
||||
background: #0a0e1a;
|
||||
color: #e0e0e0;
|
||||
line-height: 1.8;
|
||||
padding: 20px;
|
||||
}}
|
||||
.container {{ max-width: 1000px; margin: 0 auto; }}
|
||||
.header {{
|
||||
background: linear-gradient(135deg, #0d1b2a, #1b263b);
|
||||
border: 1px solid #00d4ff;
|
||||
border-radius: 12px;
|
||||
padding: 30px;
|
||||
margin-bottom: 20px;
|
||||
text-align: center;
|
||||
}}
|
||||
.header h1 {{
|
||||
color: #00d4ff;
|
||||
font-size: 28px;
|
||||
margin-bottom: 10px;
|
||||
}}
|
||||
.header .meta {{ color: #8899aa; font-size: 14px; }}
|
||||
.risk-badge {{
|
||||
display: inline-block;
|
||||
padding: 6px 20px;
|
||||
border-radius: 20px;
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
margin-top: 10px;
|
||||
background: {risk_color};
|
||||
color: #0a0e1a;
|
||||
}}
|
||||
.section {{
|
||||
background: #111827;
|
||||
border: 1px solid #1e3a5f;
|
||||
border-radius: 10px;
|
||||
padding: 25px;
|
||||
margin-bottom: 20px;
|
||||
}}
|
||||
.section h2 {{
|
||||
color: #00d4ff;
|
||||
font-size: 20px;
|
||||
margin-bottom: 15px;
|
||||
border-bottom: 1px solid #1e3a5f;
|
||||
padding-bottom: 10px;
|
||||
}}
|
||||
.summary-text {{ color: #b0b8c8; font-size: 15px; }}
|
||||
.info-grid {{
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
}}
|
||||
.info-item {{
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 8px 12px;
|
||||
background: #0d1b2a;
|
||||
border-radius: 6px;
|
||||
}}
|
||||
.info-item .label {{ color: #6889aa; }}
|
||||
.info-item .value {{ color: #e0e0e0; }}
|
||||
.charts {{ display: flex; gap: 30px; flex-wrap: wrap; }}
|
||||
.chart-box {{ flex: 1; min-width: 300px; }}
|
||||
.chart-title {{ color: #00d4ff; font-size: 15px; margin-bottom: 15px; text-align: center; }}
|
||||
.bar-chart {{ display: flex; align-items: flex-end; justify-content: space-around; height: 150px; padding: 10px 0; }}
|
||||
.bar-item {{ display: flex; flex-direction: column; align-items: center; width: 50px; }}
|
||||
.bar-value {{ color: #00d4ff; font-size: 14px; margin-bottom: 5px; }}
|
||||
.bar {{ width: 30px; background: #00d4ff; border-radius: 4px 4px 0 0; min-height: 2px; transition: height 0.3s; }}
|
||||
.bar-label {{ color: #8899aa; font-size: 12px; margin-top: 5px; text-align: center; }}
|
||||
.issue-card {{
|
||||
background: #0d1b2a;
|
||||
border-left: 4px solid #888;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
margin-bottom: 12px;
|
||||
}}
|
||||
.issue-header {{ display: flex; gap: 10px; align-items: center; margin-bottom: 10px; }}
|
||||
.issue-num {{ color: #00d4ff; font-weight: bold; }}
|
||||
.issue-dim {{ color: #6889aa; font-size: 13px; }}
|
||||
.issue-sev {{ padding: 2px 10px; border-radius: 10px; font-size: 12px; font-weight: bold; color: #0a0e1a; }}
|
||||
.issue-body p {{ margin-bottom: 5px; color: #b0b8c8; font-size: 14px; }}
|
||||
.footer {{ text-align: center; color: #445566; font-size: 12px; padding: 20px; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>合同审核报告</h1>
|
||||
<div class="meta">合同名称:{contract_name} | 生成时间:{now_str}</div>
|
||||
<div class="risk-badge">风险等级:{risk_level}</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>基本信息</h2>
|
||||
<div class="info-grid">
|
||||
<div class="info-item"><span class="label">合同名称</span><span class="value">{contract_name}</span></div>
|
||||
<div class="info-item"><span class="label">合同类型</span><span class="value">{contract_type}</span></div>
|
||||
<div class="info-item"><span class="label">风险等级</span><span class="value" style="color:{risk_color}">{risk_level}</span></div>
|
||||
<div class="info-item"><span class="label">问题总数</span><span class="value">{len(issues)}</span></div>
|
||||
<div class="info-item"><span class="label">上传日期</span><span class="value">{upload_date}</span></div>
|
||||
<div class="info-item"><span class="label">审核时间</span><span class="value">{now_str}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>审核摘要</h2>
|
||||
<p class="summary-text">{summary}</p>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>问题统计</h2>
|
||||
<div class="charts">
|
||||
<div class="chart-box">
|
||||
<div class="chart-title">严重程度分布</div>
|
||||
<div class="bar-chart">{sev_chart}</div>
|
||||
</div>
|
||||
<div class="chart-box">
|
||||
<div class="chart-title">维度分布</div>
|
||||
<div class="bar-chart">{dim_chart}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>问题详情</h2>
|
||||
{issue_cards}
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
本报告由合同审核管理平台自动生成 | {now_str}
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
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()
|
||||
+1229
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,133 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""PDF 工具(Apache-2.0 友好依赖)
|
||||
|
||||
- 文本提取:PyPDF2(BSD-3-Clause)
|
||||
- 页面渲染:pypdfium2(Apache-2.0,内置 PDFium BSD-3-Clause)
|
||||
- 图像保存:Pillow(HPND)
|
||||
|
||||
用于替代原 PyMuPDF(AGPL/商业双许可),避免开源许可证冲突。
|
||||
"""
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _as_stream(source):
|
||||
if isinstance(source, (bytes, bytearray)):
|
||||
return io.BytesIO(bytes(source)), True
|
||||
return str(source), False
|
||||
|
||||
|
||||
def _open_pdf(source):
|
||||
from PyPDF2 import PdfReader
|
||||
stream, own = _as_stream(source)
|
||||
try:
|
||||
return PdfReader(stream), None
|
||||
finally:
|
||||
if own:
|
||||
pass
|
||||
|
||||
|
||||
def page_count(source) -> int:
|
||||
reader, _ = _open_pdf(source)
|
||||
try:
|
||||
return len(reader.pages)
|
||||
finally:
|
||||
try:
|
||||
stream = getattr(reader, "stream", None)
|
||||
if stream is not None:
|
||||
stream.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def extract_text(source) -> str:
|
||||
"""提取 PDF 全部文字;没有文字层时返回空字符串。"""
|
||||
reader, _ = _open_pdf(source)
|
||||
try:
|
||||
parts = []
|
||||
for page in reader.pages:
|
||||
try:
|
||||
parts.append(page.extract_text() or "")
|
||||
except Exception:
|
||||
parts.append("")
|
||||
return "\n".join(parts)
|
||||
finally:
|
||||
try:
|
||||
stream = getattr(reader, "stream", None)
|
||||
if stream is not None:
|
||||
stream.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def render_page_png(source, page_index: int = 0, scale: float = 1.6) -> bytes:
|
||||
"""把指定页渲染为 PNG 字节。"""
|
||||
import pypdfium2 as pdfium
|
||||
stream, own = _as_stream(source)
|
||||
pdf = pdfium.PdfDocument(stream)
|
||||
try:
|
||||
if page_index < 0 or page_index >= len(pdf):
|
||||
raise IndexError("页码超出范围")
|
||||
page = pdf[page_index]
|
||||
try:
|
||||
bitmap = page.render(scale=scale)
|
||||
try:
|
||||
image = bitmap.to_pil()
|
||||
buf = io.BytesIO()
|
||||
image.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
finally:
|
||||
try:
|
||||
bitmap.close()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
page.close()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
pdf.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def render_pages_png(source, scale: float = 2.0, max_pages: int = None) -> list:
|
||||
"""批量渲染页面为 PNG 字节列表;max_pages 为空则全部渲染。"""
|
||||
import pypdfium2 as pdfium
|
||||
stream, own = _as_stream(source)
|
||||
pdf = pdfium.PdfDocument(stream)
|
||||
result = []
|
||||
try:
|
||||
total = len(pdf)
|
||||
limit = total if not max_pages else min(total, max_pages)
|
||||
for i in range(limit):
|
||||
page = pdf[i]
|
||||
try:
|
||||
bitmap = page.render(scale=scale)
|
||||
try:
|
||||
image = bitmap.to_pil()
|
||||
buf = io.BytesIO()
|
||||
image.save(buf, format="PNG")
|
||||
result.append(buf.getvalue())
|
||||
finally:
|
||||
try:
|
||||
bitmap.close()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
page.close()
|
||||
except Exception:
|
||||
pass
|
||||
return result
|
||||
finally:
|
||||
try:
|
||||
pdf.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def is_pdf(path) -> bool:
|
||||
return str(path).lower().endswith(".pdf")
|
||||
@@ -0,0 +1,227 @@
|
||||
"""合同审核管理平台 - API服务器"""
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from fastapi import FastAPI, UploadFile, File, HTTPException, Query, Body
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
import uvicorn
|
||||
|
||||
import contract_service as cs
|
||||
|
||||
BASE_DIR = Path(__file__).parent.resolve()
|
||||
REPORT_DIR = BASE_DIR / "报告"
|
||||
REPORT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
app = FastAPI(title="合同审核管理平台")
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.mount("/reports", StaticFiles(directory=str(REPORT_DIR)), name="reports")
|
||||
|
||||
app.mount("/static", StaticFiles(directory=str(BASE_DIR)), name="static")
|
||||
|
||||
_SAFE_STATIC_SUFFIXES = {
|
||||
".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp",
|
||||
".css", ".js", ".woff", ".woff2", ".ttf",
|
||||
}
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def _block_unsafe_static(request, call_next):
|
||||
if request.url.path.startswith("/static/"):
|
||||
suffix = os.path.splitext(request.url.path)[1].lower()
|
||||
if suffix not in _SAFE_STATIC_SUFFIXES:
|
||||
return JSONResponse(status_code=404, content={"detail": "Not Found"})
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# ====== 登录会话(Cookie + HMAC 签名,四套系统共享) ======
|
||||
import auth_guard as auth
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def _auth_middleware(request, call_next):
|
||||
resp = auth.guard(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def index():
|
||||
index_path = BASE_DIR / "index.html"
|
||||
return HTMLResponse(content=index_path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@app.get("/api/contracts")
|
||||
async def list_contracts(
|
||||
date_from: str = Query(None),
|
||||
date_to: str = Query(None)
|
||||
):
|
||||
contracts = cs.list_contracts(date_from, date_to)
|
||||
return JSONResponse(content={"contracts": contracts})
|
||||
|
||||
|
||||
@app.post("/api/contracts/upload")
|
||||
async def upload_contract(file: UploadFile = File(...)):
|
||||
if not file.filename:
|
||||
raise HTTPException(status_code=400, detail="文件名不能为空")
|
||||
|
||||
ext = Path(file.filename).suffix.lower()
|
||||
if ext not in [".docx", ".pdf"]:
|
||||
raise HTTPException(status_code=400, detail="仅支持Word(.docx)和PDF(.pdf)文件")
|
||||
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp:
|
||||
shutil.copyfileobj(file.file, tmp)
|
||||
tmp_path = tmp.name
|
||||
|
||||
try:
|
||||
result = cs.upload_only(file.filename, tmp_path)
|
||||
return JSONResponse(content={"contract": result})
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
finally:
|
||||
if os.path.exists(tmp_path):
|
||||
os.remove(tmp_path)
|
||||
@app.post("/api/contracts/{contract_id}/review")
|
||||
async def review_contract(contract_id: int):
|
||||
"""调用大模型审核合同"""
|
||||
try:
|
||||
result = cs.review_and_save(contract_id)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail="审核失败:" + str(e))
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="合同不存在")
|
||||
return JSONResponse(content={"contract": result})
|
||||
|
||||
|
||||
@app.put("/api/contracts/{contract_id}/review")
|
||||
async def update_review(contract_id: int, body: dict = Body(...)):
|
||||
"""手动修改审核结果并重新生成报告"""
|
||||
result = cs.update_review(contract_id, body)
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="合同不存在")
|
||||
return JSONResponse(content={"contract": result})
|
||||
|
||||
|
||||
@app.get("/api/contracts/{contract_id}/preview", response_class=HTMLResponse)
|
||||
async def preview_contract(contract_id: int):
|
||||
"""在线预览:PDF 直接返回,Word 转成 HTML 返回"""
|
||||
contract = cs.get_contract(contract_id)
|
||||
if not contract:
|
||||
raise HTTPException(status_code=404, detail="合同不存在")
|
||||
path = contract.get("file_path") or ""
|
||||
if not path or not os.path.exists(path):
|
||||
alt = cs.CONTRACT_DIR / Path(path).name
|
||||
if alt.exists():
|
||||
path = str(alt)
|
||||
if not path or not os.path.exists(path):
|
||||
raise HTTPException(status_code=404, detail="合同文件不存在")
|
||||
|
||||
ext = Path(path).suffix.lower()
|
||||
if ext == ".pdf":
|
||||
from fastapi.responses import RedirectResponse
|
||||
return RedirectResponse(url=f"/api/contracts/{contract_id}/file")
|
||||
|
||||
try:
|
||||
body = cs.docx_to_html(path)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail="Word 预览转换失败:" + str(e))
|
||||
|
||||
html = """<!DOCTYPE html>
|
||||
<html lang="zh-CN"><head><meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>%s - 合同预览</title>
|
||||
<style>
|
||||
body{margin:0;background:#eef2f6;color:#1f2d3d;font-family:"Microsoft YaHei","PingFang SC",sans-serif}
|
||||
.bar{position:sticky;top:0;background:#16323c;color:#9fe8ff;padding:12px 24px;font-size:14px;display:flex;justify-content:space-between}
|
||||
.bar a{color:#9fe8ff;text-decoration:none}
|
||||
.paper{max-width:900px;margin:24px auto;background:#fff;padding:48px 56px;box-shadow:0 8px 30px rgba(0,0,0,.12);line-height:1.9;font-size:15px;border-radius:6px}
|
||||
.paper img{max-width:100%%;height:auto}
|
||||
.paper table{border-collapse:collapse;width:100%%}
|
||||
.paper td,.paper th{border:1px solid #d8dee8;padding:8px 10px}
|
||||
.paper h1,.paper h2,.paper h3{margin:1.2em 0 .5em}
|
||||
</style></head><body>
|
||||
<div class="bar"><span>%s - 合同预览(Word 自动转换)</span><a href="javascript:history.back()">← 返回</a></div>
|
||||
<div class="paper">%s</div>
|
||||
</body></html>""" % (contract.get("name", "合同"), contract.get("name", "合同"), body)
|
||||
return HTMLResponse(content=html, headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@app.get("/api/contracts/{contract_id}/file")
|
||||
async def get_contract_file(contract_id: int):
|
||||
"""预览/下载合同原文件:PDF 浏览器内预览,Word 下载"""
|
||||
import urllib.parse
|
||||
contract = cs.get_contract(contract_id)
|
||||
if not contract:
|
||||
raise HTTPException(status_code=404, detail="合同不存在")
|
||||
path = contract.get("file_path") or ""
|
||||
if not path or not os.path.exists(path):
|
||||
alt = cs.CONTRACT_DIR / Path(path).name
|
||||
if alt.exists():
|
||||
path = str(alt)
|
||||
if not path or not os.path.exists(path):
|
||||
raise HTTPException(status_code=404, detail="合同文件不存在")
|
||||
ext = Path(path).suffix.lower()
|
||||
name = Path(path).name
|
||||
if ext == ".pdf":
|
||||
return FileResponse(path, media_type="application/pdf",
|
||||
headers={"Content-Disposition": "inline; filename*=UTF-8''" + urllib.parse.quote(name)})
|
||||
return FileResponse(path, media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
headers={"Content-Disposition": "attachment; filename*=UTF-8''" + urllib.parse.quote(name)})
|
||||
|
||||
|
||||
@app.get("/api/contracts/{contract_id}")
|
||||
async def get_contract(contract_id: int):
|
||||
contract = cs.get_contract(contract_id)
|
||||
if not contract:
|
||||
raise HTTPException(status_code=404, detail="合同不存在")
|
||||
return JSONResponse(content={"contract": contract})
|
||||
|
||||
|
||||
@app.delete("/api/contracts/{contract_id}")
|
||||
async def delete_contract(contract_id: int):
|
||||
cs.delete_contract(contract_id)
|
||||
return JSONResponse(content={"success": True})
|
||||
|
||||
|
||||
@app.put("/api/contracts/{contract_id}/rectification")
|
||||
async def update_rectification(contract_id: int, body: dict = Body(...)):
|
||||
rectifications = body.get("rectifications", [])
|
||||
result = cs.update_rectification(contract_id, rectifications)
|
||||
return JSONResponse(content={"contract": result})
|
||||
|
||||
|
||||
@app.get("/api/statistics")
|
||||
async def get_statistics(
|
||||
date_from: str = Query(None),
|
||||
date_to: str = Query(None)
|
||||
):
|
||||
stats = cs.get_statistics(date_from, date_to)
|
||||
return JSONResponse(content=stats)
|
||||
|
||||
|
||||
@app.get("/api/reports/{filename}")
|
||||
async def get_report(filename: str):
|
||||
report_path = REPORT_DIR / filename
|
||||
if not report_path.exists():
|
||||
raise HTTPException(status_code=404, detail="报告不存在")
|
||||
return HTMLResponse(content=report_path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(app, host="0.0.0.0", port=8090)
|
||||
@@ -0,0 +1,10 @@
|
||||
fastapi
|
||||
uvicorn[standard]
|
||||
python-multipart
|
||||
python-docx
|
||||
pypdfium2
|
||||
Pillow
|
||||
pytesseract
|
||||
openai
|
||||
openpyxl
|
||||
PyPDF2
|
||||
@@ -0,0 +1,34 @@
|
||||
@echo off
|
||||
chcp 936 >nul
|
||||
title 合同审核管理平台
|
||||
cd /d "%~dp0"
|
||||
|
||||
echo ========================================
|
||||
echo 合同审核管理平台 - 服务启动中...
|
||||
echo ========================================
|
||||
echo.
|
||||
|
||||
netstat -ano | findstr ":8090 " | findstr "LISTENING" >nul 2>&1
|
||||
if %errorlevel% equ 0 (
|
||||
echo [提示] 端口 8090 已被占用,服务可能已在运行。
|
||||
start http://localhost:8090/
|
||||
pause
|
||||
exit /b 0
|
||||
)
|
||||
|
||||
set "PY=%~dp0.venv\Scripts\python.exe"
|
||||
if not exist "%PY%" (
|
||||
echo [错误] 未找到虚拟环境: %PY%
|
||||
echo 请先在本目录执行:
|
||||
echo uv venv .venv --python 3.12
|
||||
echo uv pip install --python .venv\Scripts\python.exe fastapi "uvicorn[standard]" python-multipart python-docx PyMuPDF openai openpyxl PyPDF2
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo [启动] 正在启动服务...
|
||||
echo [信息] 访问地址: http://localhost:8090
|
||||
echo [信息] 按 Ctrl+C 可停止服务
|
||||
echo.
|
||||
"%PY%" portal_server.py
|
||||
pause
|
||||
Reference in new issue
Block a user