# -*- coding: utf-8 -*- """知识库管理服务 - 空间/文档的增删改查、文件解析、链接采集""" import sqlite3 import os import uuid import re import urllib.request import urllib.error from pathlib import Path from typing import Optional WORKSPACE_DIR = Path(__file__).parent.parent AUDIT_DB = WORKSPACE_DIR / "审计项目管理平台" / "audit_data.db" # 上传文件临时目录 UPLOAD_TEMP = Path(__file__).parent / "uploads" UPLOAD_TEMP.mkdir(exist_ok=True) def _get_conn(): conn = sqlite3.connect(str(AUDIT_DB), timeout=10) conn.row_factory = sqlite3.Row conn.execute("PRAGMA journal_mode = WAL") return conn def _ensure_tables(): """确保采集库表存在""" conn = _get_conn() conn.execute(""" CREATE TABLE IF NOT EXISTS collection_items ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT DEFAULT '', title TEXT NOT NULL DEFAULT '', content TEXT DEFAULT '', source_name TEXT DEFAULT '', source_type TEXT DEFAULT 'web', category TEXT DEFAULT '', status TEXT DEFAULT 'collected', doc_id INTEGER DEFAULT NULL, created_at TEXT DEFAULT (datetime('now', 'localtime')), updated_at TEXT DEFAULT (datetime('now', 'localtime')) ) """) conn.commit() conn.close() _ensure_tables() # ==================== 知识空间管理 ==================== def list_spaces(sort: str = "id") -> list[dict]: """列出所有知识空间(含文档数量),支持排序""" order_map = { "name": "name COLLATE NOCASE ASC", "name_desc": "name COLLATE NOCASE DESC", "created": "created_at DESC", "created_asc": "created_at ASC", "doc_count": "doc_count DESC", } order_by = order_map.get(sort, "id") conn = _get_conn() if sort in ("doc_count",): spaces = conn.execute("SELECT * FROM knowledge_spaces ORDER BY id").fetchall() result = [] for r in spaces: cnt = conn.execute( "SELECT COUNT(*) FROM knowledge_docs WHERE space_id = ?", (r["space_id"],) ).fetchone()[0] result.append({ "space_id": r["space_id"], "name": r["name"], "description": r["description"], "space_type": r["space_type"], "visibility": r["visibility"], "doc_count": cnt, "created_at": r["created_at"], }) result.sort(key=lambda x: x["doc_count"], reverse=True) conn.close() return result spaces = conn.execute(f"SELECT * FROM knowledge_spaces ORDER BY {order_by}").fetchall() result = [] for r in spaces: cnt = conn.execute( "SELECT COUNT(*) FROM knowledge_docs WHERE space_id = ?", (r["space_id"],) ).fetchone()[0] result.append({ "space_id": r["space_id"], "name": r["name"], "description": r["description"], "space_type": r["space_type"], "visibility": r["visibility"], "doc_count": cnt, "created_at": r["created_at"], }) conn.close() return result def create_space(name: str, description: str = "") -> dict: """新建知识空间""" space_id = f"local_{uuid.uuid4().hex[:12]}" conn = _get_conn() conn.execute( "INSERT INTO knowledge_spaces (space_id, name, description, space_type, visibility) VALUES (?, ?, ?, ?, ?)", (space_id, name, description, "wiki", "private"), ) conn.commit() conn.close() return {"space_id": space_id, "name": name} def rename_space(space_id: str, name: str) -> dict: """重命名知识空间""" conn = _get_conn() conn.execute("UPDATE knowledge_spaces SET name = ? WHERE space_id = ?", (name, space_id)) conn.execute("UPDATE knowledge_docs SET space_name = ? WHERE space_id = ?", (name, space_id)) conn.commit() conn.close() return {"space_id": space_id, "name": name} def delete_space(space_id: str) -> dict: """删除知识空间及其所有文档""" conn = _get_conn() conn.execute("DELETE FROM knowledge_docs WHERE space_id = ?", (space_id,)) conn.execute("DELETE FROM knowledge_spaces WHERE space_id = ?", (space_id,)) conn.commit() conn.close() return {"deleted": True} # ==================== 知识文档管理 ==================== def list_docs(space_id: str, sort: str = "id", keyword: str = "") -> list[dict]: """列出知识空间下的所有文档,支持排序和标题模糊搜索""" order_map = { "title": "title COLLATE NOCASE ASC", "title_desc": "title COLLATE NOCASE DESC", "created": "created_at DESC", "created_asc": "created_at ASC", } order_by = order_map.get(sort, "id") conn = _get_conn() if keyword: rows = conn.execute( f"SELECT * FROM knowledge_docs WHERE space_id = ? AND title LIKE ? ORDER BY {order_by}", (space_id, f"%{keyword}%") ).fetchall() else: rows = conn.execute( f"SELECT * FROM knowledge_docs WHERE space_id = ? ORDER BY {order_by}", (space_id,) ).fetchall() conn.close() return [{ "id": r["id"], "node_token": r["node_token"], "space_id": r["space_id"], "title": r["title"], "content": r["content"], "obj_type": r["obj_type"], "created_at": r["created_at"], } for r in rows] def get_doc(node_token: str) -> Optional[dict]: """获取单篇文档""" conn = _get_conn() r = conn.execute("SELECT * FROM knowledge_docs WHERE node_token = ?", (node_token,)).fetchone() conn.close() if not r: return None return { "id": r["id"], "node_token": r["node_token"], "space_id": r["space_id"], "space_name": r["space_name"], "title": r["title"], "content": r["content"], "obj_type": r["obj_type"], "created_at": r["created_at"], } def move_doc(node_token: str, target_space_id: str) -> dict: """将文档移动到目标知识空间""" conn = _get_conn() doc = conn.execute("SELECT * FROM knowledge_docs WHERE node_token = ?", (node_token,)).fetchone() if not doc: conn.close() return {"error": "文档不存在"} space = conn.execute("SELECT name FROM knowledge_spaces WHERE space_id = ?", (target_space_id,)).fetchone() if not space: conn.close() return {"error": "目标空间不存在"} conn.execute( "UPDATE knowledge_docs SET space_id = ?, space_name = ? WHERE node_token = ?", (target_space_id, space["name"], node_token), ) conn.commit() conn.close() return {"node_token": node_token, "space_id": target_space_id, "space_name": space["name"]} def create_doc(space_id: str, title: str, content: str) -> dict: """新建文档""" conn = _get_conn() space = conn.execute("SELECT name FROM knowledge_spaces WHERE space_id = ?", (space_id,)).fetchone() space_name = space["name"] if space else "" node_token = f"doc_{uuid.uuid4().hex[:12]}" conn.execute( "INSERT INTO knowledge_docs (space_id, space_name, node_token, title, content, obj_type, parent_node_token, has_child) " "VALUES (?, ?, ?, ?, ?, 'docx', '', 0)", (space_id, space_name, node_token, title, content), ) conn.commit() conn.close() return {"node_token": node_token, "title": title} def update_doc(node_token: str, title: str = None, content: str = None) -> dict: """更新文档""" fields = [] params = [] if title is not None: fields.append("title = ?") params.append(title) if content is not None: fields.append("content = ?") params.append(content) if not fields: return {"node_token": node_token} params.append(node_token) conn = _get_conn() conn.execute(f"UPDATE knowledge_docs SET {', '.join(fields)} WHERE node_token = ?", params) conn.commit() conn.close() return {"node_token": node_token} def delete_doc(node_token: str) -> dict: """删除文档""" conn = _get_conn() conn.execute("DELETE FROM knowledge_docs WHERE node_token = ?", (node_token,)) conn.commit() conn.close() return {"deleted": True} def split_content(content: str, max_length: int = 8000) -> list[dict]: """按标题1拆分长文本,超长段落再按长度兜底。 返回 [{"title": str, "content": str}, ...] """ if len(content) <= max_length: return [{"title": "", "content": content}] sections = _split_by_heading(content) if len(sections) <= 1: return [{"title": "", "content": c} for c in _split_by_length(content, max_length)] result = [] for sec in sections: if len(sec["content"]) <= max_length: result.append(sec) else: sub_chunks = _split_by_length(sec["content"], max_length) for i, sub in enumerate(sub_chunks): result.append({ "title": sec["title"] if i == 0 else f"{sec['title']}(续{i + 1})", "content": sub, }) return result def _split_by_heading(content: str) -> list[dict]: """按 # 标题1 行拆分,返回 [{"title": str, "content": str}, ...]""" lines = content.split('\n') sections = [] current_title = "" current_lines = [] for line in lines: if re.match(r'^#\s+', line): if current_lines or current_title: sections.append({ "title": current_title, "content": '\n'.join(current_lines).strip(), }) current_title = re.sub(r'^#\s+', '', line).strip() current_lines = [line] else: current_lines.append(line) if current_lines or current_title: sections.append({ "title": current_title, "content": '\n'.join(current_lines).strip(), }) return [s for s in sections if s["content"]] def _split_by_length(text: str, max_length: int = 8000) -> list[str]: """按长度拆分文本,优先在句末标点处断句""" chunks = [] start = 0 while start < len(text): end = min(start + max_length, len(text)) if end == len(text): chunks.append(text[start:end]) break best = -1 for punct in ('。', '!', '?', ';', '.', '!', '?', ';'): pos = text.rfind(punct, start, end) if pos != -1: best = max(best, pos + 1) if best == -1: for sep in ('\n', ' ', ',', '、'): pos = text.rfind(sep, start, end) if pos != -1: best = max(best, pos + 1) cut = best if best != -1 else end chunks.append(text[start:cut]) start = cut return chunks def create_doc_auto_split(space_id: str, title: str, content: str, max_length: int = 8000) -> dict: """新建文档,内容过长时按标题1自动拆分为多篇""" sections = split_content(content, max_length) if len(sections) <= 1: return create_doc(space_id, title, content) conn = _get_conn() space = conn.execute("SELECT name FROM knowledge_spaces WHERE space_id = ?", (space_id,)).fetchone() space_name = space["name"] if space else "" created = [] for i, sec in enumerate(sections): node_token = f"doc_{uuid.uuid4().hex[:12]}" if sec["title"]: doc_title = sec["title"] elif i == 0: doc_title = title else: doc_title = f"{title}({i + 1})" conn.execute( "INSERT INTO knowledge_docs (space_id, space_name, node_token, title, content, obj_type, parent_node_token, has_child) " "VALUES (?, ?, ?, ?, ?, 'docx', '', 0)", (space_id, space_name, node_token, doc_title, sec["content"]), ) created.append({"node_token": node_token, "title": doc_title}) conn.commit() conn.close() return {"node_token": created[0]["node_token"], "title": title, "split_count": len(sections), "docs": created} # ==================== 文件解析 ==================== LLM_API_KEY = os.getenv("LLM_API_KEY", "sk-ws-H.EIIIYIL.yjjO.MEQCIH0zxpg4LAQmoSonFkoyOG65fkQZmCqCOTw2qvSb_2LBAiAQM51Jp3TVlJnCXwz6S7ekVlnpLeOAXa_q_NDv-DiN_g") LLM_BASE_URL = os.getenv("LLM_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1") def _recognize_image(image_bytes: bytes) -> str: """用通义千问视觉模型识别图片中的文字和表格""" import base64 from openai import OpenAI try: client = OpenAI(api_key=LLM_API_KEY, base_url=LLM_BASE_URL) b64 = base64.b64encode(image_bytes).decode("utf-8") response = client.chat.completions.create( model="qwen-vl-plus", messages=[ { "role": "user", "content": [ { "type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}, }, { "type": "text", "text": "请识别图片中的所有文字和表格内容。要求:1.纯文字照原文逐字输出;2.表格用Markdown表格格式还原;3.不要添加任何额外说明,只输出识别到的内容。如果图片是装饰性图片或无文字,输出空字符串。", }, ], } ], temperature=0.1, ) result = response.choices[0].message.content.strip() return result except Exception as e: return f"[图片识别失败: {e}]" def _extract_docx_images(file_path: str) -> list[dict]: """从 Word 文档提取所有内嵌图片,返回 [{data: bytes, order: int}]""" import zipfile images = [] try: with zipfile.ZipFile(file_path) as zf: for name in zf.namelist(): if name.startswith("word/media/"): data = zf.read(name) if data: images.append({"data": data, "order": len(images)}) except Exception: pass return images def _extract_pdf_images(file_path: str) -> list[dict]: """从 PDF 提取页面图片(整页渲染),返回 [{data: bytes, order: int}]""" import pdf_tools images = [] try: for png in pdf_tools.render_pages_png(file_path, scale=1.5): images.append({"data": png, "order": len(images)}) except Exception: pass return images def parse_docx(file_path: str) -> str: """从 Word 文档提取正文,标题1以 # 前缀标记,图片用通义千问识别""" from docx import Document from docx.opc.constants import RELATIONSHIP_TYPE as RT doc = Document(file_path) paragraphs = [] # 提取内嵌图片的关联映射 image_rels = {} for rel in doc.part.rels.values(): if "image" in rel.reltype: image_rels[rel.rId] = rel for p in doc.paragraphs: text = p.text.strip() # 检查段落中是否包含图片 has_image = False for run in p.runs: if run._element.findall(".//{http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing}inline") or \ run._element.findall(".//{http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing}anchor"): has_image = True break if has_image: # 提取图片并识别 blips = p._element.findall(".//{http://schemas.openxmlformats.org/drawingml/2006/main}blip") for blip in blips: embed = blip.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed") if embed and embed in image_rels: try: image_data = image_rels[embed].target_part.blob result = _recognize_image(image_data) if result: paragraphs.append(result) except Exception: pass elif text: style_name = p.style.name if p.style else "" if style_name in ("Heading 1", "标题 1", "标题1"): paragraphs.append(f"# {text}") else: paragraphs.append(text) return "\n".join(paragraphs) def parse_pdf(file_path: str) -> tuple[str, bool]: """从 PDF 提取正文;无文字层时渲染页面识别,返回 (内容, 是否扫描件)""" import pdf_tools text = pdf_tools.extract_text(file_path) if len(text.strip()) >= 50: return (text, False) # 扫描件:渲染页面交给图像识别(最多 5 页,避免过慢) text_parts = [] try: for png in pdf_tools.render_pages_png(file_path, scale=1.8, max_pages=5): result = _recognize_image(png) if result: text_parts.append(result) except Exception: pass if not text_parts: return ("", True) return ("\n".join(text_parts), False) # ==================== 链接采集 ==================== def extract_from_url(url: str) -> dict: """从URL提取正文和来源信息""" import trafilatura from urllib.parse import quote # 处理URL中的非ASCII字符 encoded_url = quote(url, safe=":/?&=%#") req = urllib.request.Request( encoded_url, headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }, ) with urllib.request.urlopen(req, timeout=15) as resp: html = resp.read().decode("utf-8", errors="replace") extracted = trafilatura.extract( html, include_comments=False, include_tables=True, favor_precision=True ) metadata = trafilatura.extract_metadata(html) title = "" if metadata and metadata.title: title = metadata.title source_name = "" source_type = "web" if metadata and metadata.sitename: source_name = metadata.sitename elif metadata and metadata.hostname: source_name = metadata.hostname if "mp.weixin.qq.com" in url: source_type = "wechat" source_name = "" for pattern in [ r'nick_name\s*:\s*["\']([^"\']+)["\']', r'data-nickname\s*=\s*["\']([^"\']+)["\']', r'nickname\s*:\s*["\']([^"\']+)["\']', ]: m = re.search(pattern, html) if m and m.group(1).strip(): source_name = m.group(1).strip() break if not source_name: source_name = "微信公众号" content = extracted or "" return { "url": url, "title": title or "无标题", "content": content, "source_name": source_name or "未知来源", "source_type": source_type, } def save_to_collection( url: str, title: str, content: str, source_name: str, source_type: str, category: str = "" ) -> dict: """保存到采集库,未指定分类时按来源名自动归类""" if not category and source_name: category = source_name conn = _get_conn() cur = conn.execute( "INSERT INTO collection_items (url, title, content, source_name, source_type, category) " "VALUES (?, ?, ?, ?, ?, ?)", (url, title, content, source_name, source_type, category), ) item_id = cur.lastrowid conn.commit() conn.close() return {"id": item_id} def list_collection(category: str = "", keyword: str = "") -> list[dict]: """列出采集库内容""" conn = _get_conn() sql = "SELECT * FROM collection_items" params = [] conditions = [] if category: conditions.append("category = ?") params.append(category) if keyword: conditions.append("(title LIKE ? OR content LIKE ? OR source_name LIKE ?)") kw = f"%{keyword}%" params.extend([kw, kw, kw]) if conditions: sql += " WHERE " + " AND ".join(conditions) sql += " ORDER BY id DESC" rows = conn.execute(sql, params).fetchall() conn.close() return [{ "id": r["id"], "url": r["url"], "title": r["title"], "content": r["content"], "source_name": r["source_name"], "source_type": r["source_type"], "category": r["category"], "status": r["status"], "doc_id": r["doc_id"], "created_at": r["created_at"], } for r in rows] def list_collection_categories() -> list[str]: """列出采集库中所有分类""" conn = _get_conn() rows = conn.execute( "SELECT DISTINCT category FROM collection_items WHERE category != '' ORDER BY category" ).fetchall() conn.close() return [r[0] for r in rows] def get_collection_item(item_id: int) -> Optional[dict]: """获取单条采集条目""" conn = _get_conn() r = conn.execute("SELECT * FROM collection_items WHERE id = ?", (item_id,)).fetchone() conn.close() if not r: return None return { "id": r["id"], "url": r["url"], "title": r["title"], "content": r["content"], "source_name": r["source_name"], "source_type": r["source_type"], "category": r["category"], "status": r["status"], "doc_id": r["doc_id"], "created_at": r["created_at"], } def update_collection_item(item_id: int, title: str = None, content: str = None, category: str = None) -> dict: """更新采集库条目""" fields = [] params = [] if title is not None: fields.append("title = ?") params.append(title) if content is not None: fields.append("content = ?") params.append(content) if category is not None: fields.append("category = ?") params.append(category) if not fields: return {"id": item_id} fields.append("updated_at = datetime('now', 'localtime')") params.append(item_id) conn = _get_conn() conn.execute(f"UPDATE collection_items SET {', '.join(fields)} WHERE id = ?", params) conn.commit() conn.close() return {"id": item_id} def delete_collection_item(item_id: int) -> dict: """删除采集库条目""" conn = _get_conn() conn.execute("DELETE FROM collection_items WHERE id = ?", (item_id,)) conn.commit() conn.close() return {"deleted": True} def move_to_knowledge(item_id: int, space_id: str) -> dict: """将采集库条目转入知识库""" conn = _get_conn() item = conn.execute("SELECT * FROM collection_items WHERE id = ?", (item_id,)).fetchone() if not item: conn.close() return {"error": "条目不存在"} space = conn.execute("SELECT name FROM knowledge_spaces WHERE space_id = ?", (space_id,)).fetchone() space_name = space["name"] if space else "" node_token = f"doc_{uuid.uuid4().hex[:12]}" conn.execute( "INSERT INTO knowledge_docs (space_id, space_name, node_token, title, content, obj_type, parent_node_token, has_child) " "VALUES (?, ?, ?, ?, ?, 'docx', '', 0)", (space_id, space_name, node_token, item["title"], item["content"]), ) doc_id = conn.execute("SELECT id FROM knowledge_docs WHERE node_token = ?", (node_token,)).fetchone()[0] conn.execute( "UPDATE collection_items SET status = 'moved', doc_id = ? WHERE id = ?", (doc_id, item_id), ) conn.commit() conn.close() return {"node_token": node_token, "doc_id": doc_id} # ==================== 下载合并 ==================== def export_collection_as_docx(source_name: str) -> str: """将采集库中指定来源的所有文章合并为Word文件,返回文件路径""" from docx import Document conn = _get_conn() if source_name: items = conn.execute( "SELECT title, content, source_name, url, created_at FROM collection_items WHERE source_name = ? ORDER BY id", (source_name,) ).fetchall() title_prefix = source_name else: items = conn.execute( "SELECT title, content, source_name, url, created_at FROM collection_items ORDER BY id" ).fetchall() title_prefix = "全部采集文章" conn.close() if not items: return "" doc = Document() doc.add_heading(title_prefix, level=0) for item in items: doc.add_heading(item["title"] or "无标题", level=1) if item["url"]: p = doc.add_paragraph() p.add_run(f"来源链接:{item['url']}").italic = True content = item["content"] or "" for line in content.split("\n"): if line.strip(): doc.add_paragraph(line) doc.add_page_break() file_path = str(UPLOAD_TEMP / f"{title_prefix}_采集文章.docx") doc.save(file_path) return file_path def export_space_as_markdown(space_id: str) -> str: """将知识空间所有文档合并为Markdown""" conn = _get_conn() space = conn.execute("SELECT name FROM knowledge_spaces WHERE space_id = ?", (space_id,)).fetchone() if not space: conn.close() return "" space_name = space["name"] docs = conn.execute( "SELECT title, content FROM knowledge_docs WHERE space_id = ? ORDER BY id", (space_id,) ).fetchall() conn.close() md = f"# {space_name}\n\n" for doc in docs: md += f"## {doc['title']}\n\n{doc['content'] or ''}\n\n---\n\n" return md def export_space_as_docx(space_id: str) -> str: """将知识空间所有文档合并为Word文件,返回文件路径""" from docx import Document conn = _get_conn() space = conn.execute("SELECT name FROM knowledge_spaces WHERE space_id = ?", (space_id,)).fetchone() if not space: conn.close() return "" space_name = space["name"] docs = conn.execute( "SELECT title, content FROM knowledge_docs WHERE space_id = ? ORDER BY id", (space_id,) ).fetchall() conn.close() doc = Document() doc.add_heading(space_name, level=0) for d in docs: doc.add_heading(d["title"], level=1) content = d["content"] or "" for line in content.split("\n"): if line.strip(): doc.add_paragraph(line) doc.add_page_break() file_path = str(UPLOAD_TEMP / f"{space_name}_知识库.docx") doc.save(file_path) return file_path