Files
audit-platform/综合管理平台/parse_task_service.py
T
guwangtu b91954df4a
CI / check (push) Failing after 15m48s
chore: initial open-source baseline v1.0.0
Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
2026-12-05 15:44:53 +00:00

277 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""OCR 解析任务中心(阶段 A1)
- 任务可包含多个文件,支持通用/表格/手写实验三种识别引擎
- 后台线程逐个解析,前端轮询进度
- 保存原文用于双屏预览,识别结果支持 TXT / Word 导出
数据写入 digital_audit.db;原文保存在 综合管理平台/uploads/da_ocr/
"""
import json
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_ocr"
ENGINES = {
"general": "通用印刷体高精度",
"table": "含表格结构识别",
"handwritten": "手写体专项(实验)",
}
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_ocr_tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT, engine 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_ocr_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id INTEGER, filename TEXT, ext TEXT, size INTEGER DEFAULT 0,
mode TEXT, status TEXT DEFAULT '待解析', pages INTEGER DEFAULT 0,
char_count INTEGER DEFAULT 0, preview TEXT, content TEXT,
error TEXT, stored_path TEXT, created_at TEXT
);
""")
conn.executescript("""
CREATE INDEX IF NOT EXISTS idx_da_ocr_tasks_status ON da_ocr_tasks(status);
CREATE INDEX IF NOT EXISTS idx_da_ocr_files_task ON da_ocr_files(task_id);
""")
conn.commit()
conn.close()
def _safe_name(name):
return (name or "file").replace("/", "_").replace("\\", "_").replace("..", "_")
def create_task(name, engine, files):
"""files: [(filename, bytes), ...];创建后立即返回任务ID,后台解析。"""
if engine not in ENGINES:
engine = "general"
conn = _conn()
now = _now()
cur = conn.execute("""INSERT INTO da_ocr_tasks(name,engine,status,progress,file_count,done_count,created_at)
VALUES (?,?,?,?,?,?,?)""",
((name or "OCR识别任务").strip(), engine, "待执行", 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
ext = Path(filename).suffix.lower()
c = conn.execute("""INSERT INTO da_ocr_files(task_id,filename,ext,size,stored_path,status,created_at)
VALUES (?,?,?,?,?,?,?)""",
(task_id, filename, ext, len(raw), str(path) if path else "", "待解析", now))
ids.append(c.lastrowid)
conn.commit()
conn.close()
_log("OCR任务创建", f"{name}({len(files)} 个文件,引擎 {ENGINES.get(engine, engine)})")
thread = threading.Thread(target=_run_task, args=(task_id, ids), daemon=True)
thread.start()
return task_id
def _run_task(task_id, file_ids):
import digital_audit_service as das
conn = _conn()
try:
task = conn.execute("SELECT * FROM da_ocr_tasks WHERE id=?", (task_id,)).fetchone()
engine = task["engine"] if task else "general"
conn.execute("UPDATE da_ocr_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_ocr_files WHERE id=?", (fid,)).fetchone()
if not row:
continue
conn.execute("UPDATE da_ocr_files SET status='识别中' WHERE id=?", (fid,))
conn.commit()
try:
raw = Path(row["stored_path"]).read_bytes() if row["stored_path"] else b""
result = das.parse_document(row["filename"], raw, engine=engine)
conn.execute("""UPDATE da_ocr_files SET mode=?,status='已完成',pages=?,char_count=?,
preview=?,content=?,error='' WHERE id=?""",
(result.get("mode", ""), result.get("pages", 0),
result.get("char_count", 0), result.get("preview", "")[:300],
result.get("content", ""), fid))
except Exception as e:
conn.execute("UPDATE da_ocr_files SET status='失败', error=? WHERE id=?", (str(e), fid))
done += 1
progress = int(done * 100 / total) if total else 100
conn.execute("UPDATE da_ocr_tasks SET progress=?, done_count=? WHERE id=?",
(progress, done, task_id))
conn.commit()
conn.execute("UPDATE da_ocr_tasks SET status='已完成', progress=100, finished_at=? WHERE id=?",
(_now(), task_id))
conn.commit()
_log("OCR任务完成", f"任务 {task_id}:{done}/{total} 个文件")
except Exception as e:
try:
conn.execute("UPDATE da_ocr_tasks SET status='执行失败' WHERE id=?", (task_id,))
conn.commit()
except Exception:
pass
_log("OCR任务失败", f"任务 {task_id}:{e}")
finally:
conn.close()
def engine_label(engine):
return ENGINES.get(engine, engine)
def list_tasks():
conn = _conn()
try:
rows = [dict(r) for r in conn.execute(
"SELECT * FROM da_ocr_tasks ORDER BY id DESC LIMIT 100").fetchall()]
for r in rows:
r["engine_label"] = engine_label(r.get("engine"))
return rows
finally:
conn.close()
def get_task(task_id):
conn = _conn()
try:
task = conn.execute("SELECT * FROM da_ocr_tasks WHERE id=?", (task_id,)).fetchone()
if not task:
return None
d = dict(task)
d["engine_label"] = engine_label(d.get("engine"))
d["files"] = [dict(r) for r in conn.execute(
"SELECT id,task_id,filename,ext,size,mode,status,pages,char_count,preview,error "
"FROM da_ocr_files WHERE task_id=? ORDER BY id", (task_id,)).fetchall()]
return d
finally:
conn.close()
def get_file(file_id):
conn = _conn()
try:
row = conn.execute("SELECT * FROM da_ocr_files WHERE id=?", (file_id,)).fetchone()
return dict(row) if row else None
finally:
conn.close()
def delete_task(task_id):
conn = _conn()
try:
rows = conn.execute("SELECT id FROM da_ocr_files WHERE task_id=?", (task_id,)).fetchall()
conn.execute("DELETE FROM da_ocr_files WHERE task_id=?", (task_id,))
conn.execute("DELETE FROM da_ocr_tasks WHERE id=?", (task_id,))
conn.commit()
folder = FILES_DIR / str(task_id)
if folder.exists():
shutil.rmtree(folder, ignore_errors=True)
_log("OCR任务删除", f"任务 {task_id}")
finally:
conn.close()
def render_preview(file_id):
"""返回预览图 bytes:图片直接返回;PDF 渲染第一页;其他返回 None。"""
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"] != ".png" else "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
def export_task(task_id, fmt="txt"):
"""生成 TXT 或 Word 导出文件,返回路径。"""
task = get_task(task_id)
if not task:
return None
folder = FILES_DIR / str(task_id)
folder.mkdir(parents=True, exist_ok=True)
conn = _conn()
try:
files = [dict(r) for r in conn.execute(
"SELECT filename,mode,char_count,content,status,error FROM da_ocr_files WHERE task_id=? ORDER BY id",
(task_id,)).fetchall()]
finally:
conn.close()
if fmt == "docx":
from docx import Document
doc = Document()
doc.add_heading(f"OCR 识别结果:{task['name']}", level=1)
doc.add_paragraph(f"识别引擎:{task['engine_label']} 文件数:{task['file_count']} 导出时间:{_now()}")
for f in files:
doc.add_heading(f["filename"], level=2)
doc.add_paragraph(f"方式:{f.get('mode') or '-'} 字数:{f.get('char_count') or 0}")
if f.get("error"):
doc.add_paragraph(f"识别失败:{f['error']}")
else:
doc.add_paragraph(f.get("content") or "")
out = folder / f"OCR识别结果_{task_id}.docx"
doc.save(str(out))
else:
out = folder / f"OCR识别结果_{task_id}.txt"
lines = [f"OCR 识别结果:{task['name']}",
f"识别引擎:{task['engine_label']} 文件数:{task['file_count']} 导出时间:{_now()}", ""]
for f in files:
lines.append("=" * 40)
lines.append(f"文件:{f['filename']}({f.get('mode') or '-'},{f.get('char_count') or 0} 字)")
if f.get("error"):
lines.append(f"识别失败:{f['error']}")
else:
lines.append(f.get("content") or "")
lines.append("")
out.write_text("\n".join(lines), encoding="utf-8")
return out
init_db()