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,426 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""审计要素智能抽取(阶段 A3)
|
||||
|
||||
- 合同关键字段:合同编号、甲方、乙方、合同金额、签约/生效/截止日期、付款方式、违约责任
|
||||
- 单据关键信息:发票号码、开票日期、购买方、销售方、价税合计、税率
|
||||
- 文本来自 OCR/文档解析,识别结果支持人工纠偏后保存
|
||||
数据写入 digital_audit.db;原文保存在 综合管理平台/uploads/da_extract/
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
import threading
|
||||
import datetime
|
||||
from pathlib import Path
|
||||
import operator_context as opctx
|
||||
|
||||
BASE_DIR = Path(__file__).parent.resolve()
|
||||
DB_PATH = BASE_DIR / "digital_audit.db"
|
||||
FILES_DIR = BASE_DIR / "uploads" / "da_extract"
|
||||
|
||||
EXTRACT_TYPES = {
|
||||
"contract": "合同关键字段",
|
||||
"invoice": "单据信息提取",
|
||||
}
|
||||
|
||||
CONTRACT_FIELDS = [
|
||||
("contract_no", "合同编号"),
|
||||
("party_a", "甲方"),
|
||||
("party_b", "乙方"),
|
||||
("amount", "合同金额"),
|
||||
("sign_date", "签约日期"),
|
||||
("effective_date", "生效日期"),
|
||||
("expiry_date", "截止日期"),
|
||||
("payment_method", "付款方式"),
|
||||
("breach_clause", "违约责任"),
|
||||
]
|
||||
|
||||
INVOICE_FIELDS = [
|
||||
("invoice_no", "发票号码"),
|
||||
("invoice_date", "开票日期"),
|
||||
("buyer", "购买方名称"),
|
||||
("seller", "销售方名称"),
|
||||
("total_amount", "价税合计"),
|
||||
("tax_rate", "税率"),
|
||||
]
|
||||
|
||||
DATE_PAT = r"(\d{4}\s*[-年./]\s*\d{1,2}\s*[-月./]\s*\d{1,2}\s*日?)"
|
||||
|
||||
|
||||
def _now():
|
||||
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _conn():
|
||||
conn = sqlite3.connect(str(DB_PATH), timeout=15)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA busy_timeout=15000")
|
||||
return conn
|
||||
|
||||
|
||||
def _log(action, detail):
|
||||
try:
|
||||
conn = _conn()
|
||||
conn.execute("INSERT INTO da_logs(action, detail, operator, created_at) VALUES (?,?,?,?)",
|
||||
(action, detail, opctx.get_operator(), _now()))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def init_db():
|
||||
FILES_DIR.mkdir(parents=True, exist_ok=True)
|
||||
conn = _conn()
|
||||
conn.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS da_extract_tasks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT, extract_type TEXT, status TEXT DEFAULT '待执行',
|
||||
progress INTEGER DEFAULT 0, file_count INTEGER DEFAULT 0,
|
||||
done_count INTEGER DEFAULT 0, created_at TEXT, finished_at TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS da_extract_files (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
task_id INTEGER, filename TEXT, ext TEXT, size INTEGER DEFAULT 0,
|
||||
stored_path TEXT, text_content TEXT, status TEXT DEFAULT '待抽取',
|
||||
error TEXT, created_at TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS da_extract_results (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
file_id INTEGER, task_id INTEGER, fields TEXT,
|
||||
corrected INTEGER DEFAULT 0, updated_at TEXT
|
||||
);
|
||||
""")
|
||||
conn.executescript("""
|
||||
CREATE INDEX IF NOT EXISTS idx_da_extract_tasks_status ON da_extract_tasks(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_da_extract_files_task ON da_extract_files(task_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_da_extract_results_file ON da_extract_results(file_id);
|
||||
""")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def _safe_name(name):
|
||||
return (name or "file").replace("/", "_").replace("\\", "_").replace("..", "_")
|
||||
|
||||
|
||||
def _first(patterns, text):
|
||||
for pat in patterns:
|
||||
m = re.search(pat, text, re.I | re.M)
|
||||
if m:
|
||||
value = (m.group(1) if m.groups() else m.group(0)).strip()
|
||||
value = re.sub(r"[ \t]+", " ", value)
|
||||
if not value:
|
||||
continue
|
||||
start = max(0, m.start() - 20)
|
||||
snippet = text[start:m.end() + 30].replace("\n", " ")
|
||||
return value, snippet
|
||||
return "", ""
|
||||
|
||||
|
||||
def _extract_contract(text):
|
||||
fields = []
|
||||
defs = [
|
||||
("contract_no", "合同编号", [r"(?:合同编号|合同编码|协议编号)[ \t]*[::]?[ \t]*([A-Za-z0-9\-_/()()【】\[\]]{3,40})"]),
|
||||
("party_a", "甲方", [r"(?m)^[ \t]*甲[ \t]*方(?:[ \t]*[((][^))\n]{0,20}[))])?[ \t]*[::][ \t]*([^\n,,;;]{2,60})"]),
|
||||
("party_b", "乙方", [r"(?m)^[ \t]*乙[ \t]*方(?:[ \t]*[((][^))\n]{0,20}[))])?[ \t]*[::][ \t]*([^\n,,;;]{2,60})"]),
|
||||
("amount", "合同金额", [r"(?:合同金额|合同总金额|合同总价|总金额|总价款|合同价款)[^0-9\n]{0,15}([0-9][0-9,,.]*(?:\.[0-9]{1,2})?[ \t]*(?:万元|元)?)"]),
|
||||
("sign_date", "签约日期", [r"(?:签订|签署|签约)(?:日期|时间)[ \t]*[::]?[ \t]*" + DATE_PAT]),
|
||||
("effective_date", "生效日期", [r"(?:生效日期|合同生效日|生效时间|本合同自)[ \t]*[::]?[ \t]*" + DATE_PAT]),
|
||||
("expiry_date", "截止日期", [r"(?:截止日期|合同期限|有效期至|合同有效期)[^\n。]{0,12}" + DATE_PAT]),
|
||||
("payment_method", "付款方式", [r"(?m)^[ \t]*(?:付款方式|支付方式|结算方式)[^\n::]{0,12}[::][ \t]*([^\n]{3,120})"]),
|
||||
("breach_clause", "违约责任", [r"(?m)^[ \t]*(?:违约责任|违约条款)[^\n::]{0,12}[::][ \t]*([^\n]{3,160})", r"([^\n。]{0,40}违约金[^\n。]{0,80})"]),
|
||||
]
|
||||
for key, label, pats in defs:
|
||||
value, snippet = _first(pats, text)
|
||||
if key in ("party_a", "party_b") and value:
|
||||
if "双方" in value or len(value) > 40 or value.startswith(("为了", "根据", "依照")):
|
||||
value, snippet = "", ""
|
||||
confidence = 0.9 if value else 0.0
|
||||
message = "已识别" if value else "未识别到,请人工补充"
|
||||
fields.append({"key": key, "label": label, "value": value,
|
||||
"confidence": confidence, "message": message, "snippet": snippet})
|
||||
return fields
|
||||
|
||||
|
||||
def _extract_invoice(text):
|
||||
fields = []
|
||||
defs = [
|
||||
("invoice_no", "发票号码", [r"(?:发票号码|发票号)\s*[::]?\s*(\d{8,20})"]),
|
||||
("invoice_date", "开票日期", [r"(?:开票日期|开票时间)\s*[::]?\s*" + DATE_PAT]),
|
||||
("buyer", "购买方名称", [r"(?:购买方名称|购\s*方|购买方)\s*[::]?\s*([^\n,,;;]{2,60})"]),
|
||||
("seller", "销售方名称", [r"(?:销售方名称|销\s*方|销售方)\s*[::]?\s*([^\n,,;;]{2,60})"]),
|
||||
("total_amount", "价税合计", [r"(?:价税合计|合计金额|价税总计)[^\n::]{0,12}[::]?\s*(?:人民币|¥|¥)?\s*([0-9][0-9,,.]*\s*(?:万元|元)?)"]),
|
||||
("tax_rate", "税率", [r"(?:税率)\s*[::]?\s*(\d{1,2}(?:\.\d{1,2})?\s*%)"]),
|
||||
]
|
||||
for key, label, pats in defs:
|
||||
value, snippet = _first(pats, text)
|
||||
valid = True
|
||||
message = "已识别" if value else "未识别到,请人工补充"
|
||||
if key == "invoice_no" and value and not re.fullmatch(r"\d{8,20}", value):
|
||||
valid = False
|
||||
message = "格式不符合发票号码规则"
|
||||
fields.append({"key": key, "label": label, "value": value,
|
||||
"confidence": 0.9 if value else 0.0, "valid": valid,
|
||||
"message": message, "snippet": snippet})
|
||||
return fields
|
||||
|
||||
|
||||
|
||||
|
||||
def _llm_config():
|
||||
try:
|
||||
settings = json.loads((BASE_DIR / "settings.json").read_text(encoding="utf-8"))
|
||||
llm = settings.get("llm") or {}
|
||||
base_url = (llm.get("base_url") or "").strip()
|
||||
model = (llm.get("model") or "").strip()
|
||||
api_key = (llm.get("api_key") or "").strip()
|
||||
if base_url and model and api_key:
|
||||
return base_url, model, api_key
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _llm_extract(extract_type, text):
|
||||
"""调用大模型做结构化抽取;无配置/失败返回空 dict,由正则结果兜底。"""
|
||||
cfg = _llm_config()
|
||||
if not cfg or not text.strip():
|
||||
return {}
|
||||
base_url, model, api_key = cfg
|
||||
labels = CONTRACT_FIELDS if extract_type == "contract" else INVOICE_FIELDS
|
||||
keys = "、".join(f"{k}({label})" for k, label in labels)
|
||||
prompt = (
|
||||
"你是医院审计要素抽取助手。请从下面的文本中抽取指定字段,只输出一个 JSON 对象,"
|
||||
"不要输出解释或代码块标记。键必须严格使用:" + keys + "。"
|
||||
"找不到的字段用空字符串 \"\"。不要编造内容。\n\n文本:\n" + text[:12000]
|
||||
)
|
||||
try:
|
||||
from openai import OpenAI
|
||||
client = OpenAI(api_key=api_key, base_url=base_url, timeout=60)
|
||||
resp = client.chat.completions.create(
|
||||
model=model,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
temperature=0,
|
||||
max_tokens=800,
|
||||
)
|
||||
content = (resp.choices[0].message.content or "").strip()
|
||||
content = re.sub(r"^```(?:json)?|```$", "", content, flags=re.M).strip()
|
||||
data = json.loads(content)
|
||||
allowed = {k for k, _ in labels}
|
||||
return {k: ("" if v is None else str(v)).strip() for k, v in data.items() if k in allowed}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def _extract(extract_type, text):
|
||||
fields = _extract_invoice(text) if extract_type == "invoice" else _extract_contract(text)
|
||||
ai = _llm_extract(extract_type, text)
|
||||
for f in fields:
|
||||
value = ai.get(f["key"], "")
|
||||
if value:
|
||||
f["value"] = value
|
||||
f["confidence"] = 0.95
|
||||
f["message"] = "AI抽取"
|
||||
return fields
|
||||
|
||||
|
||||
def create_task(name, extract_type, files):
|
||||
if extract_type not in EXTRACT_TYPES:
|
||||
extract_type = "contract"
|
||||
conn = _conn()
|
||||
now = _now()
|
||||
cur = conn.execute("""INSERT INTO da_extract_tasks(name,extract_type,status,progress,file_count,done_count,created_at)
|
||||
VALUES (?,?,?,?,?,?,?)""",
|
||||
((name or "要素抽取任务").strip(), extract_type, "待执行", 0, len(files), 0, now))
|
||||
task_id = cur.lastrowid
|
||||
folder = FILES_DIR / str(task_id)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
ids = []
|
||||
for filename, raw in files:
|
||||
filename = _safe_name(filename)
|
||||
path = folder / filename
|
||||
try:
|
||||
path.write_bytes(raw)
|
||||
except Exception:
|
||||
path = None
|
||||
c = conn.execute("""INSERT INTO da_extract_files(task_id,filename,ext,size,stored_path,status,created_at)
|
||||
VALUES (?,?,?,?,?,?,?)""",
|
||||
(task_id, filename, Path(filename).suffix.lower(), len(raw),
|
||||
str(path) if path else "", "待抽取", now))
|
||||
ids.append(c.lastrowid)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
_log("要素抽取任务创建", f"{name}({EXTRACT_TYPES.get(extract_type, extract_type)},{len(files)} 个文件)")
|
||||
threading.Thread(target=_run_task, args=(task_id, ids, extract_type), daemon=True).start()
|
||||
return task_id
|
||||
|
||||
|
||||
def _run_task(task_id, file_ids, extract_type):
|
||||
import digital_audit_service as das
|
||||
conn = _conn()
|
||||
try:
|
||||
conn.execute("UPDATE da_extract_tasks SET status='执行中' WHERE id=?", (task_id,))
|
||||
conn.commit()
|
||||
total = len(file_ids)
|
||||
done = 0
|
||||
for fid in file_ids:
|
||||
row = conn.execute("SELECT * FROM da_extract_files WHERE id=?", (fid,)).fetchone()
|
||||
if not row:
|
||||
continue
|
||||
try:
|
||||
raw = Path(row["stored_path"]).read_bytes() if row["stored_path"] else b""
|
||||
parsed = das.parse_document(row["filename"], raw, engine="general")
|
||||
text = parsed.get("content", "")
|
||||
fields = _extract(extract_type, text)
|
||||
conn.execute("UPDATE da_extract_files SET text_content=?, status='已完成', error='' WHERE id=?",
|
||||
(text, fid))
|
||||
exists = conn.execute("SELECT id FROM da_extract_results WHERE file_id=?", (fid,)).fetchone()
|
||||
if exists:
|
||||
conn.execute("UPDATE da_extract_results SET fields=?, corrected=0, updated_at=? WHERE file_id=?",
|
||||
(json.dumps(fields, ensure_ascii=False), _now(), fid))
|
||||
else:
|
||||
conn.execute("INSERT INTO da_extract_results(file_id,task_id,fields,corrected,updated_at) VALUES (?,?,?,?,?)",
|
||||
(fid, task_id, json.dumps(fields, ensure_ascii=False), 0, _now()))
|
||||
except Exception as e:
|
||||
conn.execute("UPDATE da_extract_files SET status='失败', error=? WHERE id=?", (str(e), fid))
|
||||
done += 1
|
||||
conn.execute("UPDATE da_extract_tasks SET progress=?, done_count=? WHERE id=?",
|
||||
(int(done * 100 / total) if total else 100, done, task_id))
|
||||
conn.commit()
|
||||
conn.execute("UPDATE da_extract_tasks SET status='已完成', progress=100, finished_at=? WHERE id=?",
|
||||
(_now(), task_id))
|
||||
conn.commit()
|
||||
_log("要素抽取任务完成", f"任务 {task_id}:{done}/{total} 个文件")
|
||||
except Exception as e:
|
||||
try:
|
||||
conn.execute("UPDATE da_extract_tasks SET status='执行失败' WHERE id=?", (task_id,))
|
||||
conn.commit()
|
||||
except Exception:
|
||||
pass
|
||||
_log("要素抽取任务失败", f"任务 {task_id}:{e}")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_tasks():
|
||||
conn = _conn()
|
||||
try:
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT * FROM da_extract_tasks ORDER BY id DESC LIMIT 100").fetchall()]
|
||||
for r in rows:
|
||||
r["type_label"] = EXTRACT_TYPES.get(r.get("extract_type"), r.get("extract_type"))
|
||||
return rows
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _fields_of(conn, fid):
|
||||
row = conn.execute("SELECT * FROM da_extract_results WHERE file_id=?", (fid,)).fetchone()
|
||||
if not row:
|
||||
return []
|
||||
try:
|
||||
return json.loads(row["fields"] or "[]")
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def get_task(task_id):
|
||||
conn = _conn()
|
||||
try:
|
||||
task = conn.execute("SELECT * FROM da_extract_tasks WHERE id=?", (task_id,)).fetchone()
|
||||
if not task:
|
||||
return None
|
||||
d = dict(task)
|
||||
d["type_label"] = EXTRACT_TYPES.get(d.get("extract_type"), d.get("extract_type"))
|
||||
files = [dict(r) for r in conn.execute(
|
||||
"SELECT id,task_id,filename,ext,size,status,error FROM da_extract_files WHERE task_id=? ORDER BY id",
|
||||
(task_id,)).fetchall()]
|
||||
for f in files:
|
||||
f["fields"] = _fields_of(conn, f["id"])
|
||||
d["files"] = files
|
||||
return d
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_file(fid):
|
||||
conn = _conn()
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM da_extract_files WHERE id=?", (fid,)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
d = dict(row)
|
||||
d["fields"] = _fields_of(conn, fid)
|
||||
return d
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_fields(fid, fields):
|
||||
conn = _conn()
|
||||
try:
|
||||
row = conn.execute("SELECT * FROM da_extract_results WHERE file_id=?", (fid,)).fetchone()
|
||||
current = _fields_of(conn, fid)
|
||||
by_key = {c.get("key"): c for c in current}
|
||||
if isinstance(fields, dict):
|
||||
items = [{"key": k, "value": v} for k, v in fields.items()]
|
||||
else:
|
||||
items = fields or []
|
||||
for item in items:
|
||||
k = item.get("key")
|
||||
if not k:
|
||||
continue
|
||||
if k in by_key:
|
||||
by_key[k]["value"] = item.get("value", "")
|
||||
by_key[k]["confidence"] = 1.0
|
||||
by_key[k]["message"] = "已人工校对"
|
||||
else:
|
||||
by_key[k] = {"key": k, "label": k, "value": item.get("value", ""),
|
||||
"confidence": 1.0, "message": "已人工校对", "snippet": ""}
|
||||
merged = list(by_key.values())
|
||||
if row:
|
||||
conn.execute("UPDATE da_extract_results SET fields=?, corrected=1, updated_at=? WHERE file_id=?",
|
||||
(json.dumps(merged, ensure_ascii=False), _now(), fid))
|
||||
else:
|
||||
conn.execute("INSERT INTO da_extract_results(file_id,task_id,fields,corrected,updated_at) VALUES (?,?,?,?,?)",
|
||||
(fid, 0, json.dumps(merged, ensure_ascii=False), 1, _now()))
|
||||
conn.commit()
|
||||
_log("要素人工校对", f"文件 {fid}")
|
||||
return merged
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def delete_task(task_id):
|
||||
conn = _conn()
|
||||
try:
|
||||
conn.execute("DELETE FROM da_extract_results WHERE task_id=?", (task_id,))
|
||||
conn.execute("DELETE FROM da_extract_files WHERE task_id=?", (task_id,))
|
||||
conn.execute("DELETE FROM da_extract_tasks WHERE id=?", (task_id,))
|
||||
conn.commit()
|
||||
folder = FILES_DIR / str(task_id)
|
||||
if folder.exists():
|
||||
shutil.rmtree(folder, ignore_errors=True)
|
||||
_log("要素抽取删除", f"任务 {task_id}")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def render_preview(file_id):
|
||||
row = get_file(file_id)
|
||||
if not row or not row.get("stored_path"):
|
||||
return None
|
||||
path = Path(row["stored_path"])
|
||||
if not path.exists():
|
||||
return None
|
||||
if row["ext"] in (".png", ".jpg", ".jpeg", ".bmp", ".webp"):
|
||||
return path.read_bytes(), "image/png"
|
||||
if row["ext"] == ".pdf":
|
||||
import pdf_tools
|
||||
return pdf_tools.render_page_png(path, page_index=0, scale=1.6), "image/png"
|
||||
return None
|
||||
|
||||
|
||||
init_db()
|
||||
Reference in new issue
Block a user