diff --git a/Jenkinsfile b/Jenkinsfile index d4fb0daa..6535fa18 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -27,18 +27,18 @@ pipeline { environment { // 环境服务器地址 / Environment hosts DEV_DEPLOY_HOST = '8.152.207.171' - TEST_DEPLOY_HOST = 'YOUR_TEST_SERVER_IP' + TEST_DEPLOY_HOST = '192.168.100.192' PROD_DEPLOY_HOST = '192.168.100.230' // SSH 连接参数 / SSH connection settings DEV_SSH_USER = 'root' - TEST_SSH_USER = 'root' + TEST_SSH_USER = 'lisq' PROD_SSH_USER = 'inspur' SSH_PORT = '22' // 各环境统一部署目录 / Unified deploy root DEV_DEPLOY_ROOT = '/opt/hxops' - TEST_DEPLOY_ROOT = '/opt/hxops' + TEST_DEPLOY_ROOT = '/home/lisq/ai/platform/hxops' PROD_DEPLOY_ROOT = '/data/ai-platform/hxops/' } diff --git a/backend/Dockerfile b/backend/Dockerfile index 19d0bcff..60145d3c 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,17 +1,45 @@ -FROM python:3.12-slim-bookworm +ARG PYTHON_BASE_IMAGE=python:3.12-slim +FROM ${PYTHON_BASE_IMAGE} + +ARG APT_MIRROR=https://mirrors.aliyun.com +ARG PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple +ARG PIP_EXTRA_INDEX_URL WORKDIR /app -# Oracle Instant Client runtime dependencies for thick mode. -# `libaio1` is available on Debian bookworm, while newer variants may expose `libaio1t64`. -RUN apt-get update \ - && (apt-get install -y --no-install-recommends libaio1 libnsl2 \ - || apt-get install -y --no-install-recommends libaio1t64 libnsl2) \ +RUN set -eux; \ + if [ -f /etc/apt/sources.list.d/debian.sources ]; then \ + sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list.d/debian.sources; \ + sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list.d/debian.sources; \ + fi; \ + if [ -f /etc/apt/sources.list ]; then \ + sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list; \ + sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list; \ + fi; \ + apt-get update && apt-get install -y \ + libgl1 \ + libglib2.0-0 \ + libxcb1 \ + libx11-6 \ + libxext6 \ + libreoffice \ + fonts-noto-cjk \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies -COPY backend/requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt +COPY requirements.txt . +RUN set -eux; \ + PIP_ARGS="--no-cache-dir --retries 10 --timeout 60"; \ + if [ -n "${PIP_INDEX_URL:-}" ]; then \ + PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \ + fi; \ + if [ -n "${PIP_EXTRA_INDEX_URL:-}" ]; then \ + PIP_ARGS="$PIP_ARGS --extra-index-url ${PIP_EXTRA_INDEX_URL}"; \ + fi; \ + pip install $PIP_ARGS -r requirements.txt && \ + pip uninstall -y opencv-python && \ + pip install $PIP_ARGS opencv-python-headless && \ + python -c "import networkx, openpyxl" # Copy backend code and the Text2SQL schema required at runtime COPY backend/ . diff --git a/backend/Dockerfile_BASE_79990 b/backend/Dockerfile_BASE_79990 new file mode 100644 index 00000000..ce415800 --- /dev/null +++ b/backend/Dockerfile_BASE_79990 @@ -0,0 +1,17 @@ +FROM python:3.12-slim + +WORKDIR /app + +# Install Python dependencies +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy application code +COPY . . + +# Expose port 5000 +EXPOSE 5000 + +# Start Gunicorn +# Using the config file we created earlier +CMD ["gunicorn", "-c", "deploy/gunicorn_config.py", "run:app"] diff --git a/backend/Dockerfile_LOCAL_79990 b/backend/Dockerfile_LOCAL_79990 new file mode 100644 index 00000000..19d0bcff --- /dev/null +++ b/backend/Dockerfile_LOCAL_79990 @@ -0,0 +1,30 @@ +FROM python:3.12-slim-bookworm + +WORKDIR /app + +# Oracle Instant Client runtime dependencies for thick mode. +# `libaio1` is available on Debian bookworm, while newer variants may expose `libaio1t64`. +RUN apt-get update \ + && (apt-get install -y --no-install-recommends libaio1 libnsl2 \ + || apt-get install -y --no-install-recommends libaio1t64 libnsl2) \ + && rm -rf /var/lib/apt/lists/* + +# Install Python dependencies +COPY backend/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy backend code and the Text2SQL schema required at runtime +COPY backend/ . +RUN mkdir -p /app/docs +COPY docs/(表+字段).md /app/docs/(表+字段).md +ENV ORACLE_HOME=/app/oracle_client/instantclient_19_31 +ENV LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client:${LD_LIBRARY_PATH} + + +# Expose port 5000 +EXPOSE 5000 + +# Start Gunicorn +# Using the config file we created earlier +CMD ["gunicorn", "-c", "deploy/gunicorn_config.py", "run:app"] + diff --git a/backend/Dockerfile_REMOTE_79990 b/backend/Dockerfile_REMOTE_79990 new file mode 100644 index 00000000..7f5ee003 --- /dev/null +++ b/backend/Dockerfile_REMOTE_79990 @@ -0,0 +1,52 @@ +ARG PYTHON_BASE_IMAGE=python:3.12-slim +FROM ${PYTHON_BASE_IMAGE} + +ARG APT_MIRROR=https://mirrors.aliyun.com +ARG PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple +ARG PIP_EXTRA_INDEX_URL + +WORKDIR /app + +RUN set -eux; \ + if [ -f /etc/apt/sources.list.d/debian.sources ]; then \ + sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list.d/debian.sources; \ + sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list.d/debian.sources; \ + fi; \ + if [ -f /etc/apt/sources.list ]; then \ + sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list; \ + sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list; \ + fi; \ + apt-get update && apt-get install -y \ + libgl1 \ + libglib2.0-0 \ + libxcb1 \ + libx11-6 \ + libxext6 \ + libreoffice \ + fonts-noto-cjk \ + && rm -rf /var/lib/apt/lists/* + +# Install Python dependencies +COPY requirements.txt . +RUN set -eux; \ + PIP_ARGS="--no-cache-dir --retries 10 --timeout 60"; \ + if [ -n "${PIP_INDEX_URL:-}" ]; then \ + PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \ + fi; \ + if [ -n "${PIP_EXTRA_INDEX_URL:-}" ]; then \ + PIP_ARGS="$PIP_ARGS --extra-index-url ${PIP_EXTRA_INDEX_URL}"; \ + fi; \ + pip install $PIP_ARGS -r requirements.txt && \ + pip uninstall -y opencv-python && \ + pip install $PIP_ARGS opencv-python-headless && \ + python -c "import networkx, openpyxl" + +# Copy application code +COPY . . + +# Expose port 5000 +EXPOSE 5000 + +# Start Gunicorn +# Using the config file we created earlier +CMD ["gunicorn", "-c", "deploy/gunicorn_config.py", "run:app"] diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 29760b3d..d7563b37 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -49,6 +49,8 @@ def create_app(config_name='default'): from app.api.admin import admin_bp from app.api.agents import agents_bp from app.api.user import user_bp + from app.api.knowledge_base import knowledge_base_bp + from app.api.integration import integration_bp # 聊天相关接口 app.register_blueprint(chat_bp, url_prefix='/api/chat') @@ -58,6 +60,10 @@ def create_app(config_name='default'): app.register_blueprint(agents_bp, url_prefix='/api/agents') # 当前用户相关接口(首页、常用问题等) app.register_blueprint(user_bp, url_prefix='/api/user') + # 知识库/数据清洗模块接口 + app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb') + # 知识库外部集成接口(供聊天/外部系统按 Dify 映射反查源文件) + app.register_blueprint(integration_bp, url_prefix='/api/integration') # Eagerly load persisted runtime settings so the very first request after # a worker boot already sees the admin-saved configuration (otherwise the diff --git a/backend/app/api/agents.py b/backend/app/api/agents.py index 75c9f905..3805244e 100644 --- a/backend/app/api/agents.py +++ b/backend/app/api/agents.py @@ -4,14 +4,25 @@ backend/app/api/agents.py 引用文件:flask, models, decorators 逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合 """ -from flask import Blueprint, jsonify, g -from app.models import Agent, User +from flask import Blueprint, jsonify + +from app import db from app.decorators import _get_current_user # 内部工具函数 +from app.models import Agent, User # 定义 Blueprint,将在应用工厂中注册为 /api/agents agents_bp = Blueprint('agents', __name__) +def _serialize_agent_row(row) -> dict: + return { + 'id': row.id, + 'name': row.name, + 'description': row.description, + 'icon_url': row.icon_url, + } + + @agents_bp.route('', methods=['GET']) def list_user_agents(): """ @@ -23,12 +34,27 @@ def list_user_agents(): # 管理员:返回所有激活的 Agent if user.role == 'admin': - agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all() + agent_rows = ( + db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url) + .filter(Agent.is_active.is_(True)) + .order_by(Agent.id.asc()) + .all() + ) else: # 普通用户:仅返回多对多关系中已授权的 Agent - agents = [a for a in user.agents if a.is_active] + agent_rows = [ + type('AgentRow', (), { + 'id': a.id, + 'name': a.name, + 'description': a.description, + 'icon_url': a.icon_url, + })() + for a in user.agents + if a.is_active + ] # 序列化为前端所需字段 + return jsonify([_serialize_agent_row(row) for row in agent_rows]) @agents_bp.route('/public', methods=['GET']) def list_public_agents(): @@ -37,17 +63,12 @@ def list_public_agents(): 用途:登录页面展示 """ # 返回所有激活的 Agent,包含基本信息 - agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all() - - data = [ - { - 'id': a.id, - 'name': a.name, - 'description': a.description, - 'icon_url': a.icon_url, - } - for a in agents - ] - return jsonify(data) + agent_rows = ( + db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url) + .filter(Agent.is_active.is_(True)) + .order_by(Agent.id.asc()) + .all() + ) + return jsonify([_serialize_agent_row(row) for row in agent_rows]) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 8e9fd1c9..2c1ac356 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -43,7 +43,7 @@ def _is_allowed_preview_url(target_url: str) -> bool: return False # 显式放行配置中的集成服务主机。 - integration_base = (current_app.config.get("INTEGRATION_API_BASE") or "").strip() + integration_base = (IntegrationApiService.get_base_url() or "").strip() if integration_base: integration_host = (urlparse(integration_base).hostname or "").strip().lower() if integration_host and host == integration_host: @@ -76,8 +76,8 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024 from urllib.parse import parse_qs headers = {} - base_url = current_app.config.get('INTEGRATION_API_BASE', '') - api_key = current_app.config.get('INTEGRATION_API_KEY', '') + base_url = IntegrationApiService.get_base_url() + api_key = IntegrationApiService.get_api_key() def _resolve_latest_integration_url(raw_url: str): dataset_id = '' @@ -280,6 +280,58 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes: raise Exception("PDF output not found after conversion") +def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes: + """ + 使用 LibreOffice 将老式 `.xls` 转为 `.xlsx`,供在线预览解析。 + """ + normalized_ext = (ext or '').strip().lower() + if normalized_ext != 'xls': + return content + + with tempfile.TemporaryDirectory() as temp_dir: + input_path = os.path.join(temp_dir, "input.xls") + output_path = os.path.join(temp_dir, "input.xlsx") + with open(input_path, 'wb') as f: + f.write(content) + + commands = [ + 'soffice', + 'libreoffice', + r'C:\Program Files\LibreOffice\program\soffice.exe', + r'C:\Program Files (x86)\LibreOffice\program\soffice.exe' + ] + + errors = [] + for cmd in commands: + try: + process = subprocess.run( + [cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=60 + ) + except (FileNotFoundError, subprocess.TimeoutExpired) as e: + errors.append(f"{cmd}: {e}") + continue + + if process.returncode == 0 and os.path.exists(output_path): + with open(output_path, 'rb') as f: + return f.read() + + stderr = process.stderr.decode('utf-8', errors='ignore').strip() + errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}") + + joined = "; ".join(errors) if errors else "no converter attempted" + raise RuntimeError(f"failed to convert xls to xlsx: {joined}") + + +def _load_excel_workbook(content: bytes, ext: str): + normalized_ext = (ext or '').strip().lower() + if normalized_ext == 'xls': + content = _convert_excel_to_xlsx(content, normalized_ext) + return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True) + + @chat_bp.route('/sessions', methods=['GET']) @require_agent_permission def get_chat_sessions(): @@ -578,8 +630,8 @@ def preview_excel(): """ 内网 Excel 预览接口(简版可上线)。 说明: - - 当前仅支持 xlsx; - - xls 返回 415,由前端走下载兜底。 + - xlsx 直接解析; + - xls 先转为 xlsx 后再解析。 """ file_url = (request.args.get('url') or '').strip() if not file_url: @@ -602,13 +654,13 @@ def preview_excel(): limit = 100 limit = max(1, min(limit, 300)) - content, _, err = _fetch_preview_source_bytes(file_url) + content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024) if err: msg, code = err return jsonify({'error': msg}), code try: - wb = load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True) + wb = _load_excel_workbook(content, ext) except Exception as e: current_app.logger.warning("[excel-preview] parse workbook failed: %s", e) return jsonify({'error': 'failed to parse excel file'}), 422 @@ -673,7 +725,8 @@ def preview_text(): if ext and ext not in allowed: return jsonify({'error': f'unsupported text extension: {ext}'}), 415 - content, content_type, err = _fetch_preview_source_bytes(file_url) + max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024 + content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size) if err: msg, code = err return jsonify({'error': msg}), code diff --git a/backend/app/api/chat.py.orig b/backend/app/api/chat.py.orig new file mode 100644 index 00000000..0de28989 --- /dev/null +++ b/backend/app/api/chat.py.orig @@ -0,0 +1,816 @@ + +""" +backend/app/api/chat.py +文件用途:定义聊天相关 API 路由 +引用文件:flask, services.dify, decorators, models +逻辑关系:作为前端与 Dify 之间的 BFF 层,负责转发请求并流式返回结果 +""" +import io +import ipaddress +import tempfile +import os +import subprocess +from urllib.parse import urlparse + +import requests +from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app +from sqlalchemy import func, desc +from openpyxl import load_workbook +from app.services.dify import DifyService +from app.services.integration_api import IntegrationApiService +from app.decorators import require_agent_permission +from app.models import Agent, ChatLog, Feedback +from app import db + +# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat +chat_bp = Blueprint('chat', __name__) + + +def _is_allowed_preview_url(target_url: str) -> bool: + """ + 预览代理 URL 白名单校验。 + 仅允许: + 1) 配置中的集成服务主机; + 2) 本机地址; + 3) 私网 IP 或常见内网域名(.local/.lan)。 + """ + try: + parsed = urlparse(target_url) + if parsed.scheme not in ("http", "https"): + return False + host = (parsed.hostname or "").strip().lower() + if not host: + return False + + # 显式放行配置中的集成服务主机。 + integration_base = (IntegrationApiService.get_base_url() or "").strip() + if integration_base: + integration_host = (urlparse(integration_base).hostname or "").strip().lower() + if integration_host and host == integration_host: + return True + + if host in ("localhost", "127.0.0.1", "::1"): + return True + + try: + ip = ipaddress.ip_address(host) + return ip.is_private or ip.is_loopback + except ValueError: + # 非 IP 主机:仅放行内网风格本地域名。 + return host.endswith(".local") or host.endswith(".lan") + except Exception: + return False + + +def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024 * 1024): + """ + 从上游文件 URL 拉取二进制内容(供预览接口复用)。 + 如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。 + 返回: (content_bytes, content_type, error_tuple) + 其中 error_tuple = (message, status_code);成功时为 None。 + """ + import base64 + import json + import time + import sqlalchemy as sa + from urllib.parse import parse_qs + + headers = {} + base_url = IntegrationApiService.get_base_url() + api_key = IntegrationApiService.get_api_key() + + def _resolve_latest_integration_url(raw_url: str): + dataset_id = '' + remote_document_id = '' + try: + parsed = urlparse(raw_url) + qs = parse_qs(parsed.query) + token = (qs.get('token') or [''])[0] + if token: + parts = token.split('.') + if len(parts) >= 2: + payload_b64 = parts[1] + payload_b64 += '=' * (-len(payload_b64) % 4) + payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8')) + dataset_id = str(payload_data.get('dataset_id') or '').strip() + remote_document_id = str(payload_data.get('remote_document_id') or '').strip() + except Exception: + pass + + if not dataset_id or not remote_document_id: + try: + stmt = sa.text("CAST(retriever_resources AS TEXT) LIKE :url") + log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first() + if log and log.retriever_resources: + for r in log.retriever_resources: + source_url = str(r.get('source_download_url') or '') + if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]): + dataset_id = dataset_id or str(r.get('dataset_id') or r.get('metadata', {}).get('dataset_id') or '').strip() + remote_document_id = remote_document_id or str( + r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or '' + ).strip() + if dataset_id and remote_document_id: + break + except Exception as e: + current_app.logger.warning("[file-preview] failed to find IDs in ChatLog: %s", e) + + if dataset_id and remote_document_id: + new_info = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id) + if new_info and new_info.get('source_download_url'): + current_app.logger.info("[file-preview] refreshed integration url for dataset=%s doc=%s", dataset_id, remote_document_id) + return new_info['source_download_url'] + return raw_url + + def _build_headers(raw_url: str): + next_headers = {} + if base_url and raw_url.startswith(base_url) and api_key: + next_headers['X-Integration-Key'] = api_key + return next_headers + + def _should_refresh_from_response(resp) -> bool: + ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower() + if resp.status_code == 401: + return True + if ctype == 'application/json': + body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower() + if 'unauthorized' in body or '"error"' in body: + return True + return False + + if base_url and file_url.startswith(base_url) and 'token=' in file_url: + try: + parsed = urlparse(file_url) + qs = parse_qs(parsed.query) + token = (qs.get('token') or [''])[0] + if token: + parts = token.split('.') + if len(parts) >= 2: + payload_b64 = parts[1] + payload_b64 += '=' * (-len(payload_b64) % 4) + payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8')) + exp = payload_data.get('exp', 0) + if exp and exp < time.time() + 300: + file_url = _resolve_latest_integration_url(file_url) + except Exception as e: + current_app.logger.warning("[file-preview] failed to refresh expired integration token: %s", e) + + headers = _build_headers(file_url) + try: + upstream = requests.get(file_url, headers=headers, timeout=(5, 20)) + except requests.RequestException as e: + current_app.logger.warning("[file-preview] upstream request failed: %s", e) + return None, None, ('failed to fetch source file', 502) + + # 某些旧历史记录中的 source_download_url 已过期,但上游可能返回 200 + JSON 错误体。 + # 这里统一视为“坏链接”,刷新最新下载地址后重试一次。 + if base_url and file_url.startswith(base_url) and 'token=' in file_url and _should_refresh_from_response(upstream): + refreshed_url = _resolve_latest_integration_url(file_url) + if refreshed_url != file_url: + headers = _build_headers(refreshed_url) + try: + upstream = requests.get(refreshed_url, headers=headers, timeout=(5, 20)) + file_url = refreshed_url + except requests.RequestException as e: + current_app.logger.warning("[file-preview] refreshed upstream request failed: %s", e) + return None, None, ('failed to fetch source file', 502) + + if upstream.status_code != 200: + return None, None, (f'upstream returned status {upstream.status_code}', 502) + + content = upstream.content or b'' + if len(content) > max_size: + return None, None, ('file too large for online preview', 413) + + content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower() + if content_type == 'application/json': + body = content[:512].decode('utf-8', errors='ignore') + current_app.logger.warning("[file-preview] upstream returned json instead of binary url=%s body=%s", file_url, body) + return None, None, ('upstream returned invalid preview payload', 502) + return content, content_type, None + +def _convert_office_to_pdf(content: bytes, ext: str) -> bytes: + """ + 使用 LibreOffice 将 office 文件转为 PDF + """ + with tempfile.TemporaryDirectory() as temp_dir: + input_path = os.path.join(temp_dir, f"input.{ext}") + with open(input_path, 'wb') as f: + f.write(content) + + commands = [ + 'soffice', + 'libreoffice', + r'C:\Program Files\LibreOffice\program\soffice.exe', + r'C:\Program Files (x86)\LibreOffice\program\soffice.exe' + ] + + success = False + for cmd in commands: + try: + process = subprocess.run( + [cmd, '--headless', '--convert-to', 'pdf', '--outdir', temp_dir, input_path], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=60 + ) + if process.returncode == 0: + success = True + break + else: + current_app.logger.warning(f"LibreOffice command {cmd} failed: {process.stderr.decode('utf-8', errors='ignore')}") + except (FileNotFoundError, subprocess.TimeoutExpired): + continue + + # 如果 LibreOffice 失败,且是在 Windows 系统下,尝试调用本地安装的 WPS 或 MS Office + if not success and os.name == 'nt': + try: + import win32com.client + import pythoncom + pythoncom.CoInitialize() + output_path = os.path.join(temp_dir, "input.pdf") + + if ext in ('doc', 'docx'): + try: + app = win32com.client.Dispatch("KWPS.Application") # 尝试 WPS Word + except Exception: + app = win32com.client.Dispatch("Word.Application") # 回退 MS Word + app.Visible = False + doc = app.Documents.Open(os.path.abspath(input_path)) + doc.SaveAs(os.path.abspath(output_path), FileFormat=17) # 17 = wdFormatPDF + doc.Close() + app.Quit() + success = True + + elif ext in ('ppt', 'pptx'): + try: + app = win32com.client.Dispatch("KWPP.Application") # 尝试 WPS PPT + except Exception: + app = win32com.client.Dispatch("PowerPoint.Application") # 回退 MS PPT + app.Visible = False + presentation = app.Presentations.Open(os.path.abspath(input_path), WithWindow=False) + presentation.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF + presentation.Close() + app.Quit() + success = True + + elif ext in ('xls', 'xlsx'): + try: + app = win32com.client.Dispatch("KET.Application") # 尝试 WPS Excel + except Exception: + app = win32com.client.Dispatch("Excel.Application") # 回退 MS Excel + app.Visible = False + wb = app.Workbooks.Open(os.path.abspath(input_path)) + wb.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF + wb.Close(False) + app.Quit() + success = True + except ImportError: + current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Office COM API.") + except Exception as e: + current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}") + + if not success: + raise Exception("Failed to convert document to PDF using LibreOffice or WPS/MS Office") + + output_path = os.path.join(temp_dir, "input.pdf") + if os.path.exists(output_path): + with open(output_path, 'rb') as f: + return f.read() + else: + raise Exception("PDF output not found after conversion") + + +def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes: + """ + 使用 LibreOffice 将老式 `.xls` 转为 `.xlsx`,供在线预览解析。 + """ + normalized_ext = (ext or '').strip().lower() + if normalized_ext != 'xls': + return content + + with tempfile.TemporaryDirectory() as temp_dir: + input_path = os.path.join(temp_dir, "input.xls") + output_path = os.path.join(temp_dir, "input.xlsx") + with open(input_path, 'wb') as f: + f.write(content) + + commands = [ + 'soffice', + 'libreoffice', + r'C:\Program Files\LibreOffice\program\soffice.exe', + r'C:\Program Files (x86)\LibreOffice\program\soffice.exe' + ] + + errors = [] + for cmd in commands: + try: + process = subprocess.run( + [cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=60 + ) + except (FileNotFoundError, subprocess.TimeoutExpired) as e: + errors.append(f"{cmd}: {e}") + continue + + if process.returncode == 0 and os.path.exists(output_path): + with open(output_path, 'rb') as f: + return f.read() + + stderr = process.stderr.decode('utf-8', errors='ignore').strip() + errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}") + + joined = "; ".join(errors) if errors else "no converter attempted" + raise RuntimeError(f"failed to convert xls to xlsx: {joined}") + + +def _load_excel_workbook(content: bytes, ext: str): + normalized_ext = (ext or '').strip().lower() + if normalized_ext == 'xls': + content = _convert_excel_to_xlsx(content, normalized_ext) + return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True) + + +@chat_bp.route('/sessions', methods=['GET']) +@require_agent_permission +def get_chat_sessions(): + """ + 获取当前用户与当前 Agent 的历史会话列表 + """ + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + + if user is None or agent is None: + return jsonify({'error': 'Missing context'}), 500 + + # 聚合查询:按 conversation_id 分组,获取最新时间 + # 注意:这里简化处理,直接取最新一条记录的 query 作为标题(或者第一条,取决于需求) + # 为了性能,这里我们取 max(created_at) 和 max(query) - 这只是一个近似值 + # 更严谨的做法是先查出 conversation_ids,再查详情。 + # 这里为了简单,我们假设 query 不为空 + + # 修正逻辑:先查出最近的 20 个 conversation_id + subquery = db.session.query( + ChatLog.conversation_id, + func.max(ChatLog.created_at).label('last_active') + ).filter_by( + user_id=user.id, + agent_id=agent.id + ).group_by(ChatLog.conversation_id).subquery() + + # 联表查询获取详细信息,按时间倒序 + results = db.session.query( + subquery.c.conversation_id, + subquery.c.last_active, + ChatLog.query + ).join( + ChatLog, + (ChatLog.conversation_id == subquery.c.conversation_id) & + (ChatLog.created_at == subquery.c.last_active) + ).order_by(desc(subquery.c.last_active)).limit(20).all() + + sessions = [] + for row in results: + if not row.conversation_id: + continue + sessions.append({ + 'id': 0, # 前端需要 id key + 'conversation_id': row.conversation_id, + 'title': row.query[:30] + ('...' if len(row.query) > 30 else '') if row.query else 'New Chat', + 'created_at': row.last_active.isoformat() + }) + + return jsonify(sessions) + + +@chat_bp.route('/sessions', methods=['DELETE']) +@require_agent_permission +def delete_all_chat_sessions(): + """ + 删除当前用户与当前 Agent 的所有历史会话 + """ + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + + if user is None or agent is None: + return jsonify({'error': 'Missing context'}), 500 + + chat_logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all() + chat_log_ids = [log.id for log in chat_logs] + if chat_log_ids: + from app.models import GeneralFeedback + db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.commit() + + return jsonify({'status': 'ok'}) + + +@chat_bp.route('/sessions/', methods=['DELETE']) +@require_agent_permission +def delete_chat_session(conversation_id): + """ + 删除指定的会话记录 + """ + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + + if user is None or agent is None: + return jsonify({'error': 'Missing context'}), 500 + + chat_logs = db.session.query(ChatLog).filter_by( + user_id=user.id, + agent_id=agent.id, + conversation_id=conversation_id + ).all() + + chat_log_ids = [log.id for log in chat_logs] + if chat_log_ids: + from app.models import GeneralFeedback + db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.commit() + + return jsonify({'status': 'ok'}) + + +@chat_bp.route('/messages', methods=['GET']) +@require_agent_permission +def get_chat_messages(): + """ + 获取指定会话的消息记录 + """ + conversation_id = request.args.get('conversation_id') + if not conversation_id: + return jsonify([]) + + logs = db.session.query(ChatLog).filter_by( + conversation_id=conversation_id + ).order_by(ChatLog.created_at.asc()).all() + + messages = [] + for log in logs: + messages.append({'role': 'user', 'content': log.query}) + messages.append({ + 'role': 'assistant', + 'content': log.answer, + 'chat_log_id': log.id, + 'retriever_resources': log.retriever_resources or [], + 'attribution_parts': log.attribution_parts or [] + }) + + return jsonify(messages) + + +@chat_bp.route('/completions', methods=['POST']) +@require_agent_permission +def chat_completions(): + """ + SSE 流式聊天接口 + 用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回 + 核心逻辑: + 1. 从请求体中读取 query / agent_id / conversation_id + 2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent + 3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送 + 传入参数: + 无(从 request.json 读取) + 返回值: + Flask Response 对象,mimetype=text/event-stream + """ + # 解析 JSON 请求体 + data = request.get_json() or {} + # 提取用户提问内容 + query = data.get('query') + # 提取会话 ID(可选) + conversation_id = data.get('conversation_id') + # 知识库类型 + kb_type = data.get('kb_type', '企业知识库') + + # 从全局 g 中获取装饰器注入的用户和 Agent 对象 + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + + current_app.logger.info( + "[chat-api] /completions request user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s", + getattr(user, 'id', None), + getattr(agent, 'id', None), + len(query or ''), + conversation_id, + kb_type + ) + + # 安全兜底:如果装饰器未正确注入,返回错误 + if user is None or agent is None: + current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent)) + return jsonify({'error': 'Missing user or agent context'}), 500 + + from app.services.dify import DifyService + + if kb_type == 'ERP知识库': + from app.services.text2sql import Text2SQLService + generator = Text2SQLService.stream_chat(query, user.id, agent, conversation_id) + else: + generator = DifyService.stream_chat(query, user.id, agent, conversation_id) + + # 返回 SSE 响应,mimetype 设为 text/event-stream + return Response( + stream_with_context( + generator + ), + mimetype='text/event-stream', + headers={ + 'Cache-Control': 'no-cache', + 'Content-Type': 'text/event-stream; charset=utf-8', + 'Connection': 'keep-alive', + # 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输 + 'X-Accel-Buffering': 'no' + } + ) + + +@chat_bp.route('/feedback', methods=['POST']) +@require_agent_permission +def submit_feedback(): + """ + 提交对回答的评分与评论 + 用途:在对话结束后,由前端发送评分(1~5)和文字意见 + 核心逻辑: + 1. 从请求体中读取 score/comment/conversation_id + 2. 根据当前 user/agent 与 conversation_id 查找最近一条 ChatLog + 3. 为该 ChatLog 创建或更新 Feedback 记录 + """ + data = request.get_json() or {} + score = data.get('score') + comment = data.get('comment') or '' + conversation_id = data.get('conversation_id') + + if not current_app.config.get('FEEDBACK_ENABLED', True): + return jsonify({'error': 'feedback is disabled'}), 403 + + if score is None: + return jsonify({'error': 'score is required'}), 400 + + try: + score_value = int(score) + except (TypeError, ValueError): + return jsonify({'error': 'score must be an integer'}), 400 + + if score_value < 1 or score_value > 5: + return jsonify({'error': 'score must be between 1 and 5'}), 400 + + user = getattr(g, 'current_user', None) + agent = getattr(g, 'current_agent', None) + if user is None or agent is None: + return jsonify({'error': 'Missing user or agent context'}), 500 + + # 构造查询:限定在当前用户和 Agent 范围内 + chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id) + if conversation_id: + chat_logs_query = chat_logs_query.filter_by(conversation_id=conversation_id) + + # 取最新一条对话日志 + chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first() + if not chat_log: + return jsonify({'error': 'ChatLog not found'}), 404 + + # 如果已存在反馈,则更新;否则新建 + if chat_log.feedback: + chat_log.feedback.score = score_value + chat_log.feedback.comment = comment + else: + fb = Feedback( + chat_log_id=chat_log.id, + score=score_value, + comment=comment, + ) + db.session.add(fb) + + db.session.commit() + return jsonify({'status': 'ok'}) + + +@chat_bp.route('/source-file', methods=['GET']) +@require_agent_permission +def resolve_source_file(): + """ + Resolve original source download URL by Dify dataset/document IDs. + """ + dataset_id = (request.args.get('dataset_id') or '').strip() + remote_document_id = (request.args.get('remote_document_id') or '').strip() + if not dataset_id or not remote_document_id: + current_app.logger.warning( + "[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s", + dataset_id, + bool(remote_document_id), + (remote_document_id[:8] + "...") if remote_document_id else "", + dict(request.args), + ) + return jsonify({'error': 'dataset_id and remote_document_id are required'}), 400 + + payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id) + if not payload: + return jsonify({'error': 'source file mapping not found'}), 404 + + return jsonify({ + 'dataset_id': dataset_id, + 'remote_document_id': remote_document_id, + 'source_filename': payload.get('source_filename'), + 'source_ext': payload.get('source_ext'), + 'source_download_url': payload.get('source_download_url'), + 'download_url_expires_at': payload.get('download_url_expires_at'), + }) + + +@chat_bp.route('/preview-excel', methods=['GET']) +@require_agent_permission +def preview_excel(): + """ + 内网 Excel 预览接口(简版可上线)。 + 说明: + - xlsx 直接解析; + - xls 先转为 xlsx 后再解析。 + """ + file_url = (request.args.get('url') or '').strip() + if not file_url: + return jsonify({'error': 'url is required'}), 400 + + if not _is_allowed_preview_url(file_url): + return jsonify({'error': 'url is not allowed for preview'}), 403 + + parsed = urlparse(file_url) + url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower() + name = (request.args.get('name') or '').strip() + name_ext = (name.split('.')[-1] if '.' in name else '').lower() + ext = url_path_ext or name_ext + if ext and ext not in ('xlsx', 'xls'): + return jsonify({'error': f'unsupported file extension: {ext}'}), 415 + + try: + limit = int(request.args.get('limit', 100)) + except ValueError: + limit = 100 + limit = max(1, min(limit, 300)) + + content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024) + if err: + msg, code = err + return jsonify({'error': msg}), code + + try: + wb = _load_excel_workbook(content, ext) + except Exception as e: + current_app.logger.warning("[excel-preview] parse workbook failed: %s", e) + return jsonify({'error': 'failed to parse excel file'}), 422 + + if not wb.sheetnames: + return jsonify({'error': 'workbook has no sheets'}), 422 + + requested_sheet = (request.args.get('sheet') or '').strip() + sheet_name = requested_sheet if requested_sheet in wb.sheetnames else wb.sheetnames[0] + ws = wb[sheet_name] + + rows = [] + for row in ws.iter_rows(values_only=True): + normalized = [] + for cell in row: + if cell is None: + normalized.append('') + elif isinstance(cell, (int, float, bool)): + normalized.append(cell) + else: + normalized.append(str(cell)) + rows.append(normalized) + if len(rows) >= limit: + break + + # 统一列宽,保证前端表格渲染稳定。 + max_cols = max((len(r) for r in rows), default=0) + for r in rows: + if len(r) < max_cols: + r.extend([''] * (max_cols - len(r))) + + columns = [f'COL_{i + 1}' for i in range(max_cols)] + return jsonify({ + 'sheet_name': sheet_name, + 'sheets': wb.sheetnames, + 'columns': columns, + 'rows': rows, + 'limit': limit, + 'truncated': len(rows) >= limit, + }) + + +@chat_bp.route('/preview-text', methods=['GET']) +@require_agent_permission +def preview_text(): + """ + 文本类文件预览接口(内网代理)。 + 支持:md/markdown/txt/csv/vtt/properties/html/htm + """ + file_url = (request.args.get('url') or '').strip() + if not file_url: + return jsonify({'error': 'url is required'}), 400 + if not _is_allowed_preview_url(file_url): + return jsonify({'error': 'url is not allowed for preview'}), 403 + + parsed = urlparse(file_url) + url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower() + name = (request.args.get('name') or '').strip() + name_ext = (name.split('.')[-1] if '.' in name else '').lower() + ext = url_path_ext or name_ext + allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'} + if ext and ext not in allowed: + return jsonify({'error': f'unsupported text extension: {ext}'}), 415 + + max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024 + content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size) + if err: + msg, code = err + return jsonify({'error': msg}), code + + # 尝试多编码解码,提升兼容性。 + text = None + for enc in ('utf-8', 'utf-8-sig', 'gb18030', 'latin-1'): + try: + text = content.decode(enc) + break + except Exception: + continue + if text is None: + return jsonify({'error': 'failed to decode text file'}), 422 + + return jsonify({ + 'content': text, + 'content_type': content_type or 'text/plain', + 'ext': ext, + }) + + +@chat_bp.route('/preview-file-raw', methods=['GET']) +@require_agent_permission +def preview_file_raw(): + """ + 二进制文件内网代理预览接口。 + 用途: + - 为 pdf/doc/docx 生成可被前端 iframe 访问的同源地址; + - 尽量使用 inline 响应头,避免强制下载。 + """ + file_url = (request.args.get('url') or '').strip() + if not file_url: + return jsonify({'error': 'url is required'}), 400 + if not _is_allowed_preview_url(file_url): + return jsonify({'error': 'url is not allowed for preview'}), 403 + + parsed = urlparse(file_url) + url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower() + name = (request.args.get('name') or '').strip() + name_ext = (name.split('.')[-1] if '.' in name else '').lower() + ext = url_path_ext or name_ext + max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024 + content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size) + if err: + msg, code = err + return jsonify({'error': msg}), code + + # 如果是无法纯前端渲染的旧版 Office 或 PPT 格式,尝试转为 PDF 供前端统一渲染 + if ext in ('doc', 'ppt', 'pptx') and request.args.get('download') != '1': + try: + content = _convert_office_to_pdf(content, ext) + ext = 'pdf' + content_type = 'application/pdf' + except Exception as e: + current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e) + # 转换失败则回退到原始格式 + + fallback_types = { + 'pdf': 'application/pdf', + 'doc': 'application/msword', + 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xls': 'application/vnd.ms-excel', + 'csv': 'text/csv', + 'txt': 'text/plain', + 'md': 'text/markdown', + 'markdown': 'text/markdown', + 'html': 'text/html', + 'htm': 'text/html', + } + if ext == 'pdf' and not content.startswith(b'%PDF-'): + return jsonify({'error': 'upstream did not return a valid pdf binary'}), 422 + + mime = fallback_types.get(ext) or content_type or 'application/octet-stream' + + from urllib.parse import quote + filename = (request.args.get('name') or '').strip() or f'preview.{ext or "bin"}' + encoded_filename = quote(filename) + ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f'preview.{ext or "bin"}' + + disposition_type = 'attachment' if is_download else 'inline' + + resp = Response(content, status=200, mimetype=mime) + resp.headers['Content-Disposition'] = f"{disposition_type}; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}" + resp.headers['Cache-Control'] = 'no-store' + return resp diff --git a/backend/app/api/integration.py b/backend/app/api/integration.py new file mode 100644 index 00000000..f5571285 --- /dev/null +++ b/backend/app/api/integration.py @@ -0,0 +1,349 @@ +""" +backend/app/api/integration.py +文件用途:知识库外部集成查询接口 +""" +from __future__ import annotations + +from pathlib import Path + +from flask import Blueprint, abort, current_app, jsonify, request, send_file +from sqlalchemy import func +from sqlalchemy.orm import joinedload + +from app import db +from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup + +integration_bp = Blueprint('integration', __name__) + + +def _require_integration_key(): + configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip() + incoming = str(request.headers.get('X-Integration-Key') or '').strip() + if not configured: + return jsonify({'error': 'INTEGRATION_API_KEY is not configured'}), 503 + if configured != incoming: + return jsonify({'error': 'Unauthorized'}), 401 + return None + + +def _integration_base_url() -> str: + explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/') + if explicit: + return explicit + return request.host_url.rstrip('/') + + +def _current_version(document: KbDocument) -> KbDocumentVersion | None: + versions = list(getattr(document, 'versions', []) or []) + if not versions: + return None + return next((item for item in versions if item.is_current), versions[0]) + + +def _document_query(): + return ( + db.session.query(KbDocument) + .options( + joinedload(KbDocument.group), + joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records), + ) + .filter(KbDocument.is_deleted.is_(False)) + ) + + +def _serialize_integration_document( + document: KbDocument, + *, + version: KbDocumentVersion | None = None, + sync_record: KbDifySyncRecord | None = None, +): + version = version or _current_version(document) + if not version: + abort(404, description='No current version found.') + + sync_record = sync_record or ( + next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) + or (version.sync_records[0] if getattr(version, 'sync_records', None) else None) + ) + + base_url = _integration_base_url() + source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source' + markdown_download_url = ( + f'{base_url}/api/integration/files/{document.id}/download?kind=md' + if version.cleaned_file_path or version.cleaned_preview_path + else None + ) + + return { + 'document_id': document.id, + 'knowledge_base': { + 'id': document.group.id if document.group else None, + 'name': document.group.name if document.group else None, + 'department_id': document.group.department_id if document.group else None, + 'dify_dataset_id': document.group.dify_dataset_id if document.group else None, + }, + 'title': document.title, + 'source_filename': version.source_file_name, + 'source_ext': version.source_file_ext, + 'file_name': version.source_file_name, + 'version_id': version.id, + 'version_no': version.version_no, + 'convert_status': version.status, + 'sync_status': sync_record.status if sync_record else None, + 'uploaded_at': version.created_at.isoformat() if version.created_at else None, + 'converted_at': version.converted_at.isoformat() if version.converted_at else None, + 'download_url_expires_at': None, + 'source_download_url': source_download_url, + 'markdown_download_url': markdown_download_url, + 'markdown_download_url_expires_at': None, + 'markdown_public_url': markdown_download_url, + 'dify': { + 'dataset_id': sync_record.dataset_id if sync_record else (document.group.dify_dataset_id if document.group else None), + 'remote_document_id': sync_record.remote_document_id if sync_record else None, + 'status': sync_record.status if sync_record else None, + 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None, + }, + } + + +def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict: + return { + 'id': group.id, + 'knowledge_base_id': group.id, + 'name': group.name, + 'description': group.description, + 'department_id': group.department_id, + 'dify_dataset_id': group.dify_dataset_id, + 'document_count': int(document_count or 0), + 'created_at': group.created_at.isoformat() if group.created_at else None, + 'updated_at': group.updated_at.isoformat() if group.updated_at else None, + } + + +def _list_files_payload( + *, + knowledge_base_id: int | None = None, + department_id: int | None = None, + file_name: str | None = None, +) -> list[dict]: + normalized_file_name = str(file_name or '').strip().lower() + query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc()) + if knowledge_base_id is not None: + query = query.filter(KbDocument.group_id == knowledge_base_id) + if department_id is not None: + query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id) + + documents = query.all() + payload = [] + for document in documents: + version = _current_version(document) + if not version: + continue + normalized_name = version.source_file_name.lower() if version.source_file_name else '' + if normalized_file_name and normalized_file_name not in normalized_name and normalized_file_name not in document.title.lower(): + continue + payload.append(_serialize_integration_document(document, version=version)) + return payload + + +def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]: + if kind == 'source': + path = Path(version.source_file_path) + filename = version.source_file_name or f'document-{version.document_id}' + return path, filename + + preferred = version.cleaned_file_path or version.cleaned_preview_path + if not preferred: + abort(409, description='Markdown not ready.') + path = Path(preferred) + filename = f'document-{version.document_id}-v{version.version_no}.md' + return path, filename + + +@integration_bp.before_request +def _verify_integration_access(): + result = _require_integration_key() + if result is not None: + return result + return None + + +@integration_bp.route('/files/', methods=['GET']) +def get_file_detail(file_id: int): + document = _document_query().filter(KbDocument.id == file_id).first() + if not document: + return jsonify({'error': 'Document not found.'}), 404 + return jsonify(_serialize_integration_document(document)) + + +@integration_bp.route('/knowledge-bases', methods=['GET']) +def list_knowledge_bases(): + department_id = request.args.get('department_id', type=int) + q = str(request.args.get('q') or '').strip() + + document_counts = ( + db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count')) + .filter(KbDocument.is_deleted.is_(False)) + .group_by(KbDocument.group_id) + .subquery() + ) + + query = ( + db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count')) + .outerjoin(document_counts, document_counts.c.group_id == KbGroup.id) + .filter(KbGroup.is_active.is_(True)) + .order_by(KbGroup.name.asc()) + ) + if department_id is not None: + query = query.filter(KbGroup.department_id == department_id) + if q: + query = query.filter(KbGroup.name.ilike(f'%{q}%')) + + rows = query.all() + return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]}) + + +@integration_bp.route('/files', methods=['GET']) +def list_files(): + knowledge_base_id = request.args.get('knowledge_base_id', type=int) + department_id = request.args.get('department_id', type=int) + file_name = request.args.get('file_name') + return jsonify({'data': _list_files_payload( + knowledge_base_id=knowledge_base_id, + department_id=department_id, + file_name=file_name, + )}) + + +@integration_bp.route('/knowledge-bases//files', methods=['GET']) +def list_files_for_knowledge_base(knowledge_base_id: int): + return jsonify({'data': _list_files_payload( + knowledge_base_id=knowledge_base_id, + file_name=request.args.get('file_name'), + )}) + + +@integration_bp.route('/dify-file', methods=['GET']) +def get_file_detail_by_dify(): + remote_document_id = str(request.args.get('remote_document_id') or '').strip() + dataset_id = str(request.args.get('dataset_id') or '').strip() or None + if not remote_document_id: + return jsonify({'error': 'remote_document_id is required'}), 400 + + record_query = ( + db.session.query(KbDifySyncRecord) + .join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id) + .join(KbDocument, KbDocument.id == KbDocumentVersion.document_id) + .options( + joinedload(KbDifySyncRecord.document_version) + .joinedload(KbDocumentVersion.document) + .joinedload(KbDocument.group), + joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records), + ) + .filter( + KbDocument.is_deleted.is_(False), + KbDifySyncRecord.remote_document_id == remote_document_id, + ) + .order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc()) + ) + if dataset_id: + record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id) + + record = record_query.first() + version = record.document_version if record else None + document = version.document if version else None + if not document: + return jsonify({'error': 'No local file mapping found for the given Dify document.'}), 404 + + return jsonify(_serialize_integration_document(document, version=version, sync_record=record)) + + +@integration_bp.route('/dify-files/resolve', methods=['POST']) +def resolve_files_by_dify(): + data = request.get_json(silent=True) or {} + items = data.get('items') if isinstance(data.get('items'), list) else [] + if not items: + return jsonify({'data': []}) + + remote_ids = sorted({ + str(item.get('remote_document_id') or '').strip() + for item in items + if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip() + }) + dataset_ids = sorted({ + str(item.get('dataset_id') or '').strip() + for item in items + if isinstance(item, dict) and str(item.get('dataset_id') or '').strip() + }) + if not remote_ids: + return jsonify({'data': []}) + + query = ( + db.session.query(KbDifySyncRecord) + .join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id) + .join(KbDocument, KbDocument.id == KbDocumentVersion.document_id) + .options( + joinedload(KbDifySyncRecord.document_version) + .joinedload(KbDocumentVersion.document) + .joinedload(KbDocument.group), + joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records), + ) + .filter( + KbDocument.is_deleted.is_(False), + KbDifySyncRecord.remote_document_id.in_(remote_ids), + ) + .order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc()) + ) + if dataset_ids: + query = query.filter( + (KbDifySyncRecord.dataset_id.in_(dataset_ids)) | (KbDifySyncRecord.dataset_id.is_(None)) + ) + + records = query.all() + records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {} + records_by_remote: dict[str, KbDifySyncRecord] = {} + for record in records: + key = (record.dataset_id, record.remote_document_id) + records_by_key.setdefault(key, record) + records_by_remote.setdefault(record.remote_document_id, record) + + payload = [] + for item in items: + if not isinstance(item, dict): + continue + requested_dataset_id = str(item.get('dataset_id') or '').strip() or None + requested_remote_document_id = str(item.get('remote_document_id') or '').strip() + if not requested_remote_document_id: + continue + record = records_by_key.get((requested_dataset_id, requested_remote_document_id)) + if record is None and requested_dataset_id is None: + record = records_by_remote.get(requested_remote_document_id) + version = record.document_version if record else None + document = version.document if version else None + payload.append({ + 'request': { + 'dataset_id': requested_dataset_id, + 'remote_document_id': requested_remote_document_id, + }, + 'found': bool(document), + 'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None, + }) + return jsonify({'data': payload}) + + +@integration_bp.route('/files//download', methods=['GET']) +def download_file(file_id: int): + kind = str(request.args.get('kind') or 'md').strip().lower() + document = _document_query().filter(KbDocument.id == file_id).first() + if not document: + return jsonify({'error': 'Document not found.'}), 404 + + version = _current_version(document) + if not version: + return jsonify({'error': 'No version found.'}), 404 + + path, filename = _resolve_download_path(version, kind) + if not path.exists(): + return jsonify({'error': 'File not found on disk.'}), 404 + + return send_file(path, as_attachment=True, download_name=filename) diff --git a/backend/app/api/knowledge_base.py b/backend/app/api/knowledge_base.py new file mode 100644 index 00000000..c0cfa3d9 --- /dev/null +++ b/backend/app/api/knowledge_base.py @@ -0,0 +1,1086 @@ +""" +backend/app/api/knowledge_base.py +文件用途:知识库/数据清洗模块第一阶段 API +""" +import hashlib +from datetime import datetime +from pathlib import Path +from posixpath import normpath + +from flask import Blueprint, current_app, jsonify, request, send_file +from sqlalchemy import func +from sqlalchemy.exc import DatabaseError, OperationalError +from sqlalchemy.orm import joinedload +from werkzeug.utils import secure_filename + +from app import db +from app.auth_jwt import get_current_user +from app.decorators import require_admin +from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, KbJob +from app.services.knowledge_cleaning.dify_sync_service import delete_document_from_dify +from app.services.knowledge_cleaning.queue_service import enqueue_clean_job, enqueue_kb_job +from app.services.knowledge_cleaning.settings_service import ( + get_kb_dify_health_payload, + get_kb_dify_settings, + save_kb_dify_settings, +) +from app.services.knowledge_cleaning.tasks import run_clean_job, run_sync_job + +knowledge_base_bp = Blueprint('knowledge_base', __name__) + + +def _safe_upload_filename(raw_filename: str | None) -> str: + original_name = Path(raw_filename or '').name.strip() + if not original_name: + return 'uploaded_file' + + original_path = Path(original_name) + safe_stem = secure_filename(original_path.stem) + suffix = original_path.suffix.lower() + + if not safe_stem: + safe_stem = 'uploaded_file' + return f'{safe_stem}{suffix}' + + +def _require_user(): + user = get_current_user() + if not user: + return None, (jsonify({'error': 'Unauthorized'}), 401) + return user, None + + +def _run_db_read(label: str, loader): + try: + return loader() + except (OperationalError, DatabaseError) as exc: + current_app.logger.warning('[kb] transient db error during %s, retry with reconnect: %s', label, exc) + db.session.rollback() + db.session.remove() + try: + db.engine.dispose() + except Exception: + current_app.logger.warning('[kb] failed to dispose engine during %s recovery', label, exc_info=True) + return loader() + + +def _serialize_group(group: KbGroup, document_count: int = 0): + return { + 'id': group.id, + 'name': group.name, + 'description': group.description, + 'department_id': group.department_id, + 'document_count': int(document_count or 0), + 'created_at': group.created_at.isoformat() if group.created_at else None, + 'updated_at': group.updated_at.isoformat() if group.updated_at else None, + } + + +def _serialize_document(doc: KbDocument): + latest_version = _current_version(doc) + + return { + 'id': doc.id, + 'group_id': doc.group_id, + 'title': doc.title, + 'description': doc.description, + 'status': doc.status, + 'source_type': doc.source_type, + 'created_at': doc.created_at.isoformat() if doc.created_at else None, + 'updated_at': doc.updated_at.isoformat() if doc.updated_at else None, + 'version_count': len(doc.versions) if getattr(doc, 'versions', None) else 0, + 'latest_version': _serialize_version(latest_version) if latest_version else None, + } + + +def _serialize_version(version: KbDocumentVersion | None): + if version is None: + return None + return { + 'id': version.id, + 'document_id': version.document_id, + 'version_no': version.version_no, + 'status': version.status, + 'is_current': version.is_current, + 'source_file_name': version.source_file_name, + 'source_file_ext': version.source_file_ext, + 'source_file_size': version.source_file_size, + 'sha256': version.sha256, + 'cleaned_file_path': version.cleaned_file_path, + 'cleaned_preview_path': version.cleaned_preview_path, + 'error_message': version.error_message, + 'created_at': version.created_at.isoformat() if version.created_at else None, + } + + +def _serialize_sync_record(record: KbDifySyncRecord): + return { + 'id': record.id, + 'group_id': record.group_id, + 'document_id': record.document_id, + 'document_version_id': record.document_version_id, + 'dataset_id': record.dataset_id, + 'dataset_name': record.dataset_name, + 'remote_document_id': record.remote_document_id, + 'remote_document_name': record.remote_document_name, + 'status': record.status, + 'sync_hash': record.sync_hash, + 'error_message': record.error_message, + 'synced_at': record.synced_at.isoformat() if record.synced_at else None, + 'updated_at': record.updated_at.isoformat() if record.updated_at else None, + } + + +def _serialize_job(job: KbJob): + return { + 'id': job.id, + 'job_type': job.job_type, + 'status': job.status, + 'group_id': job.group_id, + 'document_id': job.document_id, + 'document_version_id': job.document_version_id, + 'progress': job.progress, + 'message': job.message, + 'error_message': job.error_message, + 'payload_json': job.payload_json, + 'result_json': job.result_json, + 'created_at': job.created_at.isoformat() if job.created_at else None, + 'started_at': job.started_at.isoformat() if job.started_at else None, + 'finished_at': job.finished_at.isoformat() if job.finished_at else None, + } + + +def _current_version(document: KbDocument | None) -> KbDocumentVersion | None: + versions = list(getattr(document, 'versions', []) or []) + if not versions: + return None + return next((item for item in versions if item.is_current), versions[0]) + + +def _resolve_storage_path(path_value: str | None) -> Path | None: + if not path_value: + return None + candidate = Path(path_value).resolve() + root = _kb_storage_root() + try: + candidate.relative_to(root) + except ValueError: + return None + return candidate + + +def _resolve_markdown_read_path(version: KbDocumentVersion) -> tuple[Path | None, str]: + primary = _resolve_storage_path(version.cleaned_file_path) + if primary and primary.exists(): + return primary, 'markdown' + + preview = _resolve_storage_path(version.cleaned_preview_path) + if preview and preview.exists(): + return preview, 'preview' + + return None, 'markdown' + + +def _resolve_markdown_write_path(version: KbDocumentVersion) -> Path | None: + primary = _resolve_storage_path(version.cleaned_file_path) + if primary: + return primary + + preview = _resolve_storage_path(version.cleaned_preview_path) + if preview and preview.suffix.lower() == '.md': + return preview + + source = _resolve_storage_path(version.source_file_path) + if source: + return source.parent / 'document.md' + + return None + + +def _serialize_markdown_payload(document: KbDocument, version: KbDocumentVersion, content: str, kind: str): + return { + 'document_id': document.id, + 'title': document.title, + 'version': _serialize_version(version), + 'content': content, + 'kind': kind, + } + + +@knowledge_base_bp.route('/dify/settings', methods=['GET']) +@require_admin +def get_dify_settings(): + payload = get_kb_dify_settings() + return jsonify(payload) + + +@knowledge_base_bp.route('/dify/settings', methods=['PATCH']) +@require_admin +def update_dify_settings(): + data = request.get_json(silent=True) or {} + payload = save_kb_dify_settings(data) + return jsonify(payload) + + +@knowledge_base_bp.route('/dify/health', methods=['GET']) +@require_admin +def get_dify_health(): + payload = get_kb_dify_health_payload() + if payload['dify_api_configured'] and payload['dify_base_url']: + try: + from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService + + datasets = KbDifySyncService().list_datasets() + payload['api']['reachable'] = True + payload['api']['dataset_count'] = len(datasets) + except Exception as exc: + payload['api']['error'] = str(exc) + else: + payload['api']['error'] = 'Dify 连接尚未配置' + return jsonify(payload) + + +def _kb_storage_root() -> Path: + root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve() + root.mkdir(parents=True, exist_ok=True) + return root + + +def _next_version_no(document: KbDocument) -> int: + versions = list(getattr(document, 'versions', []) or []) + if not versions: + return 1 + return max(item.version_no for item in versions) + 1 + + +def _save_upload(file_storage, target_path: Path): + target_path.parent.mkdir(parents=True, exist_ok=True) + sha = hashlib.sha256() + size = 0 + with target_path.open('wb') as handle: + while True: + chunk = file_storage.stream.read(1024 * 1024) + if not chunk: + break + handle.write(chunk) + sha.update(chunk) + size += len(chunk) + return sha.hexdigest(), size + + +def _get_active_path_upload_job(group_id: int) -> KbJob | None: + return ( + db.session.query(KbJob) + .filter( + KbJob.group_id == group_id, + KbJob.job_type == 'path_upload', + KbJob.status.in_(('draft', 'staging', 'queued', 'running')), + ) + .order_by(KbJob.created_at.desc(), KbJob.id.desc()) + .first() + ) + + +def _sanitize_relative_path(relative_path: str | None, fallback_name: str) -> str: + raw = str(relative_path or '').replace('\\', '/').strip().lstrip('/') + normalized = normpath(raw) if raw else fallback_name + normalized = normalized.replace('\\', '/').lstrip('/') + if normalized in ('', '.'): + normalized = fallback_name + if normalized.startswith('../') or normalized == '..': + raise ValueError('非法路径') + + parts = [part for part in normalized.split('/') if part not in ('', '.')] + if any(part == '..' for part in parts): + raise ValueError('非法路径') + if not parts: + parts = [fallback_name] + + safe_parts = [_safe_upload_filename(part) for part in parts[:-1]] + safe_leaf = _safe_upload_filename(parts[-1] or fallback_name) + return '/'.join([*safe_parts, safe_leaf]).strip('/') or _safe_upload_filename(fallback_name) + + +@knowledge_base_bp.route('/groups', methods=['GET']) +def list_groups(): + user, error = _require_user() + if error: + return error + + rows = _run_db_read( + 'list_groups', + lambda: ( + db.session.query( + KbGroup, + func.count(KbDocument.id).label('document_count'), + ) + .outerjoin( + KbDocument, + (KbDocument.group_id == KbGroup.id) & (KbDocument.is_deleted.is_(False)), + ) + .filter(KbGroup.is_active.is_(True)) + .group_by(KbGroup.id) + .order_by(KbGroup.updated_at.desc(), KbGroup.id.desc()) + .all() + ), + ) + + payload = [_serialize_group(group, document_count) for group, document_count in rows] + return jsonify(payload) + + +@knowledge_base_bp.route('/groups', methods=['POST']) +@require_admin +def create_group(): + data = request.get_json(silent=True) or {} + name = str(data.get('name') or '').strip() + description = str(data.get('description') or '').strip() or None + department_id = data.get('department_id') + + if not name: + return jsonify({'error': 'name is required'}), 400 + + existing_query = db.session.query(KbGroup).filter( + KbGroup.name == name, + KbGroup.is_active.is_(True), + ) + if department_id is None: + existing_query = existing_query.filter(KbGroup.department_id.is_(None)) + else: + existing_query = existing_query.filter(KbGroup.department_id == department_id) + + if existing_query.first(): + return jsonify({'error': '知识库分组已存在'}), 400 + + current_user = get_current_user() + group = KbGroup( + name=name, + description=description, + department_id=department_id, + created_by_id=getattr(current_user, 'id', None), + updated_by_id=getattr(current_user, 'id', None), + ) + db.session.add(group) + db.session.commit() + + return jsonify(_serialize_group(group, 0)), 201 + + +@knowledge_base_bp.route('/groups/', methods=['PATCH']) +@require_admin +def update_group(group_id: int): + group = db.session.get(KbGroup, group_id) + if not group or not group.is_active: + return jsonify({'error': '知识库分组不存在'}), 404 + + data = request.get_json(silent=True) or {} + name = str(data.get('name') or group.name).strip() + description = data.get('description') + department_id = data.get('department_id', group.department_id) + + if not name: + return jsonify({'error': 'name is required'}), 400 + + existing_query = db.session.query(KbGroup).filter( + KbGroup.id != group.id, + KbGroup.name == name, + KbGroup.is_active.is_(True), + ) + if department_id is None: + existing_query = existing_query.filter(KbGroup.department_id.is_(None)) + else: + existing_query = existing_query.filter(KbGroup.department_id == department_id) + + if existing_query.first(): + return jsonify({'error': '知识库分组已存在'}), 400 + + current_user = get_current_user() + group.name = name + group.description = str(description).strip() or None if description is not None else None + group.department_id = department_id + group.updated_by_id = getattr(current_user, 'id', None) + db.session.commit() + + document_count = ( + db.session.query(func.count(KbDocument.id)) + .filter(KbDocument.group_id == group.id, KbDocument.is_deleted.is_(False)) + .scalar() + ) + return jsonify(_serialize_group(group, document_count)) + + +@knowledge_base_bp.route('/groups/', methods=['DELETE']) +@require_admin +def delete_group(group_id: int): + group = db.session.get(KbGroup, group_id) + if not group or not group.is_active: + return jsonify({'error': '知识库分组不存在'}), 404 + + current_user = get_current_user() + group.is_active = False + group.updated_by_id = getattr(current_user, 'id', None) + db.session.commit() + + return jsonify({'ok': True, 'id': group_id}) + + +@knowledge_base_bp.route('/groups//files', methods=['GET']) +def list_group_files(group_id: int): + user, error = _require_user() + if error: + return error + + group = _run_db_read('get_group_for_files', lambda: db.session.get(KbGroup, group_id)) + if not group or not group.is_active: + return jsonify({'error': 'Knowledge base group not found'}), 404 + + documents = _run_db_read( + 'list_group_files', + lambda: ( + db.session.query(KbDocument) + .options(joinedload(KbDocument.versions)) + .filter( + KbDocument.group_id == group_id, + KbDocument.is_deleted.is_(False), + ) + .order_by(KbDocument.updated_at.desc(), KbDocument.id.desc()) + .all() + ), + ) + + payload = [_serialize_document(doc) for doc in documents] + return jsonify(payload) + + +@knowledge_base_bp.route('/groups//files', methods=['POST']) +def create_group_file(group_id: int): + current_user, error = _require_user() + if error: + return error + + group = db.session.get(KbGroup, group_id) + if not group or not group.is_active: + return jsonify({'error': 'Knowledge base group not found'}), 404 + + data = request.get_json(silent=True) or {} + title = str(data.get('title') or '').strip() + description = str(data.get('description') or '').strip() or None + status = str(data.get('status') or 'draft').strip() or 'draft' + + if not title: + return jsonify({'error': 'title is required'}), 400 + + existing = ( + db.session.query(KbDocument) + .options(joinedload(KbDocument.versions)) + .filter(KbDocument.group_id == group_id, KbDocument.title == title) + .first() + ) + if existing and not existing.is_deleted: + return jsonify({'error': '当前分组下已存在同名文档'}), 400 + + if existing and existing.is_deleted: + existing.is_deleted = False + existing.description = description + existing.status = status + existing.updated_by_id = getattr(current_user, 'id', None) + db.session.commit() + return jsonify(_serialize_document(existing)), 201 + + document = KbDocument( + group_id=group_id, + title=title, + description=description, + status=status, + source_type='manual', + created_by_id=getattr(current_user, 'id', None), + updated_by_id=getattr(current_user, 'id', None), + ) + db.session.add(document) + db.session.commit() + return jsonify(_serialize_document(document)), 201 + + +@knowledge_base_bp.route('/groups//path-upload-jobs', methods=['POST']) +def create_path_upload_job(group_id: int): + current_user, error = _require_user() + if error: + return error + + group = db.session.get(KbGroup, group_id) + if not group or not group.is_active: + return jsonify({'error': 'Knowledge base group not found'}), 404 + + existing_job = _get_active_path_upload_job(group_id) + if existing_job: + return jsonify({'error': '有文件正在上传请稍等再试~', 'job': _serialize_job(existing_job)}), 409 + + data = request.get_json(silent=True) or {} + total_files = max(int(data.get('total_files') or 0), 0) + selected_paths = data.get('selected_paths') or [] + if not isinstance(selected_paths, list): + selected_paths = [] + + job = KbJob( + job_type='path_upload', + status='draft', + group_id=group_id, + progress=0, + message='等待上传路径文件到后台暂存区', + payload_json={ + 'total_files': total_files, + 'selected_paths': selected_paths, + 'staged_count': 0, + 'files': [], + }, + result_json={ + 'total': total_files, + 'success': 0, + 'failed': 0, + 'staged': 0, + }, + created_by_id=getattr(current_user, 'id', None), + ) + db.session.add(job) + db.session.commit() + return jsonify(_serialize_job(job)), 201 + + +@knowledge_base_bp.route('/path-upload-jobs//files', methods=['POST']) +def upload_path_job_file(job_id: int): + current_user, error = _require_user() + if error: + return error + + job = db.session.get(KbJob, job_id) + if not job or job.job_type != 'path_upload': + return jsonify({'error': '路径上传任务不存在'}), 404 + if job.status not in ('draft', 'staging'): + return jsonify({'error': '当前任务不允许继续上传文件'}), 409 + + uploaded = request.files.get('file') + if not uploaded or not uploaded.filename: + return jsonify({'error': 'file is required'}), 400 + + fallback_name = Path(uploaded.filename).name or 'uploaded_file' + try: + relative_path = _sanitize_relative_path(request.form.get('relative_path'), fallback_name) + except ValueError as exc: + return jsonify({'error': str(exc)}), 400 + + staging_root = _kb_storage_root() / 'path_upload_jobs' / f'job_{job.id:06d}' / 'staging' + target_path = staging_root / Path(relative_path) + sha256, file_size = _save_upload(uploaded, target_path) + + payload = dict(job.payload_json or {}) + files = list(payload.get('files') or []) + files.append({ + 'relative_path': relative_path, + 'original_name': fallback_name, + 'staged_path': str(target_path), + 'size': file_size, + 'sha256': sha256, + 'status': 'queued', + 'error': None, + 'document_id': None, + 'version_id': None, + }) + payload['files'] = files + payload['staged_count'] = len(files) + job.payload_json = payload + job.status = 'staging' + job.message = f'已暂存 {len(files)}/{payload.get("total_files") or len(files)} 个文件' + result = dict(job.result_json or {}) + result['total'] = payload.get('total_files') or len(files) + result['staged'] = len(files) + job.result_json = result + db.session.commit() + return jsonify(_serialize_job(job)), 201 + + +@knowledge_base_bp.route('/path-upload-jobs//finalize', methods=['POST']) +def finalize_path_upload_job(job_id: int): + current_user, error = _require_user() + if error: + return error + + job = db.session.get(KbJob, job_id) + if not job or job.job_type != 'path_upload': + return jsonify({'error': '路径上传任务不存在'}), 404 + if job.status not in ('draft', 'staging'): + return jsonify({'error': '当前任务不允许提交执行'}), 409 + + payload = dict(job.payload_json or {}) + files = list(payload.get('files') or []) + if not files: + return jsonify({'error': '当前没有可上传的文件'}), 400 + + job.status = 'queued' + job.progress = 0 + job.message = '等待后台批量导入文档' + payload['finalized_at'] = datetime.utcnow().isoformat() + job.payload_json = payload + job.created_by_id = getattr(current_user, 'id', None) + db.session.commit() + + enqueue_kb_job(job.id) + refreshed = db.session.get(KbJob, job.id) + return jsonify(_serialize_job(refreshed)) + + +@knowledge_base_bp.route('/path-upload-jobs//retry-failed', methods=['POST']) +def retry_failed_path_upload_job(job_id: int): + current_user, error = _require_user() + if error: + return error + + source_job = db.session.get(KbJob, job_id) + if not source_job or source_job.job_type != 'path_upload': + return jsonify({'error': '路径上传任务不存在'}), 404 + if not source_job.group_id: + return jsonify({'error': '路径上传任务缺少分组信息'}), 400 + + existing_job = _get_active_path_upload_job(source_job.group_id) + if existing_job and existing_job.id != source_job.id: + return jsonify({'error': '有文件正在上传请稍等再试~', 'job': _serialize_job(existing_job)}), 409 + + source_payload = dict(source_job.payload_json or {}) + source_files = list(source_payload.get('files') or []) + data = request.get_json(silent=True) or {} + requested_paths = data.get('relative_paths') or [] + if not isinstance(requested_paths, list): + requested_paths = [] + requested_path_set = {str(item).strip() for item in requested_paths if str(item).strip()} + + failed_files = [item for item in source_files if str(item.get('status') or '').lower() == 'failed'] + if requested_path_set: + failed_files = [ + item for item in failed_files + if str(item.get('relative_path') or item.get('original_name') or '').strip() in requested_path_set + ] + if not failed_files: + return jsonify({'error': '当前任务没有可重试的失败文件'}), 400 + + retry_files = [] + selected_paths = [] + for item in failed_files: + staged_path = str(item.get('staged_path') or '').strip() + if not staged_path: + continue + retry_item = { + 'relative_path': item.get('relative_path'), + 'original_name': item.get('original_name'), + 'staged_path': staged_path, + 'size': item.get('size'), + 'sha256': item.get('sha256'), + 'status': 'queued', + 'error': None, + 'document_id': None, + 'version_id': None, + } + retry_files.append(retry_item) + relative_path = str(item.get('relative_path') or item.get('original_name') or '').strip() + if relative_path: + root = relative_path.split('/')[0] + if root and root not in selected_paths: + selected_paths.append(root) + + if not retry_files: + return jsonify({'error': '失败文件暂存内容不存在,无法重试'}), 400 + + retry_job = KbJob( + job_type='path_upload', + status='queued', + group_id=source_job.group_id, + progress=0, + message='等待后台重试失败文件', + payload_json={ + 'total_files': len(retry_files), + 'selected_paths': selected_paths, + 'staged_count': len(retry_files), + 'source_job_id': source_job.id, + 'retry_mode': 'failed_only', + 'retry_relative_paths': list(requested_path_set), + 'files': retry_files, + }, + result_json={ + 'total': len(retry_files), + 'success': 0, + 'failed': 0, + 'staged': len(retry_files), + 'source_job_id': source_job.id, + }, + created_by_id=getattr(current_user, 'id', None), + ) + db.session.add(retry_job) + db.session.commit() + + enqueue_kb_job(retry_job.id) + refreshed = db.session.get(KbJob, retry_job.id) + return jsonify(_serialize_job(refreshed)), 201 + + +@knowledge_base_bp.route('/documents//versions', methods=['GET']) +def list_document_versions(document_id: int): + current_user, error = _require_user() + if error: + return error + + document = ( + db.session.query(KbDocument) + .options(joinedload(KbDocument.versions)) + .filter(KbDocument.id == document_id, KbDocument.is_deleted.is_(False)) + .first() + ) + if not document: + return jsonify({'error': 'Knowledge base document not found'}), 404 + + return jsonify([_serialize_version(item) for item in document.versions]) + + +@knowledge_base_bp.route('/document-versions//source-file', methods=['GET']) +def get_document_version_source_file(version_id: int): + current_user, error = _require_user() + if error: + return error + + version = ( + db.session.query(KbDocumentVersion) + .options(joinedload(KbDocumentVersion.document)) + .filter(KbDocumentVersion.id == version_id) + .first() + ) + if not version or not version.document or version.document.is_deleted: + return jsonify({'error': '知识库文档版本不存在'}), 404 + + source_path = _resolve_storage_path(version.source_file_path) + if not source_path or not source_path.exists(): + return jsonify({'error': '原始文件不存在或已被移除'}), 404 + + as_attachment = str(request.args.get('download') or '').strip() == '1' + filename = version.source_file_name or source_path.name + return send_file(source_path, as_attachment=as_attachment, download_name=filename) + + +@knowledge_base_bp.route('/documents//sync-records', methods=['GET']) +def list_document_sync_records(document_id: int): + current_user, error = _require_user() + if error: + return error + + document = db.session.get(KbDocument, document_id) + if not document or document.is_deleted: + return jsonify({'error': 'Knowledge base document not found'}), 404 + + records = ( + db.session.query(KbDifySyncRecord) + .filter(KbDifySyncRecord.document_id == document_id) + .order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc()) + .all() + ) + return jsonify([_serialize_sync_record(item) for item in records]) + + +@knowledge_base_bp.route('/documents//markdown', methods=['GET']) +def get_document_markdown(document_id: int): + current_user, error = _require_user() + if error: + return error + + document = ( + db.session.query(KbDocument) + .options(joinedload(KbDocument.versions)) + .filter(KbDocument.id == document_id, KbDocument.is_deleted.is_(False)) + .first() + ) + if not document: + return jsonify({'error': 'Knowledge base document not found'}), 404 + + version = _current_version(document) + if not version: + return jsonify({'error': '当前文档暂无版本记录'}), 404 + + markdown_path, kind = _resolve_markdown_read_path(version) + if not markdown_path: + return jsonify({'error': '当前文档尚未生成可编辑 Markdown'}), 409 + + content = markdown_path.read_text(encoding='utf-8', errors='ignore') + return jsonify(_serialize_markdown_payload(document, version, content, kind)) + + +@knowledge_base_bp.route('/documents//markdown', methods=['PATCH']) +def update_document_markdown(document_id: int): + current_user, error = _require_user() + if error: + return error + + document = ( + db.session.query(KbDocument) + .options(joinedload(KbDocument.versions)) + .filter(KbDocument.id == document_id, KbDocument.is_deleted.is_(False)) + .first() + ) + if not document: + return jsonify({'error': 'Knowledge base document not found'}), 404 + + version = _current_version(document) + if not version: + return jsonify({'error': '当前文档暂无版本记录'}), 404 + + data = request.get_json(silent=True) or {} + content = data.get('content') + if not isinstance(content, str): + return jsonify({'error': 'content is required'}), 400 + + markdown_path = _resolve_markdown_write_path(version) + if not markdown_path: + return jsonify({'error': '当前文档尚未生成可编辑 Markdown'}), 409 + + markdown_path.parent.mkdir(parents=True, exist_ok=True) + markdown_path.write_text(content, encoding='utf-8') + + version.cleaned_file_path = str(markdown_path) + version.cleaned_preview_path = str(markdown_path) + version.word_count = len(content.split()) + version.status = 'cleaned' + version.converted_at = datetime.utcnow() + version.error_message = None + + document.status = 'ready' + document.updated_by_id = getattr(current_user, 'id', None) + db.session.commit() + + return jsonify(_serialize_markdown_payload(document, version, content, 'markdown')) + + +@knowledge_base_bp.route('/documents//upload', methods=['POST']) +def upload_document_version(document_id: int): + current_user, error = _require_user() + if error: + return error + + document = ( + db.session.query(KbDocument) + .options(joinedload(KbDocument.versions)) + .filter(KbDocument.id == document_id, KbDocument.is_deleted.is_(False)) + .first() + ) + if not document: + return jsonify({'error': 'Knowledge base document not found'}), 404 + + uploaded = request.files.get('file') + if not uploaded or not uploaded.filename: + return jsonify({'error': 'file is required'}), 400 + + filename = _safe_upload_filename(uploaded.filename) + version_no = _next_version_no(document) + ext = Path(filename).suffix.lower().lstrip('.') or None + version_dir = _kb_storage_root() / f'group_{document.group_id:04d}' / f'document_{document.id:06d}' / f'v{version_no:03d}' + target_path = version_dir / filename + sha256, file_size = _save_upload(uploaded, target_path) + + for version in document.versions: + if version.is_current: + version.is_current = False + + version = KbDocumentVersion( + document_id=document.id, + version_no=version_no, + status='uploaded', + is_current=True, + source_file_name=filename, + source_file_path=str(target_path), + source_file_ext=ext, + source_file_size=file_size, + sha256=sha256, + uploaded_by_id=getattr(current_user, 'id', None), + ) + db.session.add(version) + db.session.flush() + document.source_type = 'upload' + document.updated_by_id = getattr(current_user, 'id', None) + + upload_job = KbJob( + job_type='upload', + status='success', + group_id=document.group_id, + document_id=document.id, + document_version_id=version.id, + progress=100, + message=f'已上传原始文件:{filename}', + payload_json={ + 'source_file_name': filename, + 'source_file_size': file_size, + }, + result_json={ + 'sha256': sha256, + 'stored_path': str(target_path), + }, + created_by_id=getattr(current_user, 'id', None), + started_at=version.created_at, + finished_at=version.created_at, + ) + clean_job = KbJob( + job_type='clean', + status='queued', + group_id=document.group_id, + document_id=document.id, + document_version_id=version.id, + progress=0, + message='等待接入清洗任务链路', + payload_json={ + 'document_version_id': version.id, + 'source_file_name': filename, + }, + created_by_id=getattr(current_user, 'id', None), + ) + db.session.add(upload_job) + db.session.add(clean_job) + db.session.commit() + enqueue_clean_job(clean_job.id) + db.session.expire_all() + version = db.session.get(KbDocumentVersion, version.id) + + return jsonify(_serialize_version(version)), 201 + + +@knowledge_base_bp.route('/documents//sync', methods=['POST']) +@require_admin +def sync_document(document_id: int): + current_user = get_current_user() + document = ( + db.session.query(KbDocument) + .options(joinedload(KbDocument.versions)) + .filter(KbDocument.id == document_id, KbDocument.is_deleted.is_(False)) + .first() + ) + if not document: + return jsonify({'error': 'Knowledge base document not found'}), 404 + + version = next((item for item in document.versions if item.is_current), None) + if not version: + return jsonify({'error': '当前文档没有可同步的版本'}), 400 + + sync_job = KbJob( + job_type='sync_dify', + status='queued', + group_id=document.group_id, + document_id=document.id, + document_version_id=version.id, + progress=0, + message='等待同步到 Dify', + payload_json={ + 'document_version_id': version.id, + 'document_id': document.id, + }, + created_by_id=getattr(current_user, 'id', None), + ) + db.session.add(sync_job) + db.session.commit() + + success, message = run_sync_job(sync_job.id) + refreshed = db.session.get(KbJob, sync_job.id) + payload = _serialize_job(refreshed) if refreshed else {'id': sync_job.id} + payload['run_result'] = message + if not success: + payload['error'] = (refreshed.error_message if refreshed else None) or message + return jsonify(payload), (200 if success else 400) + + +@knowledge_base_bp.route('/documents/', methods=['PATCH']) +def update_document(document_id: int): + current_user, error = _require_user() + if error: + return error + + document = db.session.get(KbDocument, document_id) + if not document or document.is_deleted: + return jsonify({'error': 'Knowledge base document not found'}), 404 + + data = request.get_json(silent=True) or {} + title = str(data.get('title') or document.title).strip() + description = data.get('description') + status = str(data.get('status') or document.status).strip() + + if not title: + return jsonify({'error': 'title is required'}), 400 + + duplicate = ( + db.session.query(KbDocument) + .filter( + KbDocument.id != document.id, + KbDocument.group_id == document.group_id, + KbDocument.title == title, + KbDocument.is_deleted.is_(False), + ) + .first() + ) + if duplicate: + return jsonify({'error': '当前分组下已存在同名文档'}), 400 + + document.title = title + document.description = str(description).strip() or None if description is not None else None + document.status = status or document.status + document.updated_by_id = getattr(current_user, 'id', None) + db.session.commit() + return jsonify(_serialize_document(document)) + + +@knowledge_base_bp.route('/documents/', methods=['DELETE']) +def delete_document(document_id: int): + current_user, error = _require_user() + if error: + return error + + document = db.session.get(KbDocument, document_id) + if not document or document.is_deleted: + return jsonify({'error': 'Knowledge base document not found'}), 404 + + try: + delete_result = delete_document_from_dify(document.id) + except Exception as exc: + return jsonify({'error': f'删除 Dify 远端文档失败:{exc}'}), 400 + + document.is_deleted = True + document.updated_by_id = getattr(current_user, 'id', None) + db.session.commit() + return jsonify({'ok': True, 'id': document_id, 'delete_dify': delete_result}) + + +@knowledge_base_bp.route('/jobs', methods=['GET']) +def list_jobs(): + user, error = _require_user() + if error: + return error + + jobs = _run_db_read( + 'list_jobs', + lambda: ( + db.session.query(KbJob) + .order_by(KbJob.created_at.desc(), KbJob.id.desc()) + .limit(50) + .all() + ), + ) + payload = [_serialize_job(job) for job in jobs] + return jsonify(payload) + + +@knowledge_base_bp.route('/jobs//run', methods=['POST']) +@require_admin +def run_job(job_id: int): + job = db.session.get(KbJob, job_id) + if not job: + return jsonify({'error': '任务不存在'}), 404 + + if job.job_type == 'clean': + success, message = run_clean_job(job_id) + elif job.job_type == 'sync_dify': + success, message = run_sync_job(job_id) + else: + return jsonify({'error': '当前仅支持手动执行 clean 或 sync_dify 任务'}), 400 + + refreshed = db.session.get(KbJob, job_id) + payload = _serialize_job(refreshed) if refreshed else {'id': job_id} + payload['run_result'] = message + return jsonify(payload), (200 if success else 400) diff --git a/backend/app/api/user.py b/backend/app/api/user.py index a842e6eb..f000d925 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -5,7 +5,7 @@ from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_even from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field from app.auth_jwt import get_current_user as _auth_current_user from app.auth_jwt import issue_local_access_token -from sqlalchemy.exc import IntegrityError, OperationalError +from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError from sqlalchemy import and_, or_, inspect, insert from datetime import datetime, timedelta import uuid @@ -147,6 +147,20 @@ def _get_current_user(): """ return _auth_current_user() + +def _run_db_with_retry(operation, *, label: str): + try: + return operation() + except (OperationalError, DatabaseError) as exc: + current_app.logger.warning('%s failed on first attempt: %s', label, exc) + db.session.rollback() + db.session.remove() + try: + db.engine.dispose() + except Exception as dispose_exc: + current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc) + return operation() + def _is_wecom_configured(): return all([ current_app.config.get('WECOM_ENABLED'), @@ -891,7 +905,7 @@ def login(): 'error_code': 'PASSWORD_LOGIN_DISABLED', }), 403 - try: + def _attempt_login(): data = request.get_json() or {} username = data.get('username') password = data.get('password') @@ -919,12 +933,28 @@ def login(): _write_login_audit('password', 'success', user=user) db.session.commit() return jsonify(_build_login_payload(user, 'password')) + + try: + return _attempt_login() except OperationalError as e: - print(f"Database connection error: {e}") - return jsonify({'error': 'Database connection failed'}), 503 + db.session.rollback() + db.session.remove() + try: + return _attempt_login() + except (OperationalError, DatabaseError) as retry_exc: + current_app.logger.warning('Password login retry failed: %s', retry_exc) + return jsonify({'error': 'Database connection failed'}), 503 + except DatabaseError as e: + db.session.rollback() + db.session.remove() + try: + return _attempt_login() + except (OperationalError, DatabaseError) as retry_exc: + current_app.logger.warning('Password login retry failed: %s', retry_exc) + return jsonify({'error': 'Database connection failed'}), 503 except Exception as e: db.session.rollback() - print(f"Login error: {e}") + current_app.logger.exception('Login error: %s', e) return jsonify({'error': 'Internal server error'}), 500 @@ -1720,64 +1750,76 @@ def home(): user = _get_current_user() if not user: return jsonify({'error': 'Unauthorized'}), 401 - - # Get all agents available to user (including public ones) - if user.role == 'admin': - agents = db.session.query(Agent).filter_by(is_active=True).all() - else: - # User permissions - agents = user.agents - - # Favorites - favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all() - favorite_ids = [f.agent_id for f in favorites] - - # Quick Questions (Global + User specific) - qqs = db.session.query(QuickQuestion).filter( - (QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None) - ).all() - - # Layout - layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first() - layout = layout_config.layout if layout_config else {} - - # Embedded agents - embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all() - embedded_agents = [] - for rel in embedded_rel: - agent = db.session.get(Agent, rel.agent_id) - if agent: - embedded_agents.append({ + + def _load_home_payload(): + # Get all agents available to user (including public ones) + if user.role == 'admin': + agent_rows = ( + db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url) + .filter(Agent.is_active.is_(True)) + .all() + ) + else: + # User permissions + agent_rows = [{ 'id': agent.id, 'name': agent.name, - 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None - }) + 'description': agent.description, + 'icon_url': agent.icon_url, + } for agent in user.agents] - return jsonify({ - 'user': { - 'id': user.id, - 'username': user.username, - 'role': user.role, - 'default_agent_id': user.default_agent_id, - 'language': user.language, - 'theme_preference': user.theme_preference or 'system', - }, - 'agents': [{ - 'id': a.id, - 'name': a.name, - 'description': a.description, - 'icon_url': a.icon_url - } for a in agents], - 'favorite_agent_ids': favorite_ids, - 'quick_questions': [{ - 'id': q.id, - 'title': q.title, - 'question': q.question, - 'agent_id': q.agent_id - } for q in qqs], - 'embedded_agents': embedded_agents, - 'layout': layout - }) + favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all() + favorite_ids = [f.agent_id for f in favorites] + + qqs = db.session.query(QuickQuestion).filter( + (QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None) + ).all() + + layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first() + layout = layout_config.layout if layout_config else {} + + embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all() + embedded_agents = [] + for rel in embedded_rel: + agent = db.session.get(Agent, rel.agent_id) + if agent: + embedded_agents.append({ + 'id': agent.id, + 'name': agent.name, + 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None + }) + + return jsonify({ + 'user': { + 'id': user.id, + 'username': user.username, + 'role': user.role, + 'default_agent_id': user.default_agent_id, + 'language': user.language, + 'theme_preference': user.theme_preference or 'system', + }, + 'agents': [{ + 'id': a.id if hasattr(a, 'id') else a['id'], + 'name': a.name if hasattr(a, 'name') else a['name'], + 'description': a.description if hasattr(a, 'description') else a['description'], + 'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url'] + } for a in agent_rows], + 'favorite_agent_ids': favorite_ids, + 'quick_questions': [{ + 'id': q.id, + 'title': q.title, + 'question': q.question, + 'agent_id': q.agent_id + } for q in qqs], + 'embedded_agents': embedded_agents, + 'layout': layout + }) + + try: + return _run_db_with_retry(_load_home_payload, label='user.home') + except (OperationalError, DatabaseError) as exc: + current_app.logger.warning('user.home retry failed: %s', exc) + return jsonify({'error': 'Database connection failed'}), 503 @user_bp.route('/favorites/', methods=['POST', 'DELETE']) def toggle_favorite(agent_id: int): @@ -1888,41 +1930,45 @@ def user_profile(): # PUT data = request.get_json() or {} - - if 'real_name' in data: - user.real_name = data['real_name'] - if 'phone_number' in data: - user.phone_number = data['phone_number'] - if 'language' in data: - user.language = data['language'] - if 'theme_preference' in data: - if data['theme_preference'] not in ['light', 'dark', 'system']: - return jsonify({'error': 'Invalid theme preference'}), 400 - user.theme_preference = data['theme_preference'] - - # Allow editing email, employee_id, department - if 'email' in data: - # Check uniqueness - if data['email']: - existing = db.session.query(User).filter_by(email=data['email']).first() - if existing and existing.id != user.id: - return jsonify({'error': 'Email already exists'}), 400 - user.email = data['email'] - - if 'employee_id' in data: - # Check uniqueness - if data['employee_id']: - existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first() - if existing and existing.id != user.id: - return jsonify({'error': 'Employee ID already exists'}), 400 - user.employee_id = data['employee_id'] - - if 'department' in data: - user.department = data['department'] - - try: + + def _update_profile(): + if 'real_name' in data: + user.real_name = data['real_name'] + if 'phone_number' in data: + user.phone_number = data['phone_number'] + if 'language' in data: + user.language = data['language'] + if 'theme_preference' in data: + if data['theme_preference'] not in ['light', 'dark', 'system']: + return jsonify({'error': 'Invalid theme preference'}), 400 + user.theme_preference = data['theme_preference'] + + if 'email' in data: + if data['email']: + existing = db.session.query(User).filter_by(email=data['email']).first() + if existing and existing.id != user.id: + return jsonify({'error': 'Email already exists'}), 400 + user.email = data['email'] + + if 'employee_id' in data: + if data['employee_id']: + existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first() + if existing and existing.id != user.id: + return jsonify({'error': 'Employee ID already exists'}), 400 + user.employee_id = data['employee_id'] + + if 'department' in data: + user.department = data['department'] + db.session.commit() return jsonify({'message': 'Profile updated successfully'}) + + try: + return _run_db_with_retry(_update_profile, label='user.profile.update') + except (OperationalError, DatabaseError) as exc: + db.session.rollback() + current_app.logger.warning('user.profile.update retry failed: %s', exc) + return jsonify({'error': 'Database connection failed'}), 503 except Exception as e: db.session.rollback() return jsonify({'error': str(e)}), 500 @@ -2055,17 +2101,30 @@ def get_announcements(): """ Get active announcements (Public) """ - try: - anns = db.session.query(Announcement).filter_by(is_active=True).order_by(Announcement.created_at.desc()).all() + def _load_announcements(): + anns = ( + db.session.query( + Announcement.id, + Announcement.title, + Announcement.content, + Announcement.created_at, + ) + .filter(Announcement.is_active.is_(True)) + .order_by(Announcement.created_at.desc()) + .all() + ) return jsonify([{ 'id': a.id, 'title': a.title, 'content': a.content, 'created_at': a.created_at.isoformat() } for a in anns]) - except Exception as e: - import traceback - return jsonify({'error': str(e), 'traceback': traceback.format_exc()}), 500 + + try: + return _run_db_with_retry(_load_announcements, label='user.announcements') + except (OperationalError, DatabaseError) as exc: + current_app.logger.warning('user.announcements retry failed: %s', exc) + return jsonify({'error': 'Database connection failed'}), 503 @user_bp.route('/announcements', methods=['POST']) def create_announcement(): diff --git a/backend/app/auth_jwt.py b/backend/app/auth_jwt.py index 0fd9591d..62982c2c 100644 --- a/backend/app/auth_jwt.py +++ b/backend/app/auth_jwt.py @@ -6,6 +6,7 @@ from typing import Any, Optional import jwt import requests from flask import current_app, g, request +from sqlalchemy.exc import DatabaseError, OperationalError from app import db from app.models import User @@ -156,43 +157,69 @@ def _extract_unverified_claims(token: str) -> dict: def _resolve_user_from_claims(claims: dict) -> Optional[User]: # Resolution order keeps compatibility with different token claim conventions. - user_id = claims.get('user_id') or claims.get('id') - if user_id is not None: - try: - user = db.session.get(User, int(user_id)) + def _lookup() -> Optional[User]: + user_id = claims.get('user_id') or claims.get('id') + if user_id is not None: + try: + user = db.session.get(User, int(user_id)) + if user: + return user + except (TypeError, ValueError): + pass + + username = claims.get('preferred_username') or claims.get('username') or claims.get('name') + if username: + user = db.session.query(User).filter_by(username=str(username)).first() if user: return user - except (TypeError, ValueError): - pass - username = claims.get('preferred_username') or claims.get('username') or claims.get('name') - if username: - user = db.session.query(User).filter_by(username=str(username)).first() - if user: - return user + email = claims.get('email') + if email: + user = db.session.query(User).filter_by(email=str(email)).first() + if user: + return user + return None - email = claims.get('email') - if email: - user = db.session.query(User).filter_by(email=str(email)).first() - if user: - return user - return None + try: + return _lookup() + except (OperationalError, DatabaseError) as exc: + current_app.logger.warning('[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s', request.path, exc) + db.session.rollback() + db.session.remove() + try: + db.engine.dispose() + except Exception: + current_app.logger.warning('[auth_jwt] failed to dispose engine during user reconnect recovery', exc_info=True) + return _lookup() def _legacy_header_user() -> Optional[User]: - user_id = request.headers.get('X-User-Id') - if user_id: - try: - user = db.session.get(User, int(user_id)) - if user: - return user - except (TypeError, ValueError): - pass + def _lookup() -> Optional[User]: + user_id = request.headers.get('X-User-Id') + if user_id: + try: + user = db.session.get(User, int(user_id)) + if user: + return user + except (TypeError, ValueError): + pass - username = request.headers.get('X-Username') - if username: - return db.session.query(User).filter_by(username=username).first() - return None + username = request.headers.get('X-Username') + if username: + return db.session.query(User).filter_by(username=username).first() + return None + + try: + return _lookup() + except (OperationalError, DatabaseError) as exc: + current_app.logger.warning('[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s', request.path, exc) + db.session.rollback() + db.session.remove() + try: + db.engine.dispose() + except Exception: + current_app.logger.warning('[auth_jwt] failed to dispose engine during legacy user reconnect recovery', exc_info=True) + return _lookup() def get_current_user() -> Optional[User]: diff --git a/backend/app/config.py b/backend/app/config.py index 45fe9693..d4a66f91 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -16,6 +16,9 @@ load_dotenv(_BACKEND_DIR / '.env') class Config: SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key') + KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb')) + KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'sync').strip().lower() + KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2')) # 数据库连接池配置 SQLALCHEMY_ENGINE_OPTIONS = { 'pool_size': 20, @@ -37,6 +40,7 @@ class Config: HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY') # External integration API (resolve original source file links by Dify IDs) + INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower() INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE', 'http://192.168.100.230:8891') INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY') @@ -104,9 +108,7 @@ class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABASE_URL', - 'postgresql://postgres:123456@8.152.207.171:5432/hxops_db', - #'postgresql://postgres:difyai123456@localhost:5432/hxops_db', - #'postgresql://postgres:123456@localhost:5432/hxops_db', + 'postgresql://postgres:1qaz%40WSX@localhost:5432/hxops', ) diff --git a/backend/app/models.py b/backend/app/models.py index 1402a615..ec9731d3 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -1,6 +1,6 @@ from datetime import datetime from typing import Optional, List -from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index +from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column, relationship from app import db from werkzeug.security import generate_password_hash, check_password_hash @@ -338,6 +338,191 @@ class AppSetting(Base): ) +class KbGroup(Base): + """ + 知识库分组 + 用途:承载数据清洗/知识库管理模块中的分组/知识库 + """ + __tablename__ = 'kb_groups' + __table_args__ = ( + UniqueConstraint('department_id', 'name', name='uq_kb_groups_department_name'), + Index('ix_kb_groups_department_active', 'department_id', 'is_active'), + Index('ix_kb_groups_dify_dataset_id', 'dify_dataset_id'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + name: Mapped[str] = mapped_column(String(128), index=True) + description: Mapped[Optional[str]] = mapped_column(Text) + department_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, index=True) + is_active: Mapped[bool] = mapped_column(Boolean, default=True) + dify_dataset_id: Mapped[Optional[str]] = mapped_column(String(128)) + dify_dataset_name: Mapped[Optional[str]] = mapped_column(String(255)) + created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) + updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id]) + updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id]) + documents: Mapped[List["KbDocument"]] = relationship( + "KbDocument", + back_populates="group", + cascade="all, delete-orphan", + ) + + +class KbDocument(Base): + """ + 知识库逻辑文档 + 用途:表示一个文档条目,不直接等同于某一次上传文件 + """ + __tablename__ = 'kb_documents' + __table_args__ = ( + UniqueConstraint('group_id', 'title', name='uq_kb_documents_group_title'), + Index('ix_kb_documents_group_status', 'group_id', 'status'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + group_id: Mapped[int] = mapped_column(ForeignKey('kb_groups.id'), index=True) + title: Mapped[str] = mapped_column(String(255)) + description: Mapped[Optional[str]] = mapped_column(Text) + status: Mapped[str] = mapped_column(String(32), default='draft', index=True) + source_type: Mapped[Optional[str]] = mapped_column(String(32)) + is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, index=True) + created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) + updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + group: Mapped["KbGroup"] = relationship("KbGroup", back_populates="documents") + created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id]) + updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id]) + versions: Mapped[List["KbDocumentVersion"]] = relationship( + "KbDocumentVersion", + back_populates="document", + cascade="all, delete-orphan", + order_by="desc(KbDocumentVersion.version_no)", + ) + + +class KbDocumentVersion(Base): + """ + 知识库文档版本 + 用途:记录每次上传、清洗、同步产生的版本信息 + """ + __tablename__ = 'kb_document_versions' + __table_args__ = ( + UniqueConstraint('document_id', 'version_no', name='uq_kb_document_versions_doc_version'), + Index('ix_kb_document_versions_doc_status', 'document_id', 'status'), + Index('ix_kb_document_versions_sha256', 'sha256'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + document_id: Mapped[int] = mapped_column(ForeignKey('kb_documents.id'), index=True) + version_no: Mapped[int] = mapped_column(Integer) + status: Mapped[str] = mapped_column(String(32), default='uploaded', index=True) + is_current: Mapped[bool] = mapped_column(Boolean, default=True, index=True) + source_file_name: Mapped[str] = mapped_column(String(255)) + source_file_path: Mapped[str] = mapped_column(Text) + source_file_ext: Mapped[Optional[str]] = mapped_column(String(32)) + source_file_size: Mapped[Optional[int]] = mapped_column(Integer) + cleaned_file_path: Mapped[Optional[str]] = mapped_column(Text) + cleaned_preview_path: Mapped[Optional[str]] = mapped_column(Text) + sha256: Mapped[Optional[str]] = mapped_column(String(64)) + word_count: Mapped[int] = mapped_column(Integer, default=0) + error_message: Mapped[Optional[str]] = mapped_column(Text) + warnings_json: Mapped[Optional[dict]] = mapped_column(JSON) + uploaded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) + converted_at: Mapped[Optional[datetime]] = mapped_column(DateTime) + + document: Mapped["KbDocument"] = relationship("KbDocument", back_populates="versions") + uploaded_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[uploaded_by_id]) + jobs: Mapped[List["KbJob"]] = relationship( + "KbJob", + back_populates="document_version", + cascade="all, delete-orphan", + ) + sync_records: Mapped[List["KbDifySyncRecord"]] = relationship( + "KbDifySyncRecord", + back_populates="document_version", + cascade="all, delete-orphan", + order_by="desc(KbDifySyncRecord.updated_at)", + ) + + +class KbJob(Base): + """ + 知识库后台任务 + 用途:记录上传、清洗、同步等后台任务执行情况 + """ + __tablename__ = 'kb_jobs' + __table_args__ = ( + Index('ix_kb_jobs_status_created', 'status', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + job_type: Mapped[str] = mapped_column(String(32), index=True) + status: Mapped[str] = mapped_column(String(32), default='queued', index=True) + queue_job_id: Mapped[Optional[str]] = mapped_column(String(64)) + group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id')) + document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id')) + document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), index=True) + progress: Mapped[int] = mapped_column(Integer, default=0) + message: Mapped[Optional[str]] = mapped_column(Text) + error_message: Mapped[Optional[str]] = mapped_column(Text) + payload_json: Mapped[Optional[dict]] = mapped_column(JSON) + result_json: Mapped[Optional[dict]] = mapped_column(JSON) + created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime) + finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime) + + created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id]) + document_version: Mapped[Optional["KbDocumentVersion"]] = relationship( + "KbDocumentVersion", + back_populates="jobs", + ) + + +class KbDifySyncRecord(Base): + """ + 知识库 Dify 同步记录 + 用途:记录本地文档版本与 Dify 远端文档之间的同步映射 + """ + __tablename__ = 'kb_dify_sync_records' + __table_args__ = ( + UniqueConstraint( + 'document_version_id', + 'remote_document_id', + name='uq_kb_dify_sync_records_version_remote' + ), + Index('ix_kb_dify_sync_records_dataset_id', 'dataset_id'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id')) + document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id')) + document_version_id: Mapped[int] = mapped_column(ForeignKey('kb_document_versions.id'), index=True) + dataset_id: Mapped[str] = mapped_column(String(128)) + dataset_name: Mapped[Optional[str]] = mapped_column(String(255)) + remote_document_id: Mapped[str] = mapped_column(String(128)) + remote_document_name: Mapped[Optional[str]] = mapped_column(String(255)) + status: Mapped[str] = mapped_column(String(32), default='pending', index=True) + sync_hash: Mapped[Optional[str]] = mapped_column(String(64)) + error_message: Mapped[Optional[str]] = mapped_column(Text) + synced_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) + synced_at: Mapped[Optional[datetime]] = mapped_column(DateTime) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + document_version: Mapped["KbDocumentVersion"] = relationship( + "KbDocumentVersion", + back_populates="sync_records", + ) + synced_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[synced_by_id]) + + class WecomCallbackAudit(Base): """ 企业微信回调审计表 diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index de2497fc..3552a15a 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -38,22 +38,33 @@ class DifyService: """Dify service wrapper.""" @staticmethod - def build_chat_messages_url(raw_base_url: str) -> str: + def _build_chat_messages_url(base_url: str) -> str: """ - 统一构建 Dify chat-messages URL,兼容以下输入: - - http(s)://host - - http(s)://host/v1 - - http(s)://host/chat-messages - - http(s)://host/v1/chat-messages + Build the Dify chat-messages endpoint URL from a base URL. + + Our config/agent base_url may be: + - https://api.dify.ai/v1 + - http://host:port + - http://host:port/v1 + - (user mistake) http://host:port/v1/chat-messages + + This helper normalizes common mistakes and prevents duplicate `/v1/v1/...`. """ - base_url = (raw_base_url or '').strip().rstrip('/') - if not base_url: - return '' - if base_url.endswith('/v1/chat-messages') or base_url.endswith('/chat-messages'): - return base_url - if base_url.endswith('/v1'): - return f'{base_url}/chat-messages' - return f'{base_url}/v1/chat-messages' + base = str(base_url or "").strip().rstrip("/") + if not base: + # Keep old behavior: downstream will fail with a request error. + return "/v1/chat-messages" + + # User mistake hardening: strip endpoint suffix if someone stored it as base_url. + if base.endswith("/v1/chat-messages"): + base = base[: -len("/v1/chat-messages")].rstrip("/") + elif base.endswith("/chat-messages"): + base = base[: -len("/chat-messages")].rstrip("/") + + # Config.DIFY_API_BASE defaults to ".../v1". Avoid double "/v1". + if base.endswith("/v1"): + return f"{base}/chat-messages" + return f"{base}/v1/chat-messages" @staticmethod def stream_chat(query: str, user_id: int, agent, conversation_id: str = None): @@ -78,7 +89,7 @@ class DifyService: """ # Prefer agent-specific base URL; fallback to global config. base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE - url = DifyService.build_chat_messages_url(base_url) + url = DifyService._build_chat_messages_url(base_url) headers = { 'Authorization': f'Bearer {agent.dify_api_key}', diff --git a/backend/app/services/integration_api.py b/backend/app/services/integration_api.py index 822581dc..c6f3f54f 100644 --- a/backend/app/services/integration_api.py +++ b/backend/app/services/integration_api.py @@ -3,9 +3,10 @@ Integration API client for resolving original source-file download links. """ from datetime import datetime from typing import Any, Dict, List, Optional, Tuple +from urllib.parse import urlparse import requests -from flask import current_app +from flask import current_app, has_app_context, has_request_context, request from app.config import Config @@ -13,6 +14,44 @@ from app.config import Config class IntegrationApiService: _cache: Dict[Tuple[str, str], Dict[str, Any]] = {} + @staticmethod + def _is_loopback_url(url: str) -> bool: + host = (urlparse(str(url or "").strip()).hostname or "").strip().lower() + return host in {"127.0.0.1", "localhost", "::1"} + + @staticmethod + def get_api_key() -> str: + if has_app_context(): + return str(current_app.config.get("INTEGRATION_API_KEY") or "").strip() + return str(Config.INTEGRATION_API_KEY or "").strip() + + @staticmethod + def get_base_url() -> str: + mode = "local" + if has_app_context(): + mode = str(current_app.config.get("INTEGRATION_API_MODE") or "local").strip().lower() + configured = str(current_app.config.get("INTEGRATION_API_BASE") or "").strip().rstrip("/") + public_base = str(current_app.config.get("WECOM_PUBLIC_BASE_URL") or "").strip().rstrip("/") + else: + mode = str(getattr(Config, "INTEGRATION_API_MODE", "local") or "local").strip().lower() + configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/") + public_base = "" + + if mode != "external": + # For server-side lookups inside containers/workers, an explicit integration + # endpoint is more reliable than a public loopback URL like 127.0.0.1:5002. + if configured and ( + not has_request_context() + or IntegrationApiService._is_loopback_url(public_base) + ): + return configured + if public_base: + return public_base + if has_request_context(): + return request.host_url.rstrip("/") + + return configured + @staticmethod def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]: return (str(dataset_id), str(remote_document_id)) @@ -60,8 +99,8 @@ class IntegrationApiService: if cached and IntegrationApiService._is_cache_valid(cached): return cached - base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/") - api_key = Config.INTEGRATION_API_KEY + base_url = IntegrationApiService.get_base_url() + api_key = IntegrationApiService.get_api_key() if not base_url or not api_key: return None @@ -82,7 +121,7 @@ class IntegrationApiService: IntegrationApiService._cache[cache_key] = payload return payload except Exception as e: - if current_app: + if has_app_context(): current_app.logger.warning(f"Integration API lookup failed: {e}") return None @@ -121,8 +160,8 @@ class IntegrationApiService: if not unresolved: return results - base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/") - api_key = Config.INTEGRATION_API_KEY + base_url = IntegrationApiService.get_base_url() + api_key = IntegrationApiService.get_api_key() if not base_url or not api_key: return results @@ -136,7 +175,7 @@ class IntegrationApiService: try: resp = requests.post(url, headers=headers, json=body, timeout=(5, 12)) if resp.status_code != 200: - if current_app: + if has_app_context(): current_app.logger.warning( "Integration API batch lookup failed: status=%s", resp.status_code ) @@ -187,7 +226,7 @@ class IntegrationApiService: return results except Exception as e: - if current_app: + if has_app_context(): current_app.logger.warning(f"Integration API batch lookup exception: {e}") # Fallback to single lookup when batch call errors. for item in unresolved: diff --git a/backend/app/services/knowledge_cleaning/__init__.py b/backend/app/services/knowledge_cleaning/__init__.py new file mode 100644 index 00000000..2419dbaa --- /dev/null +++ b/backend/app/services/knowledge_cleaning/__init__.py @@ -0,0 +1,3 @@ +""" +知识库清洗服务包 +""" diff --git a/backend/app/services/knowledge_cleaning/dify_sync_service.py b/backend/app/services/knowledge_cleaning/dify_sync_service.py new file mode 100644 index 00000000..36285771 --- /dev/null +++ b/backend/app/services/knowledge_cleaning/dify_sync_service.py @@ -0,0 +1,305 @@ +""" +backend/app/services/knowledge_cleaning/dify_sync_service.py +文件用途:知识库文档版本到 Dify 的最小同步服务 +""" +from __future__ import annotations + +from datetime import datetime +import hashlib +from pathlib import Path + +import requests + +from app import db +from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup +from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings + + +class KbDifySyncError(RuntimeError): + pass + + +class KbDifySyncService: + def __init__(self) -> None: + settings = get_kb_dify_settings() + self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/') + self.api_key = str(settings.get('DIFY_API_KEY') or '').strip() + self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me') + self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality') + self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search') + self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model') + self.timeout = 60 + + def _headers(self) -> dict[str, str]: + if not self.base_url: + raise KbDifySyncError('DIFY_API_BASE 未配置') + if not self.api_key: + raise KbDifySyncError('DIFY_API_KEY 未配置') + return { + 'Authorization': f'Bearer {self.api_key}', + 'Content-Type': 'application/json', + } + + def _request(self, method: str, path: str, **kwargs): + url = f'{self.base_url}{path}' + try: + response = requests.request( + method, + url, + headers=self._headers(), + timeout=self.timeout, + **kwargs, + ) + except requests.RequestException as exc: + raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc + if response.status_code >= 400: + raise KbDifySyncError( + f'Dify API {method} {path} failed: {response.status_code} {response.text}' + ) + if response.status_code == 204: + return None + return response.json() + + def list_datasets(self) -> list[dict]: + payload = self._request('GET', '/datasets') + return payload.get('data', []) if isinstance(payload, dict) else [] + + def create_dataset(self, *, name: str, description: str | None) -> dict: + payload = { + 'name': name, + 'description': description or '', + 'permission': self.permission, + 'indexing_technique': self.indexing_technique, + 'doc_form': self.doc_form, + 'retrieval_model': { + 'search_method': self.search_method, + 'reranking_enable': False, + 'top_k': 3, + 'score_threshold_enabled': False, + 'score_threshold': None, + }, + } + return self._request('POST', '/datasets', json=payload) + + def ensure_dataset(self, group: KbGroup) -> tuple[str, str]: + if group.dify_dataset_id: + return group.dify_dataset_id, group.dify_dataset_name or group.name + + dataset_name = group.dify_dataset_name or group.name + existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None) + if existing: + group.dify_dataset_id = existing.get('id') + group.dify_dataset_name = existing.get('name') or dataset_name + db.session.commit() + return group.dify_dataset_id, group.dify_dataset_name + + created = self.create_dataset(name=dataset_name, description=group.description) + group.dify_dataset_id = created.get('id') + group.dify_dataset_name = created.get('name') or dataset_name + db.session.commit() + return group.dify_dataset_id, group.dify_dataset_name + + def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict: + payload = { + 'name': name, + 'text': text, + 'indexing_technique': self.indexing_technique, + 'doc_form': self.doc_form, + 'process_rule': {'mode': 'automatic'}, + } + return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload) + + def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict: + payload = { + 'name': name, + 'text': text, + 'process_rule': {'mode': 'automatic'}, + } + return self._request( + 'POST', + f'/datasets/{dataset_id}/documents/{document_id}/update-by-text', + json=payload, + ) + + def get_document(self, *, dataset_id: str, document_id: str) -> dict: + return self._request('GET', f'/datasets/{dataset_id}/documents/{document_id}') + + def delete_document(self, *, dataset_id: str, document_id: str) -> None: + self._request( + 'DELETE', + f'/datasets/{dataset_id}/documents/{document_id}', + ) + + +def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]: + candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path] + for value in candidate_paths: + if not value: + continue + path = Path(value) + if not path.exists(): + continue + text = path.read_text(encoding='utf-8', errors='ignore').strip() + if text: + return text, str(path) + raise KbDifySyncError('没有可用于同步的文本结果') + + +def _is_remote_document_missing(error_text: str) -> bool: + return ( + '404' in error_text + and ('Document not found' in error_text or '"code":"not_found"' in error_text) + ) + + +def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict: + version = db.session.get(KbDocumentVersion, document_version_id) + if not version or not version.document or not version.document.group: + raise KbDifySyncError('文档版本或关联分组不存在') + + group = version.document.group + document = version.document + text, source_path = _load_sync_text(version) + sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest() + + service = KbDifySyncService() + dataset_id, dataset_name = service.ensure_dataset(group) + + existing_record = ( + db.session.query(KbDifySyncRecord) + .filter( + KbDifySyncRecord.document_id == document.id, + KbDifySyncRecord.remote_document_id.isnot(None), + ) + .order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc()) + .first() + ) + + remote_document_id = None + remote_document_name = None + if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash: + try: + payload = service.get_document( + dataset_id=dataset_id, + document_id=existing_record.remote_document_id, + ) + remote_document_id = payload.get('id') or existing_record.remote_document_id + remote_document_name = payload.get('name') or existing_record.remote_document_name or document.title + except KbDifySyncError as exc: + if not _is_remote_document_missing(str(exc)): + raise + payload = service.create_document_by_text( + dataset_id=dataset_id, + name=document.title, + text=text, + ) + remote_document_id = payload.get('document', {}).get('id') or payload.get('id') + remote_document_name = payload.get('document', {}).get('name') or document.title + elif existing_record and existing_record.dataset_id == dataset_id: + try: + payload = service.update_document_by_text( + dataset_id=dataset_id, + document_id=existing_record.remote_document_id, + name=document.title, + text=text, + ) + except KbDifySyncError as exc: + if not _is_remote_document_missing(str(exc)): + raise + payload = service.create_document_by_text( + dataset_id=dataset_id, + name=document.title, + text=text, + ) + remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id + remote_document_name = payload.get('document', {}).get('name') or document.title + else: + payload = service.create_document_by_text( + dataset_id=dataset_id, + name=document.title, + text=text, + ) + remote_document_id = payload.get('document', {}).get('id') or payload.get('id') + remote_document_name = payload.get('document', {}).get('name') or document.title + + if not remote_document_id: + raise KbDifySyncError('Dify 未返回远端文档 ID') + + record = ( + db.session.query(KbDifySyncRecord) + .filter( + KbDifySyncRecord.document_version_id == version.id, + KbDifySyncRecord.remote_document_id == remote_document_id, + ) + .first() + ) + if not record: + record = KbDifySyncRecord( + group_id=group.id, + document_id=document.id, + document_version_id=version.id, + dataset_id=dataset_id, + dataset_name=dataset_name, + remote_document_id=remote_document_id, + remote_document_name=remote_document_name, + status='synced', + sync_hash=sync_hash, + synced_by_id=synced_by_id, + ) + db.session.add(record) + else: + record.dataset_id = dataset_id + record.dataset_name = dataset_name + record.remote_document_name = remote_document_name + record.status = 'synced' + record.sync_hash = sync_hash + record.error_message = None + record.synced_by_id = synced_by_id + + record.synced_at = datetime.utcnow() + db.session.commit() + return { + 'dataset_id': dataset_id, + 'dataset_name': dataset_name, + 'remote_document_id': remote_document_id, + 'remote_document_name': remote_document_name, + 'sync_hash': sync_hash, + 'source_path': source_path, + } + + +def delete_document_from_dify(document_id: int) -> dict: + records = ( + db.session.query(KbDifySyncRecord) + .filter( + KbDifySyncRecord.document_id == document_id, + KbDifySyncRecord.remote_document_id.isnot(None), + KbDifySyncRecord.dataset_id.isnot(None), + ) + .order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc()) + .all() + ) + if not records: + return {'deleted': True, 'remote_document_count': 0} + + service = KbDifySyncService() + deleted_count = 0 + visited: set[tuple[str, str]] = set() + + for record in records: + key = (str(record.dataset_id), str(record.remote_document_id)) + if key in visited: + continue + visited.add(key) + try: + service.delete_document(dataset_id=key[0], document_id=key[1]) + except KbDifySyncError as exc: + if not _is_remote_document_missing(str(exc)): + raise + record.status = 'deleted' + record.error_message = None + record.synced_at = datetime.utcnow() + deleted_count += 1 + + db.session.commit() + return {'deleted': True, 'remote_document_count': deleted_count} diff --git a/backend/app/services/knowledge_cleaning/dify_sync_service.py.bak b/backend/app/services/knowledge_cleaning/dify_sync_service.py.bak new file mode 100644 index 00000000..b8a04ef0 --- /dev/null +++ b/backend/app/services/knowledge_cleaning/dify_sync_service.py.bak @@ -0,0 +1,242 @@ +""" +backend/app/services/knowledge_cleaning/dify_sync_service.py +文件用途:知识库文档版本到 Dify 的最小同步服务 +""" +from __future__ import annotations + +from datetime import datetime +import hashlib +from pathlib import Path + +import requests + +from app import db +from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup +from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings + + +class KbDifySyncError(RuntimeError): + pass + + +class KbDifySyncService: + def __init__(self) -> None: + settings = get_kb_dify_settings() + self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/') + self.api_key = str(settings.get('DIFY_API_KEY') or '').strip() + self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me') + self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality') + self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search') + self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model') + self.timeout = 60 + + def _headers(self) -> dict[str, str]: + if not self.base_url: + raise KbDifySyncError('DIFY_API_BASE 未配置') + if not self.api_key: + raise KbDifySyncError('DIFY_API_KEY 未配置') + return { + 'Authorization': f'Bearer {self.api_key}', + 'Content-Type': 'application/json', + } + + def _request(self, method: str, path: str, **kwargs): + url = f'{self.base_url}{path}' + try: + response = requests.request( + method, + url, + headers=self._headers(), + timeout=self.timeout, + **kwargs, + ) + except requests.RequestException as exc: + raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc + if response.status_code >= 400: + raise KbDifySyncError( + f'Dify API {method} {path} failed: {response.status_code} {response.text}' + ) + if response.status_code == 204: + return None + return response.json() + + def list_datasets(self) -> list[dict]: + payload = self._request('GET', '/datasets') + return payload.get('data', []) if isinstance(payload, dict) else [] + + def create_dataset(self, *, name: str, description: str | None) -> dict: + payload = { + 'name': name, + 'description': description or '', + 'permission': self.permission, + 'indexing_technique': self.indexing_technique, + 'doc_form': self.doc_form, + 'retrieval_model': { + 'search_method': self.search_method, + 'reranking_enable': False, + 'top_k': 3, + 'score_threshold_enabled': False, + 'score_threshold': None, + }, + } + return self._request('POST', '/datasets', json=payload) + + def ensure_dataset(self, group: KbGroup) -> tuple[str, str]: + if group.dify_dataset_id: + return group.dify_dataset_id, group.dify_dataset_name or group.name + + dataset_name = group.dify_dataset_name or group.name + existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None) + if existing: + group.dify_dataset_id = existing.get('id') + group.dify_dataset_name = existing.get('name') or dataset_name + db.session.commit() + return group.dify_dataset_id, group.dify_dataset_name + + created = self.create_dataset(name=dataset_name, description=group.description) + group.dify_dataset_id = created.get('id') + group.dify_dataset_name = created.get('name') or dataset_name + db.session.commit() + return group.dify_dataset_id, group.dify_dataset_name + + def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict: + payload = { + 'name': name, + 'text': text, + 'indexing_technique': self.indexing_technique, + 'doc_form': self.doc_form, + 'process_rule': {'mode': 'automatic'}, + } + return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload) + + def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict: + payload = { + 'name': name, + 'text': text, + 'process_rule': {'mode': 'automatic'}, + } + return self._request( + 'POST', + f'/datasets/{dataset_id}/documents/{document_id}/update-by-text', + json=payload, + ) + + +def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]: + candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path] + for value in candidate_paths: + if not value: + continue + path = Path(value) + if not path.exists(): + continue + text = path.read_text(encoding='utf-8', errors='ignore').strip() + if text: + return text, str(path) + raise KbDifySyncError('没有可用于同步的文本结果') + + +def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict: + version = db.session.get(KbDocumentVersion, document_version_id) + if not version or not version.document or not version.document.group: + raise KbDifySyncError('文档版本或关联分组不存在') + + group = version.document.group + document = version.document + text, source_path = _load_sync_text(version) + sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest() + + service = KbDifySyncService() + dataset_id, dataset_name = service.ensure_dataset(group) + + existing_record = ( + db.session.query(KbDifySyncRecord) + .filter( + KbDifySyncRecord.document_id == document.id, + KbDifySyncRecord.remote_document_id.isnot(None), + ) + .order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc()) + .first() + ) + + remote_document_id = None + remote_document_name = None + if existing_record and existing_record.sync_hash == sync_hash: + remote_document_id = existing_record.remote_document_id + remote_document_name = existing_record.remote_document_name + elif existing_record and existing_record.dataset_id == dataset_id: + try: + payload = service.update_document_by_text( + dataset_id=dataset_id, + document_id=existing_record.remote_document_id, + name=document.title, + text=text, + ) + except KbDifySyncError as exc: + error_text = str(exc) + remote_missing = ( + '404' in error_text + and ('Document not found' in error_text or '"code":"not_found"' in error_text) + ) + if not remote_missing: + raise + payload = service.create_document_by_text( + dataset_id=dataset_id, + name=document.title, + text=text, + ) + remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id + remote_document_name = payload.get('document', {}).get('name') or document.title + else: + payload = service.create_document_by_text( + dataset_id=dataset_id, + name=document.title, + text=text, + ) + remote_document_id = payload.get('document', {}).get('id') or payload.get('id') + remote_document_name = payload.get('document', {}).get('name') or document.title + + if not remote_document_id: + raise KbDifySyncError('Dify 未返回远端文档 ID') + + record = ( + db.session.query(KbDifySyncRecord) + .filter( + KbDifySyncRecord.document_version_id == version.id, + KbDifySyncRecord.remote_document_id == remote_document_id, + ) + .first() + ) + if not record: + record = KbDifySyncRecord( + group_id=group.id, + document_id=document.id, + document_version_id=version.id, + dataset_id=dataset_id, + dataset_name=dataset_name, + remote_document_id=remote_document_id, + remote_document_name=remote_document_name, + status='synced', + sync_hash=sync_hash, + synced_by_id=synced_by_id, + ) + db.session.add(record) + else: + record.dataset_id = dataset_id + record.dataset_name = dataset_name + record.remote_document_name = remote_document_name + record.status = 'synced' + record.sync_hash = sync_hash + record.error_message = None + record.synced_by_id = synced_by_id + + record.synced_at = datetime.utcnow() + db.session.commit() + return { + 'dataset_id': dataset_id, + 'dataset_name': dataset_name, + 'remote_document_id': remote_document_id, + 'remote_document_name': remote_document_name, + 'sync_hash': sync_hash, + 'source_path': source_path, + } diff --git a/backend/app/services/knowledge_cleaning/edkb_adapter.py b/backend/app/services/knowledge_cleaning/edkb_adapter.py new file mode 100644 index 00000000..fca8baef --- /dev/null +++ b/backend/app/services/knowledge_cleaning/edkb_adapter.py @@ -0,0 +1,88 @@ +""" +backend/app/services/knowledge_cleaning/edkb_adapter.py +文件用途:edkb_system 轻量适配层 +""" +from __future__ import annotations + +import shutil +import tempfile +from pathlib import Path + + +TEXT_EXTS = {'.txt', '.md'} + + +def _find_generated_markdown(output_root: Path) -> Path: + # Look for md files directly inside output_root or inside any of its subdirectories + # Note that edkb_system puts output inside a directory matching the parent dir name, which might be tmp_dir + candidates = [path for path in output_root.rglob('*.md') if not path.name.startswith('_')] + if not candidates: + raise RuntimeError('No markdown output produced by edkb_system.') + candidates.sort(key=lambda item: len(item.parts)) + return candidates[0] + + +def _write_text_result(source_path: Path, target_dir: Path) -> dict: + target_dir.mkdir(parents=True, exist_ok=True) + cleaned_path = target_dir / 'document.md' + content = source_path.read_text(encoding='utf-8', errors='ignore') + cleaned_path.write_text(content, encoding='utf-8') + return { + 'mode': 'plain_text', + 'cleaned_file_path': str(cleaned_path), + 'cleaned_preview_path': str(cleaned_path), + 'word_count': len(content.split()), + } + + +def build_clean_result(source_path: Path, target_dir: Path) -> dict: + """ + 优先产出真实文本结果: + - txt/md:直接抽取文本; + - 其它格式:尝试走 edkb_system; + - 失败时由调用方决定是否回退。 + """ + suffix = source_path.suffix.lower() + if suffix in TEXT_EXTS: + return _write_text_result(source_path, target_dir) + + from edkb_system.config import SystemConfig + from edkb_system.controller import build_knowledge + + target_dir.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix='edkb_', dir=str(target_dir.parent)) as tmp_dir: + tmp_root = Path(tmp_dir) + output_dir = tmp_root / 'output' + cache_dir = tmp_root / 'cache' + output_dir.mkdir(parents=True, exist_ok=True) + cache_dir.mkdir(parents=True, exist_ok=True) + + # IMPORTANT: copy the source file into tmp_root so that its parent directory is predictable + # edkb_system seems to output to output_dir / / .md + # ALSO IMPORTANT: ensure the file has its original suffix, otherwise edkb_system might fail or output nothing + original_name = getattr(source_path, "original_filename", None) + if not original_name: + original_name = source_path.name + if "." not in original_name and hasattr(source_path, "suffix_hint"): + original_name += source_path.suffix_hint + + tmp_source_path = tmp_root / original_name + shutil.copy2(source_path, tmp_source_path) + + config = SystemConfig.load(None) + result = build_knowledge(tmp_source_path, output_dir, config, cache_dir) + failures = [item for item in result if item.get('status') == 'failed'] + if failures: + raise RuntimeError(failures[0].get('error') or 'edkb_system failed.') + + markdown_source = _find_generated_markdown(output_dir) + cleaned_path = target_dir / 'document.md' + shutil.copy2(markdown_source, cleaned_path) + content = cleaned_path.read_text(encoding='utf-8', errors='ignore') + + return { + 'mode': 'edkb_system', + 'cleaned_file_path': str(cleaned_path), + 'cleaned_preview_path': str(cleaned_path), + 'word_count': len(content.split()), + } diff --git a/backend/app/services/knowledge_cleaning/queue_service.py b/backend/app/services/knowledge_cleaning/queue_service.py new file mode 100644 index 00000000..3385b6d6 --- /dev/null +++ b/backend/app/services/knowledge_cleaning/queue_service.py @@ -0,0 +1,63 @@ +""" +backend/app/services/knowledge_cleaning/queue_service.py +文件用途:知识库任务调度最小实现 +""" +from __future__ import annotations + +from flask import current_app + +from app import db +from app.models import KbJob + + +def enqueue_kb_job(job_id: int) -> tuple[bool, str]: + """ + 最小任务调度器: + - sync: 上传后立即在请求内执行; + - worker: 仅保留 queued,等待独立 worker 轮询; + - manual: 保留 queued,等待管理台手动执行。 + """ + mode = str(current_app.config.get('KB_TASK_EXECUTION_MODE', 'sync')).strip().lower() + + job = db.session.get(KbJob, job_id) + if not job: + return False, 'job_not_found' + + if mode == 'sync': + from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job + + if job.job_type == 'clean': + return run_clean_job(job_id) + if job.job_type == 'path_upload': + return run_path_upload_job(job_id) + return False, f'unsupported_sync_job:{job.job_type}' + + if mode == 'worker': + return True, 'queued_for_worker' + + return True, 'queued_manual' + + +def enqueue_clean_job(job_id: int) -> tuple[bool, str]: + return enqueue_kb_job(job_id) + + +def process_next_kb_job() -> tuple[bool, str]: + job = ( + db.session.query(KbJob) + .filter(KbJob.job_type.in_(('path_upload', 'clean')), KbJob.status == 'queued') + .order_by(KbJob.created_at.asc(), KbJob.id.asc()) + .first() + ) + if not job: + return False, 'no_job' + + from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job + + if job.job_type == 'path_upload': + return run_path_upload_job(job.id) + return run_clean_job(job.id) + + +def process_next_clean_job() -> tuple[bool, str]: + return process_next_kb_job() diff --git a/backend/app/services/knowledge_cleaning/settings_service.py b/backend/app/services/knowledge_cleaning/settings_service.py new file mode 100644 index 00000000..9f0d439a --- /dev/null +++ b/backend/app/services/knowledge_cleaning/settings_service.py @@ -0,0 +1,75 @@ +""" +backend/app/services/knowledge_cleaning/settings_service.py +文件用途:知识库 Dify 设置读写服务 +""" +from __future__ import annotations + +import os + +from flask import current_app + +from app import db +from app.env_persistence import persist_env_settings +from app.models import AppSetting, KbDifySyncRecord, KbGroup, KbJob, KbDocumentVersion + + +SETTING_DEFAULTS = { + 'DIFY_API_BASE': '', + 'DIFY_API_KEY': '', + 'KB_DIFY_PERMISSION': 'only_me', + 'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality', + 'KB_DIFY_SEARCH_METHOD': 'semantic_search', + 'KB_DIFY_DOC_FORM': 'text_model', +} + + +def _get_setting_value(key: str) -> str: + row = db.session.get(AppSetting, key) + if row and row.value is not None: + return row.value + config_value = current_app.config.get(key) + if config_value is not None: + return str(config_value) + return str(os.getenv(key, SETTING_DEFAULTS.get(key, ''))) + + +def get_kb_dify_settings() -> dict: + payload = {key: _get_setting_value(key) for key in SETTING_DEFAULTS} + payload['dify_api_configured'] = bool(payload.get('DIFY_API_KEY')) + return payload + + +def save_kb_dify_settings(values: dict[str, object]) -> dict: + allowed = {key: values[key] for key in SETTING_DEFAULTS if key in values} + persisted = persist_env_settings(allowed) + return { + **get_kb_dify_settings(), + **persisted, + 'dify_api_configured': bool((persisted.get('DIFY_API_KEY') or _get_setting_value('DIFY_API_KEY')).strip()), + } + + +def get_kb_dify_health_payload() -> dict: + settings = get_kb_dify_settings() + base_url = settings.get('DIFY_API_BASE') or '' + api_key = settings.get('DIFY_API_KEY') or '' + + payload = { + 'dify_base_url': base_url, + 'dify_api_configured': bool(api_key), + 'api': { + 'configured': bool(api_key), + 'reachable': False, + 'dataset_count': None, + 'error': None, + }, + 'local_sync_health': { + 'dataset_bound_groups': db.session.query(KbGroup).filter(KbGroup.dify_dataset_id.isnot(None)).count(), + 'sync_records': db.session.query(KbDifySyncRecord).count(), + 'syncing_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'syncing').count(), + 'synced_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'synced').count(), + 'failed_sync_records': db.session.query(KbDifySyncRecord).filter(KbDifySyncRecord.status == 'failed').count(), + 'pending_sync_jobs': db.session.query(KbJob).filter(KbJob.job_type == 'sync_dify', KbJob.status == 'queued').count(), + }, + } + return payload diff --git a/backend/app/services/knowledge_cleaning/tasks.py b/backend/app/services/knowledge_cleaning/tasks.py new file mode 100644 index 00000000..650f560d --- /dev/null +++ b/backend/app/services/knowledge_cleaning/tasks.py @@ -0,0 +1,471 @@ +""" +backend/app/services/knowledge_cleaning/tasks.py +文件用途:知识库任务执行第一版 +""" +from __future__ import annotations + +from datetime import datetime +import hashlib +from pathlib import Path +import shutil +import zipfile + +from flask import current_app +from app import db +from app.models import KbDocument, KbDocumentVersion, KbJob +from app.services.knowledge_cleaning.edkb_adapter import build_clean_result +from app.services.knowledge_cleaning.dify_sync_service import ( + KbDifySyncError, + sync_document_version_to_dify, +) +from werkzeug.utils import secure_filename + + +def _utc_now() -> datetime: + return datetime.utcnow() + + +def _infer_missing_extension(source_path: Path) -> str: + if zipfile.is_zipfile(source_path): + try: + with zipfile.ZipFile(source_path) as archive: + names = archive.namelist() + except Exception: + names = [] + if any(name.startswith('xl/') for name in names): + return '.xlsx' + if any(name.startswith('word/') for name in names): + return '.docx' + if any(name.startswith('ppt/') for name in names): + return '.pptx' + return '.zip' + + try: + header = source_path.read_bytes()[:8] + except Exception: + return '' + if header.startswith(b'\xd0\xcf\x11\xe0'): + return '.xls' + return '' + + +def _normalized_source_filename(version: KbDocumentVersion, source_path: Path) -> str: + raw_name = Path(version.source_file_name or source_path.name).name + if Path(raw_name).suffix: + return raw_name + + ext = version.source_file_ext + if ext: + normalized_ext = ext if str(ext).startswith('.') else f'.{ext}' + else: + normalized_ext = _infer_missing_extension(source_path) + + return f'{raw_name}{normalized_ext}' if normalized_ext else raw_name + + +def _hash_file(source_path: Path) -> tuple[str, int]: + sha = hashlib.sha256() + size = 0 + with source_path.open('rb') as handle: + while True: + chunk = handle.read(1024 * 1024) + if not chunk: + break + sha.update(chunk) + size += len(chunk) + return sha.hexdigest(), size + + +def _safe_storage_filename(filename: str) -> str: + candidate = Path(filename or '').name.strip() + if not candidate: + return 'uploaded_file' + safe_stem = secure_filename(Path(candidate).stem) or 'uploaded_file' + suffix = Path(candidate).suffix.lower() + return f'{safe_stem}{suffix}' + + +def _kb_storage_root() -> Path: + root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve() + root.mkdir(parents=True, exist_ok=True) + return root + + +def _get_or_create_document(*, group_id: int, title: str, description: str | None, user_id: int | None) -> KbDocument: + document = ( + db.session.query(KbDocument) + .filter(KbDocument.group_id == group_id, KbDocument.title == title) + .first() + ) + if document and document.is_deleted: + document.is_deleted = False + if document: + document.description = description + document.updated_by_id = user_id + return document + + document = KbDocument( + group_id=group_id, + title=title, + description=description, + status='draft', + source_type='upload', + created_by_id=user_id, + updated_by_id=user_id, + ) + db.session.add(document) + db.session.flush() + return document + + +def _find_existing_active_document(*, group_id: int, title: str) -> KbDocument | None: + return ( + db.session.query(KbDocument) + .filter( + KbDocument.group_id == group_id, + KbDocument.title == title, + KbDocument.is_deleted.is_(False), + ) + .first() + ) + + +def _next_version_no(document: KbDocument) -> int: + versions = list(getattr(document, 'versions', []) or []) + if not versions: + return 1 + return max(item.version_no for item in versions) + 1 + + +def _register_document_version_from_staged_file( + *, + group_id: int, + relative_path: str, + staged_path: Path, + original_name: str, + user_id: int | None, +) -> tuple[KbDocument, KbDocumentVersion, KbJob]: + display_name = Path(original_name or relative_path).name or Path(relative_path).name or 'uploaded_file' + if _find_existing_active_document(group_id=group_id, title=display_name): + raise FileExistsError('上传失败,文件已存在') + document = _get_or_create_document( + group_id=group_id, + title=display_name, + description=display_name, + user_id=user_id, + ) + version_no = _next_version_no(document) + source_file_name = _safe_storage_filename(original_name) + ext = Path(source_file_name).suffix.lower().lstrip('.') or None + version_dir = _kb_storage_root() / f'group_{group_id:04d}' / f'document_{document.id:06d}' / f'v{version_no:03d}' + version_dir.mkdir(parents=True, exist_ok=True) + target_path = version_dir / source_file_name + shutil.copy2(staged_path, target_path) + sha256, file_size = _hash_file(target_path) + + for existing in document.versions: + if existing.is_current: + existing.is_current = False + + version = KbDocumentVersion( + document_id=document.id, + version_no=version_no, + status='uploaded', + is_current=True, + source_file_name=source_file_name, + source_file_path=str(target_path), + source_file_ext=ext, + source_file_size=file_size, + sha256=sha256, + uploaded_by_id=user_id, + ) + db.session.add(version) + db.session.flush() + + document.source_type = 'upload' + document.status = 'uploaded' + document.updated_by_id = user_id + + upload_job = KbJob( + job_type='upload', + status='success', + group_id=group_id, + document_id=document.id, + document_version_id=version.id, + progress=100, + message=f'已通过上传路径导入文件:{relative_path}', + payload_json={ + 'source_file_name': source_file_name, + 'relative_path': relative_path, + 'source_file_size': file_size, + }, + result_json={ + 'sha256': sha256, + 'stored_path': str(target_path), + }, + created_by_id=user_id, + started_at=version.created_at, + finished_at=version.created_at, + ) + clean_job = KbJob( + job_type='clean', + status='queued', + group_id=group_id, + document_id=document.id, + document_version_id=version.id, + progress=0, + message='等待清洗任务执行', + payload_json={ + 'document_version_id': version.id, + 'source_file_name': source_file_name, + 'relative_path': relative_path, + }, + created_by_id=user_id, + ) + db.session.add(upload_job) + db.session.add(clean_job) + db.session.commit() + + from app.services.knowledge_cleaning.queue_service import enqueue_clean_job + + enqueue_clean_job(clean_job.id) + return document, version, clean_job + + +def run_path_upload_job(job_id: int) -> tuple[bool, str]: + job = db.session.get(KbJob, job_id) + if not job: + return False, '任务不存在' + if job.job_type != 'path_upload': + return False, '当前任务不是 path_upload 类型' + + payload = dict(job.payload_json or {}) + items = list(payload.get('files') or []) + total = max(int(payload.get('total_files') or len(items) or 0), 1) + result = dict(job.result_json or {}) + result.setdefault('total', total) + result.setdefault('success', 0) + result.setdefault('failed', 0) + result.setdefault('staged', len(items)) + + job.status = 'running' + job.progress = min(job.progress or 0, 5) + job.message = '后台开始批量导入上传路径文件' + job.started_at = job.started_at or _utc_now() + db.session.commit() + + success_count = 0 + fail_count = 0 + processed = 0 + + for item in items: + if item.get('status') in ('success', 'failed'): + processed += 1 + if item.get('status') == 'success': + success_count += 1 + else: + fail_count += 1 + continue + + staged_path = Path(str(item.get('staged_path') or '')) + item['status'] = 'uploading' + item['error'] = None + payload['current_file'] = item.get('relative_path') or item.get('original_name') + job.payload_json = payload + job.message = f'正在导入:{payload["current_file"]}' + db.session.commit() + + try: + if not staged_path.exists(): + raise FileNotFoundError('暂存文件不存在') + + document, version, _clean_job = _register_document_version_from_staged_file( + group_id=job.group_id, + relative_path=str(item.get('relative_path') or item.get('original_name') or staged_path.name), + staged_path=staged_path, + original_name=str(item.get('original_name') or staged_path.name), + user_id=job.created_by_id, + ) + item['status'] = 'success' + item['document_id'] = document.id + item['version_id'] = version.id + item['error'] = None + success_count += 1 + except Exception as exc: + item['status'] = 'failed' + item['error'] = str(exc) + fail_count += 1 + + processed += 1 + result['success'] = success_count + result['failed'] = fail_count + result['processed'] = processed + result['items'] = items + job.payload_json = payload + job.result_json = result + job.progress = min(int(processed * 100 / total), 100) + db.session.commit() + + payload['current_file'] = '' + job.payload_json = payload + job.result_json = result + job.progress = 100 + job.finished_at = _utc_now() + if fail_count > 0: + job.status = 'failed' + job.message = f'路径上传完成,成功 {success_count} 条,失败 {fail_count} 条' + job.error_message = f'部分文件上传失败:{fail_count} 条' + db.session.commit() + return False, 'partial_failed' + + job.status = 'success' + job.message = f'路径上传完成,成功 {success_count} 条' + job.error_message = None + db.session.commit() + return True, 'ok' + + +def run_clean_job(job_id: int) -> tuple[bool, str]: + """ + 第一版最小清洗任务执行器。 + 当前先不接 edkb_system,只做以下动作: + 1. 把 queued 的 clean 任务改为 running/success; + 2. 为版本生成 cleaned_preview_path; + 3. 更新版本状态为 cleaned; + 4. 为下一步接真实清洗链路预留结构。 + """ + job = db.session.get(KbJob, job_id) + if not job: + return False, '任务不存在' + if job.job_type != 'clean': + return False, '当前任务不是 clean 类型' + + version = db.session.get(KbDocumentVersion, job.document_version_id) + if not version: + job.status = 'failed' + job.error_message = '关联文档版本不存在' + job.finished_at = _utc_now() + db.session.commit() + return False, '关联文档版本不存在' + + source_path = Path(version.source_file_path) + if not source_path.exists(): + job.status = 'failed' + job.error_message = '原始文件不存在,无法执行 clean' + version.status = 'failed' + version.error_message = '原始文件不存在,无法执行 clean' + job.finished_at = _utc_now() + db.session.commit() + return False, '原始文件不存在' + + job.status = 'running' + job.progress = 20 + job.message = '开始执行最小清洗任务' + job.started_at = _utc_now() + version.status = 'processing' + db.session.commit() + + target_dir = source_path.parent + warnings = [] + + try: + normalized_name = _normalized_source_filename(version, source_path) + staged_source = target_dir / normalized_name + if staged_source != source_path: + shutil.copy2(source_path, staged_source) + source_path = staged_source + + result = build_clean_result(source_path, target_dir) + job_message = '真实清洗结果已生成' + except Exception as exc: + preview_path = target_dir / f'{_normalized_source_filename(version, source_path)}.preview.txt' + preview_path.write_text( + '\n'.join([ + f'source_file={source_path.name}', + f'source_size={version.source_file_size or 0}', + 'clean_status=placeholder_success', + f'fallback_reason={str(exc)}', + ]), + encoding='utf-8', + ) + result = { + 'mode': 'placeholder_clean', + 'cleaned_file_path': None, + 'cleaned_preview_path': str(preview_path), + 'word_count': 0, + } + warnings.append({'message': f'edkb_fallback={str(exc)}'}) + job_message = 'edkb_system 未就绪,已回退到占位清洗结果' + + version.cleaned_file_path = result.get('cleaned_file_path') + version.cleaned_preview_path = result.get('cleaned_preview_path') + version.word_count = int(result.get('word_count') or 0) + version.status = 'cleaned' + version.converted_at = _utc_now() + version.error_message = None + version.warnings_json = warnings or None + if version.document: + version.document.status = 'ready' + + job.status = 'success' + job.progress = 100 + job.message = job_message + job.error_message = None + job.result_json = result + job.finished_at = _utc_now() + db.session.commit() + + return True, 'ok' + + +def run_sync_job(job_id: int) -> tuple[bool, str]: + job = db.session.get(KbJob, job_id) + if not job: + return False, '任务不存在' + if job.job_type != 'sync_dify': + return False, '当前任务不是 sync_dify 类型' + + version = db.session.get(KbDocumentVersion, job.document_version_id) + if not version: + job.status = 'failed' + job.error_message = '关联文档版本不存在' + job.finished_at = _utc_now() + db.session.commit() + return False, '关联文档版本不存在' + + job.status = 'running' + job.progress = 20 + job.message = '开始同步到 Dify' + job.started_at = _utc_now() + db.session.commit() + + try: + result = sync_document_version_to_dify(version.id, synced_by_id=job.created_by_id) + except KbDifySyncError as exc: + version.status = 'ready' + job.status = 'failed' + job.progress = 100 + job.error_message = str(exc) + job.message = '同步到 Dify 失败' + job.finished_at = _utc_now() + db.session.commit() + return False, str(exc) + except Exception as exc: + version.status = 'ready' + job.status = 'failed' + job.progress = 100 + job.error_message = f'同步到 Dify 时发生未预期错误:{exc}' + job.message = '同步到 Dify 失败' + job.finished_at = _utc_now() + db.session.commit() + return False, str(exc) + + version.status = 'synced' + job.status = 'success' + job.progress = 100 + job.message = '已同步到 Dify' + job.error_message = None + job.result_json = result + job.finished_at = _utc_now() + db.session.commit() + return True, 'ok' diff --git a/backend/app/services/text2sql.py b/backend/app/services/text2sql.py index 0eb22d1d..ff86e263 100644 --- a/backend/app/services/text2sql.py +++ b/backend/app/services/text2sql.py @@ -2,13 +2,13 @@ import json import os import re import time -from flask import current_app, has_app_context +from pathlib import Path +from flask import current_app class Text2SQLService: _schema_text = None - _oracle_client_init_attempted = False - _oracle_client_init_error = None - _oracle_client_mode = "unknown" + _oracle_client_initialized = False + _jdbc_driver_url = "https://repo1.maven.org/maven2/com/oracle/database/jdbc/ojdbc8/19.25.0.0/ojdbc8-19.25.0.0.jar" @staticmethod def _backend_dir() -> str: @@ -151,6 +151,122 @@ class Text2SQLService: text = (error_message or "").upper() return any(code in text for code in ("ORA-00904", "ORA-00942", "INVALID IDENTIFIER", "TABLE OR VIEW DOES NOT EXIST")) + @classmethod + def _get_oracle_client_dir(cls) -> str | None: + env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip() + if env_dir and os.path.exists(env_dir): + return env_dir + + linux_candidates = [ + "/opt/oracle/instantclient", + "/opt/oracle/instantclient_19_28", + "/opt/oracle/instantclient_19_27", + ] + for path in linux_candidates: + if os.path.exists(path): + return path + + return cls._find_oracle_client_dir() + + @classmethod + def _init_oracle_client(cls, oracledb) -> None: + if cls._oracle_client_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)(): + return + + import platform + import shutil + import tempfile + + target_lib_dir = cls._get_oracle_client_dir() + + if platform.system() == 'Windows' and target_lib_dir: + # OCI C-library fails to load if path contains non-ASCII. + if not target_lib_dir.isascii(): + temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client') + safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir)) + if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir): + os.makedirs(temp_dir, exist_ok=True) + shutil.copytree(target_lib_dir, safe_lib_dir) + target_lib_dir = safe_lib_dir + + if target_lib_dir: + oracledb.init_oracle_client(lib_dir=target_lib_dir) + else: + oracledb.init_oracle_client() + cls._oracle_client_initialized = True + + @classmethod + def _jdbc_dir(cls) -> Path: + return Path(cls._backend_dir()) / "jdbc" + + @classmethod + def _ensure_jdbc_driver_jar(cls) -> str: + env_path = (os.getenv("ERP_JDBC_JAR") or "").strip() + if env_path and os.path.exists(env_path): + return env_path + + jar_dir = cls._jdbc_dir() + jar_dir.mkdir(parents=True, exist_ok=True) + jar_path = jar_dir / "ojdbc8-19.25.0.0.jar" + if jar_path.exists(): + return str(jar_path) + + import requests + + driver_url = os.getenv("ERP_JDBC_JAR_URL", cls._jdbc_driver_url).strip() or cls._jdbc_driver_url + with requests.get(driver_url, stream=True, timeout=120) as resp: + resp.raise_for_status() + with open(jar_path, "wb") as f: + for chunk in resp.iter_content(chunk_size=1024 * 256): + if chunk: + f.write(chunk) + return str(jar_path) + + @staticmethod + def _dsn_to_jdbc_url(dsn: str) -> str: + dsn = (dsn or "").strip() + if not dsn: + raise ValueError("ERP_DB_DSN is empty") + if dsn.startswith("jdbc:oracle:thin:@"): + return dsn + if dsn.startswith("("): + return f"jdbc:oracle:thin:@{dsn}" + match = re.match(r"^(?P[^:/]+)(?::(?P\d+))?/(?P.+)$", dsn) + if match: + host = match.group("host") + port = match.group("port") or "1521" + service = match.group("service") + return f"jdbc:oracle:thin:@//{host}:{port}/{service}" + return f"jdbc:oracle:thin:@{dsn}" + + @classmethod + def _execute_sql_via_jdbc(cls, sql: str, user: str, password: str, dsn: str): + import jaydebeapi + + jar_path = cls._ensure_jdbc_driver_jar() + jdbc_url = cls._dsn_to_jdbc_url(dsn) + connection = jaydebeapi.connect( + "oracle.jdbc.OracleDriver", + jdbc_url, + { + "user": user, + "password": password, + "oracle.jdbc.timezoneAsRegion": "false", + }, + jar_path, + ) + cursor = connection.cursor() + try: + cursor.execute(sql) + columns = [col[0] for col in cursor.description] if cursor.description else [] + rows = cursor.fetchall() if columns else [] + return columns, rows + finally: + try: + cursor.close() + finally: + connection.close() + @classmethod def get_schema(cls): if cls._schema_text is None: @@ -392,9 +508,14 @@ class Text2SQLService: user = "EXT_VIEW_USER" password = "extviewuser" - dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod") - - cls._ensure_oracle_client_initialized(oracledb) + dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod") + + try: + # Old ERP Oracle versions require python-oracledb thick mode. + cls._init_oracle_client(oracledb) + except Exception as e: + if current_app: + current_app.logger.warning(f"Failed to init thick mode: {e}") try: connection = oracledb.connect(user=user, password=password, dsn=dsn) @@ -409,7 +530,15 @@ class Text2SQLService: return columns, rows except Exception as e: - return ["Error"], [[cls._format_connection_error(str(e))]] + error_text = str(e) + if current_app: + current_app.logger.warning(f"Oracle direct query failed, trying JDBC fallback: {error_text}") + if "DPY-3010" in error_text or "DPI-1047" in error_text: + try: + return cls._execute_sql_via_jdbc(sql, user, password, dsn) + except Exception as jdbc_error: + return ["Error"], [[f"{error_text} | JDBC fallback failed: {jdbc_error}"]] + return ["Error"], [[error_text]] @classmethod def format_result(cls, columns, rows, sql, original_query): diff --git a/backend/data/kb/group_0003/document_000009/v001/integration.txt b/backend/data/kb/group_0003/document_000009/v001/integration.txt new file mode 100644 index 00000000..9a93df0c --- /dev/null +++ b/backend/data/kb/group_0003/document_000009/v001/integration.txt @@ -0,0 +1 @@ +integration smoke text \ No newline at end of file diff --git a/backend/deploy/gunicorn_config.py b/backend/deploy/gunicorn_config.py index 5ae89301..361b2a15 100644 --- a/backend/deploy/gunicorn_config.py +++ b/backend/deploy/gunicorn_config.py @@ -37,5 +37,6 @@ daemon = False # 进程名称 proc_name = "hxops_backend" -# 预加载应用 (加快启动速度) -preload_app = True +# 应用启动时会访问数据库加载持久化配置;预加载会让主进程先建立连接再 fork, +# 导致 worker 继承损坏的数据库连接。 +preload_app = False diff --git a/backend/edkb_system/__init__.py b/backend/edkb_system/__init__.py new file mode 100644 index 00000000..96607c16 --- /dev/null +++ b/backend/edkb_system/__init__.py @@ -0,0 +1 @@ +"""Enterprise KB Skill System orchestrator package.""" diff --git a/backend/edkb_system/cli.py b/backend/edkb_system/cli.py new file mode 100644 index 00000000..cc7fbc01 --- /dev/null +++ b/backend/edkb_system/cli.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import typer + +from edkb_system.config import SystemConfig +from edkb_system.contracts import Context +from edkb_system.controller import build_knowledge +from edkb_system.skills import ( + flow_reconstruct, + loader_excel, + loader_pdf, + table_linearize, +) + +app = typer.Typer(help="Enterprise KB multi-skill orchestrator") + + +def _write_failed_files_report(out_dir: Path, failed: list[dict]) -> tuple[Path, Path]: + txt_path = out_dir / "_failed_files.txt" + json_path = out_dir / "_failed_files.json" + if not failed: + for p in [txt_path, json_path]: + if p.exists(): + p.unlink() + return txt_path, json_path + + out_dir.mkdir(parents=True, exist_ok=True) + lines: list[str] = [] + payload: list[dict] = [] + for idx, item in enumerate(failed, start=1): + file_name = str(item.get("file") or "unknown").strip() or "unknown" + reason = str(item.get("error") or "unknown error") + elapsed_ms = int(item.get("elapsed_ms") or 0) + elapsed_s = f"{elapsed_ms / 1000:.3f}s" + is_timeout = "timed out" in reason.lower() + payload.append( + { + "index": idx, + "file": file_name, + "reason": reason, + "elapsed_ms": elapsed_ms, + "timed_out": is_timeout, + } + ) + lines.extend( + [ + f"[{idx}] {file_name}", + f"reason: {reason}", + f"elapsed: {elapsed_s}", + f"timed_out: {'true' if is_timeout else 'false'}", + "", + ] + ) + + txt_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8") + json_path.write_text( + json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + return txt_path, json_path + + +@app.command("build") +def build_cmd( + input_path: str = typer.Argument(..., metavar="PATH"), + out: str = typer.Option(..., "--out"), + config: str | None = typer.Option(None, "--config"), + skip: list[str] | None = typer.Option( + None, + "--skip", + help="Skip files by glob pattern (match name or relative path, repeatable)", + ), + resume: bool = typer.Option( + False, + "--resume/--no-resume", + help="Skip files whose target markdown already exists", + ), + prune_stale: bool = typer.Option( + False, + "--prune-stale/--keep-stale", + help="Remove stale markdown/intermediate leftovers in output before build", + ), +) -> None: + cfg = SystemConfig.load(config) + root = Path(__file__).resolve().parents[2] + temp_dir = root / "work" / "cache" + in_path = Path(input_path) + if not in_path.exists(): + typer.echo(f"Input path not found: {in_path}") + typer.echo("Create the folder and put documents in it, e.g. work/input") + raise typer.Exit(code=2) + results = build_knowledge( + in_path, + Path(out), + cfg, + temp_dir, + skip_patterns=skip or [], + resume=resume, + prune_stale_output=prune_stale, + ) + ok = [r for r in results if r.get("status") == "success"] + failed = [r for r in results if r.get("status") == "failed"] + skipped = [r for r in results if r.get("status") == "skipped"] + typer.echo( + "Completed files: " + f"{len(results)} (success={len(ok)}, failed={len(failed)}, skipped={len(skipped)})" + ) + if failed: + txt_path, json_path = _write_failed_files_report(Path(out), failed) + for r in failed: + file_name = str(r.get("file", "")).strip() or "unknown" + reason = str(r.get("error") or "unknown error") + typer.echo(f"- Failed: {file_name}") + typer.echo(f" - reason: {reason}") + typer.echo(f"- Failed list: {txt_path}") + typer.echo(f"- Failed json: {json_path}") + else: + _write_failed_files_report(Path(out), []) + typer.echo(f"- Output dir: {Path(out)}") + + +@app.command("inspect-flow") +def inspect_flow_cmd( + file: str = typer.Argument(..., metavar="FILE"), + out: str = typer.Option(..., "--out"), +) -> None: + ctx = Context(file_type="pdf") + blocks = loader_pdf.run({"file_path": file}, ctx) + data = flow_reconstruct.run(blocks, ctx) + out_dir = Path(out) + out_dir.mkdir(parents=True, exist_ok=True) + (out_dir / "inspect_flow.md").write_text( + "\n\n".join(data.get("flow_markdowns", [])), encoding="utf-8" + ) + (out_dir / "inspect_flow_debug.json").write_text( + json.dumps(data.get("debug", []), ensure_ascii=False, indent=2), + encoding="utf-8", + ) + typer.echo("inspect-flow done") + + +@app.command("inspect-excel") +def inspect_excel_cmd( + file: str = typer.Argument(..., metavar="FILE"), + out: str = typer.Option(..., "--out"), +) -> None: + ctx = Context(file_type="xlsx") + tables = loader_excel.run({"file_path": file, "work_dir": str(Path(out))}, ctx) + md = table_linearize.run(tables, ctx) + out_dir = Path(out) + out_dir.mkdir(parents=True, exist_ok=True) + (out_dir / "inspect_excel.md").write_text(md, encoding="utf-8") + (out_dir / "inspect_excel_schema.json").write_text( + json.dumps( + [{"sheet": t.get("sheet"), "headers": t.get("headers")} for t in tables], + ensure_ascii=False, + indent=2, + ), + encoding="utf-8", + ) + typer.echo("inspect-excel done") + + +if __name__ == "__main__": + app() diff --git a/backend/edkb_system/config.py b/backend/edkb_system/config.py new file mode 100644 index 00000000..6c84687d --- /dev/null +++ b/backend/edkb_system/config.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +import json +from pathlib import Path + +from pydantic import BaseModel, Field + + +class RouterConfig(BaseModel): + scan_likelihood_threshold: float = 0.6 + flow_likelihood_threshold: float = 0.5 + table_likelihood_threshold: float = 0.5 + + +class OCRConfig(BaseModel): + enable: bool = True + engine: str = "rapidocr" + min_confidence: float = 0.3 + + +class ChunkConfig(BaseModel): + enable: bool = True + max_chars: int = 1200 + overlap_chars: int = 150 + add_heading_path_prefix: bool = True + + +class CleanConfig(BaseModel): + dedup_min_repeats: int = 3 + merge_short_line_chars: int = 15 + + +class SystemConfig(BaseModel): + router: RouterConfig = Field(default_factory=RouterConfig) + ocr: OCRConfig = Field(default_factory=OCRConfig) + chunk: ChunkConfig = Field(default_factory=ChunkConfig) + clean: CleanConfig = Field(default_factory=CleanConfig) + + @classmethod + def load(cls, path: str | None) -> "SystemConfig": + if not path: + return cls() + p = Path(path) + raw = p.read_text(encoding="utf-8") + if p.suffix.lower() in {".yaml", ".yml"}: + import yaml + + data = yaml.safe_load(raw) or {} + elif p.suffix.lower() == ".json": + data = json.loads(raw) + else: + raise ValueError("config only supports yaml/yml/json") + return cls.model_validate(data) diff --git a/backend/edkb_system/contracts.py b/backend/edkb_system/contracts.py new file mode 100644 index 00000000..4c2bdcac --- /dev/null +++ b/backend/edkb_system/contracts.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + + +@dataclass +class Block: + id: str + page: int + type: str + text: str + bbox: tuple[float, float, float, float] + meta: dict[str, Any] = field(default_factory=dict) + + def cx(self) -> float: + return (self.bbox[0] + self.bbox[2]) / 2.0 + + def cy(self) -> float: + return (self.bbox[1] + self.bbox[3]) / 2.0 + + +@dataclass +class Chunk: + id: str + heading_path: str + text: str + index: int + source: str + + +@dataclass +class Context: + file_type: str = "" + pages: int = 0 + images: int = 0 + ocr_characters: int = 0 + flows_detected: int = 0 + warnings: list[str] = field(default_factory=list) + confidence: float = 1.0 + extras: dict[str, Any] = field(default_factory=dict) + + +@dataclass +class DocumentProfile: + file_type: str + text_density: float + has_images: bool + has_tables: bool + flow_likelihood: float + scan_likelihood: float + table_likelihood: float + language_hint: str + recommended_pipeline: list[str] diff --git a/backend/edkb_system/controller.py b/backend/edkb_system/controller.py new file mode 100644 index 00000000..2e9b2b83 --- /dev/null +++ b/backend/edkb_system/controller.py @@ -0,0 +1,893 @@ +from __future__ import annotations + +import json +import fnmatch +import multiprocessing as mp +import os +import re +import shutil +import time +import traceback +from pathlib import Path + +from edkb_system.config import SystemConfig +from edkb_system.contracts import Context +from edkb_system.discovery import discover +from edkb_system.skills import ( + chunk, + clean, + doc_to_pdf, + export, + flow_reconstruct, + intake_router, + loader_csv, + loader_docx, + loader_excel, + loader_pdf, + loader_pptx, + ocr, + postcheck, + quality_gate, + table_linearize, +) +from edkb_system.skills.common import blocks_to_plain_markdown +from edkb_system.skills.word_bridge import _kill_winword_pids, _list_winword_pids + + +_STEP_ALIAS = { + "edkb-intake-router": "route", + "edkb-loader-docx": "docx", + "edkb-doc-to-pdf": "doc2pdf", + "edkb-loader-pdf": "pdf", + "edkb-loader-pptx": "pptx", + "edkb-loader-excel": "excel", + "edkb-loader-csv": "csv", + "edkb-ocr": "ocr", + "edkb-flow-reconstruct": "flow", + "edkb-table-linearize": "table", + "edkb-clean": "clean", + "edkb-chunk": "chunk", + "edkb-quality-gate": "qgate", + "edkb-export": "export", + "edkb-postcheck": "check", +} + + +def _step_alias(step: str) -> str: + return _STEP_ALIAS.get(step, step.replace("edkb-", "")) + + +def _extract_doc_header_from_flow(flow_mds: list[str]) -> str | None: + if not flow_mds: + return None + for line in "\n".join(flow_mds).splitlines(): + if "文件编号" not in line or "文件级别" not in line or "版本" not in line: + continue + s = " ".join(line.split()) + m = re.search(r"文件编号\s*(\S+)\s*文件级别\s*(\S+)\s*版本\s*(\S+)", s) + if m: + return f"文件编号 {m.group(1)} 文件级别 {m.group(2)} 版本 {m.group(3)}" + return None + + +def _inject_doc_header_from_flow(text: str, flow_mds: list[str]) -> str: + if "文件编号" in text: + return text + meta = _extract_doc_header_from_flow(flow_mds) + if not meta: + return text + if text.startswith("制定部门"): + i = text.find("\n") + if i >= 0: + return text[: i + 1] + meta + "\n" + text[i + 1 :] + return meta + "\n" + text + + +def _inject_source_title_if_missing(text: str, source_stem: str) -> str: + if not source_stem: + return text + preview = "\n".join(text.splitlines()[:20]) + norm_preview = re.sub(r"\s+", "", preview) + norm_source = re.sub(r"\s+", "", source_stem) + if norm_source in norm_preview: + return text + return source_stem + "\n" + text + + +def _promote_title_above_meta(text: str) -> str: + lines = text.splitlines() + if len(lines) < 2: + return text + + first_idx = next((i for i, x in enumerate(lines) if x.strip()), None) + if first_idx is None: + return text + second_idx = next( + (i for i in range(first_idx + 1, len(lines)) if lines[i].strip()), None + ) + if second_idx is None: + return text + + first = lines[first_idx].strip() + second = lines[second_idx].strip() + if "文件编号" not in first: + return text + if ( + re.match(r"^[一二三四五六七八九十]+、", second) + or second.startswith("制定部门") + or second.startswith("文件修订履历") + or "文件编号" in second + ): + return text + if len(second) > 80: + return text + + lines[first_idx], lines[second_idx] = lines[second_idx], lines[first_idx] + return "\n".join(lines) + + +def _promote_dept_header_near_top(text: str) -> str: + lines = text.splitlines() + pat = re.compile(r"制定部门.+制/修订日期.+页码\s*\d+\s*/\s*\d+") + idx = next( + (i for i, ln in enumerate(lines) if pat.search(" ".join(ln.split()))), None + ) + if idx is None or idx <= 4: + return text + + line = lines.pop(idx) + insert_at = 1 + for i, ln in enumerate(lines[:6]): + if ln.strip().startswith("文件编号"): + insert_at = i + 1 + break + lines.insert(insert_at, line) + return "\n".join(lines) + + +def _ocr_payload_map(blocks: list) -> dict[str, str]: + out: dict[str, str] = {} + for b in blocks: + if getattr(b, "type", "") != "ocr_text" or not str( + getattr(b, "id", "") + ).startswith("ocr-"): + continue + txt = (getattr(b, "text", "") or "").strip() + if txt.startswith("OCR_TEXT:"): + txt = txt[len("OCR_TEXT:") :].strip() + txt = re.sub(r"(?m)^\s*-\s*", "", txt) + txt = " ".join(x.strip() for x in txt.splitlines() if x.strip()) + if txt and txt != "": + out[str(b.id)[len("ocr-") :]] = txt + return out + + +def _has_non_flow_image_content(blocks: list) -> bool: + img_ids = [str(b.id) for b in blocks if getattr(b, "type", "") == "image"] + if not img_ids: + return False + ocr_map = _ocr_payload_map(blocks) + info_kw = re.compile(r"分数值|频繁程度|严重性|LEC|评分基准|风险积分|事故发生") + flow_kw = re.compile(r"备料|取样|资料确认|品质检验|判定|产品出货|NG|OK|不合格品") + + for iid in img_ids: + payload = ocr_map.get(iid, "") + if not payload: + continue + if info_kw.search(payload): + return True + if len(payload) >= 80 and len(flow_kw.findall(payload)) <= 2: + return True + return False + + +def _derive_source_category(file_path: Path, input_path: Path) -> str: + if input_path.is_dir(): + try: + rel = file_path.relative_to(input_path) + if len(rel.parts) >= 2: + return rel.parts[0] + return input_path.name or "uncategorized" + except Exception: + return file_path.parent.name or "uncategorized" + return input_path.parent.name or "uncategorized" + + +def _derive_output_rel_md(file_path: Path, input_path: Path) -> Path: + if input_path.is_dir(): + try: + rel = file_path.relative_to(input_path) + except Exception: + rel = Path(file_path.name) + if len(rel.parts) == 1: + root_name = input_path.name + if root_name and root_name.lower() not in {"input", "work"}: + rel = Path(root_name) / rel + else: + parent_name = file_path.parent.name + if parent_name and parent_name.lower() not in {"input", "work"}: + rel = Path(parent_name) / file_path.name + else: + rel = Path(file_path.name) + return rel.with_suffix(".md") + + +def _normalize_path_for_match(p: Path | str) -> str: + return str(p).replace("\\", "/") + + +def _file_timeout_sec() -> int | None: + raw = str(os.environ.get("EDKB_FILE_TIMEOUT_SEC", "0")).strip() + try: + value = int(raw) + except ValueError: + value = 0 + return value if value > 0 else None + + +def _cleanup_input_temp_files(input_path: Path) -> list[Path]: + if input_path.is_file(): + candidates = [input_path] + elif input_path.exists(): + candidates = [p for p in input_path.rglob("*") if p.is_file()] + else: + return [] + + removed: list[Path] = [] + for file in candidates: + name = file.name + if not (name.startswith("~$") or name.startswith("~WRL")): + continue + try: + file.unlink() + except Exception: + continue + removed.append(file) + return removed + + +def _matches_pattern(candidates: list[str], patterns: list[str]) -> str | None: + if not patterns: + return None + lowered_candidates = [c.lower() for c in candidates if c] + for pat in patterns: + norm_pat = _normalize_path_for_match(pat).strip().lower() + if not norm_pat: + continue + for cand in lowered_candidates: + if fnmatch.fnmatch(cand, norm_pat): + return pat + return None + + +def _prune_stale_markdowns(output_dir: Path, expected: set[Path]) -> None: + keep_names = {"INDEX.md", "POSTCHECK_ISSUES.md"} + expected_resolved = {p.resolve() for p in expected} + + for md in output_dir.rglob("*.md"): + if md.name in keep_names: + continue + try: + resolved = md.resolve() + except Exception: + resolved = md + if resolved in expected_resolved: + continue + try: + md.unlink() + except Exception: + continue + + +def _run_one_worker(payload: dict, queue: mp.Queue) -> None: + try: + cfg = SystemConfig.model_validate(payload["config"]) + res = _run_one( + Path(payload["file_path"]), + Path(payload["out_root"]), + Path(payload["temp_dir"]), + cfg, + source_root=Path(payload["source_root"]) + if payload.get("source_root") + else None, + source_category=payload.get("source_category"), + final_md_path=( + Path(payload["final_md_path"]) if payload.get("final_md_path") else None + ), + progress_label=payload.get("progress_label"), + ) + queue.put({"ok": True, "result": res}) + except Exception as exc: + queue.put({"ok": False, "error": str(exc), "detail": traceback.format_exc()}) + + +def _run_one_with_timeout( + file_path: Path, + out_root: Path, + temp_dir: Path, + cfg: SystemConfig, + source_root: Path | None = None, + source_category: str | None = None, + final_md_path: Path | None = None, + progress_label: str | None = None, +) -> dict: + timeout = _file_timeout_sec() + if not timeout: + return _run_one( + file_path, + out_root, + temp_dir, + cfg, + source_root=source_root, + source_category=source_category, + final_md_path=final_md_path, + progress_label=progress_label, + ) + + ctx = mp.get_context("spawn") + queue: mp.Queue = ctx.Queue() + before_pids = _list_winword_pids() + payload = { + "file_path": str(file_path), + "out_root": str(out_root), + "temp_dir": str(temp_dir), + "config": cfg.model_dump(), + "source_root": str(source_root) if source_root else None, + "source_category": source_category, + "final_md_path": str(final_md_path) if final_md_path else None, + "progress_label": progress_label, + } + proc = ctx.Process(target=_run_one_worker, args=(payload, queue)) + proc.start() + proc.join(timeout) + if proc.is_alive(): + proc.terminate() + proc.join(5) + after_pids = _list_winword_pids() + _kill_winword_pids(after_pids - before_pids) + raise TimeoutError( + f"file processing timed out after {timeout}s: {file_path.name}" + ) + if queue.empty(): + if proc.exitcode not in {0, None}: + raise RuntimeError( + f"file worker exited unexpectedly (code={proc.exitcode}): {file_path.name}" + ) + raise RuntimeError(f"file worker returned no result: {file_path.name}") + message = queue.get() + if message.get("ok"): + return message["result"] + detail = str(message.get("detail") or "") + raise RuntimeError(str(message.get("error") or detail or "unknown worker error")) + + marker_files = { + "01_raw_layout.json", + "02_flow_procedure.md", + "03_clean.md", + "04_chunks.jsonl", + "report.md", + "trace_pipeline.json", + "postcheck.json", + } + for d in list(output_dir.iterdir()): + if not d.is_dir(): + continue + try: + names = {p.name for p in d.iterdir()} + except Exception: + continue + if names & marker_files: + shutil.rmtree(d, ignore_errors=True) + + for d in sorted(output_dir.rglob("*"), key=lambda x: len(x.parts), reverse=True): + if not d.is_dir(): + continue + try: + if d == output_dir: + continue + next(d.iterdir()) + except StopIteration: + try: + d.rmdir() + except Exception: + pass + except Exception: + continue + + +def _run_one( + file_path: Path, + out_root: Path, + temp_dir: Path, + cfg: SystemConfig, + source_root: Path | None = None, + source_category: str | None = None, + final_md_path: Path | None = None, + progress_label: str | None = None, +) -> dict: + ctx = Context() + trace_steps: list[str] = [] + timings_ms: dict[str, int] = {} + + def _mark(step: str, started: float) -> None: + timings_ms[step] = int((time.perf_counter() - started) * 1000) + + def _announce(stage: str) -> None: + if not progress_label: + return + print(f"{progress_label} stage: {stage}", flush=True) + + out_dir = out_root / file_path.stem + out_dir.mkdir(parents=True, exist_ok=True) + for stale in [ + out_dir / "inspect_flow_debug.json", + out_dir / "trace_pipeline.json", + out_dir / "postcheck.json", + ]: + if stale.exists(): + stale.unlink() + + t0 = time.perf_counter() + profile = intake_router.run({"file_path": str(file_path)}, ctx, cfg.router) + _mark("edkb-intake-router", t0) + trace_steps.append("edkb-intake-router") + + blocks = [] + tables = None + text = "" + flow_mds: list[str] = [] + + if profile.file_type in {"doc", "docx"}: + _announce("doc/docx parse") + t0 = time.perf_counter() + docx_blocks = loader_docx.run( + {"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx + ) + _mark("edkb-loader-docx", t0) + trace_steps.append("edkb-loader-docx") + + table_blocks = sum(1 for b in docx_blocks if b.type == "table") + prefer_docx = table_blocks > 0 + docx_images = [b for b in docx_blocks if b.type == "image"] + docx_non_images = [b for b in docx_blocks if b.type != "image"] + pdf_blocks = None + + if "edkb-doc-to-pdf" in profile.recommended_pipeline and ( + (profile.file_type == "doc" and not prefer_docx) or not docx_blocks + ): + _announce("doc to pdf") + t0 = time.perf_counter() + conv = doc_to_pdf.run( + {"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx + ) + _mark("edkb-doc-to-pdf", t0) + trace_steps.append("edkb-doc-to-pdf") + pdf_path = conv.get("pdf_path") + if pdf_path: + _announce("pdf load") + t0 = time.perf_counter() + pdf_blocks = loader_pdf.run({"file_path": str(pdf_path)}, ctx) + _mark("edkb-loader-pdf", t0) + trace_steps.append("edkb-loader-pdf") + blocks = pdf_blocks + else: + blocks = docx_blocks + else: + blocks = docx_blocks + + if ( + profile.file_type == "doc" + and "edkb-doc-to-pdf" in profile.recommended_pipeline + and (not prefer_docx or not docx_blocks) + ): + if pdf_blocks is None: + _announce("doc to pdf") + t0 = time.perf_counter() + conv = doc_to_pdf.run( + {"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx + ) + _mark("edkb-doc-to-pdf", t0) + trace_steps.append("edkb-doc-to-pdf") + pdf_path = conv.get("pdf_path") + if pdf_path: + _announce("pdf load") + t0 = time.perf_counter() + pdf_blocks = loader_pdf.run({"file_path": str(pdf_path)}, ctx) + _mark("edkb-loader-pdf", t0) + trace_steps.append("edkb-loader-pdf") + if pdf_blocks is not None: + pdf_images = [b for b in pdf_blocks if b.type == "image"] + if pdf_images and len(pdf_images) > len(docx_images): + blocks = docx_non_images + pdf_images + ctx.warnings.append( + f"doc image source switched to pdf: {len(docx_images)} -> {len(pdf_images)}" + ) + elif not blocks: + blocks = pdf_blocks + elif profile.file_type == "pdf": + _announce("pdf load") + t0 = time.perf_counter() + blocks = loader_pdf.run({"file_path": str(file_path)}, ctx) + _mark("edkb-loader-pdf", t0) + trace_steps.append("edkb-loader-pdf") + elif profile.file_type in {"ppt", "pptx"}: + _announce("ppt/pptx load") + t0 = time.perf_counter() + blocks = loader_pptx.run( + {"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx + ) + _mark("edkb-loader-pptx", t0) + trace_steps.append("edkb-loader-pptx") + elif profile.file_type in {"xls", "xlsx"}: + _announce("excel load") + t0 = time.perf_counter() + tables = loader_excel.run( + {"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx + ) + _mark("edkb-loader-excel", t0) + trace_steps.append("edkb-loader-excel") + elif profile.file_type == "csv": + t0 = time.perf_counter() + tables = loader_csv.run({"file_path": str(file_path)}, ctx) + _mark("edkb-loader-csv", t0) + trace_steps.append("edkb-loader-csv") + else: + ctx.warnings.append(f"unsupported file type: {profile.file_type}") + + if blocks: + ctx.images = sum(1 for b in blocks if b.type == "image") + should_ocr = cfg.ocr.enable and ( + "edkb-ocr" in profile.recommended_pipeline + or any(b.type == "image" for b in blocks) + ) + if profile.file_type in {"ppt", "pptx"}: + should_ocr = False + if should_ocr: + _announce("ocr") + t0 = time.perf_counter() + blocks = ocr.run(blocks, ctx, min_confidence=cfg.ocr.min_confidence) + _mark("edkb-ocr", t0) + trace_steps.append("edkb-ocr") + + doc_kind = (ctx.extras.get("intake") or {}).get("doc_kind") + policy_text = doc_kind == "policy_text" + has_non_flow_info = _has_non_flow_image_content(blocks) + has_page_image_mode = bool(ctx.extras.get("pdf_page_image_mode_pages")) + has_figure_anchor = any( + (b.text or "") + and re.search( + r"^\s*\d+(?:\.\d+){1,3}\s*[^\n]{0,40}(?:示意图|图示)\s*$", + b.text, + ) + for b in blocks + if b.type in {"heading", "paragraph"} + ) + suppress_images = False + if profile.file_type not in {"ppt", "pptx"} and not has_figure_anchor: + if policy_text and not has_non_flow_info and not has_page_image_mode: + suppress_images = True + elif ( + doc_kind == "flow_procedure" + and not has_non_flow_info + and not has_page_image_mode + ): + suppress_images = True + if suppress_images: + blocks = [b for b in blocks if b.type not in {"image", "ocr_text"}] + trace_steps.append("edkb-image-suppress(no_figure_anchor)") + + flow_info = {} + if "edkb-flow-reconstruct" in profile.recommended_pipeline: + _announce("flow reconstruct") + t0 = time.perf_counter() + flow_info = flow_reconstruct.run(blocks, ctx) + _mark("edkb-flow-reconstruct", t0) + trace_steps.append("edkb-flow-reconstruct") + flow_mds = flow_info.get("flow_markdowns", []) + if flow_info.get("debug"): + (out_dir / "inspect_flow_debug.json").write_text( + json.dumps(flow_info["debug"], ensure_ascii=False, indent=2), + encoding="utf-8", + ) + + text = blocks_to_plain_markdown(blocks) + text = _inject_doc_header_from_flow(text, flow_mds) + elif tables is not None: + _announce("table linearize") + t0 = time.perf_counter() + text = table_linearize.run(tables, ctx) + _mark("edkb-table-linearize", t0) + trace_steps.append("edkb-table-linearize") + + _announce("clean") + t0 = time.perf_counter() + clean_md = clean.run( + text, ctx, cfg.clean.dedup_min_repeats, cfg.clean.merge_short_line_chars + ) + _mark("edkb-clean", t0) + clean_md = _inject_source_title_if_missing(clean_md, file_path.stem) + clean_md = _promote_title_above_meta(clean_md) + meta = _extract_doc_header_from_flow(flow_mds) + has_meta_line = bool( + re.search(r"文件编号\s+\S+\s+文件级别\s+\S+\s+版本\s+\S+", clean_md) + or ("| 文件编号 |" in clean_md and "| 文件级别 |" in clean_md) + ) + if meta and not has_meta_line: + if clean_md.startswith("制定部门"): + i = clean_md.find("\n") + if i >= 0: + clean_md = clean_md[: i + 1] + meta + "\n" + clean_md[i + 1 :] + else: + clean_md = clean_md + "\n" + meta + "\n" + else: + clean_md = meta + "\n" + clean_md + clean_md = _promote_title_above_meta(clean_md) + clean_md = _promote_dept_header_near_top(clean_md) + trace_steps.append("edkb-clean") + + chunks = [] + if cfg.chunk.enable: + _announce("chunk") + t0 = time.perf_counter() + chunks = chunk.run( + {"source": file_path.name, "text": clean_md}, + ctx, + max_chars=cfg.chunk.max_chars, + overlap_chars=cfg.chunk.overlap_chars, + add_heading_path_prefix=cfg.chunk.add_heading_path_prefix, + ) + _mark("edkb-chunk", t0) + trace_steps.append("edkb-chunk") + t0 = time.perf_counter() + chunks = quality_gate.run(chunks, ctx) + _mark("edkb-quality-gate", t0) + trace_steps.append("edkb-quality-gate") + else: + ctx.warnings.append( + "chunk disabled by config: skip edkb-chunk/edkb-quality-gate" + ) + trace_steps.append("edkb-chunk(skipped)") + trace_steps.append("edkb-quality-gate(skipped)") + + source_rel_path = file_path.name + if source_root is not None: + try: + source_rel_path = str(file_path.relative_to(source_root)) + except Exception: + source_rel_path = file_path.name + + target_md_path = final_md_path + if target_md_path is None: + target_md_path = out_root / f"{file_path.stem}.md" + + _announce("export") + t0 = time.perf_counter() + export.run( + { + "out_dir": str(out_dir), + "source_file": file_path.name, + "source_rel_path": source_rel_path, + "source_category": source_category or "", + "flat_md_path": str(target_md_path), + "clean_md": clean_md, + "chunks": chunks, + "blocks": blocks, + "flow_markdowns": flow_mds, + }, + ctx, + ) + _mark("edkb-export", t0) + trace_steps.append("edkb-export") + + exported_clean_md = clean_md + exported_clean_path = out_dir / "03_clean.md" + if exported_clean_path.exists(): + try: + exported_clean_md = exported_clean_path.read_text(encoding="utf-8") + except Exception: + exported_clean_md = clean_md + + _announce("postcheck") + t0 = time.perf_counter() + check = postcheck.run({"out_dir": str(out_dir), "clean_md": exported_clean_md}, ctx) + _mark("edkb-postcheck", t0) + (out_dir / "postcheck.json").write_text( + json.dumps(check, ensure_ascii=False, indent=2), encoding="utf-8" + ) + if check.get("status") != "pass": + failed = ", ".join(check.get("failed_required", [])) + ctx.warnings.append(f"postcheck failed: {failed}") + if check.get("issue_count", 0) > 0: + issue_codes: list[str] = [] + for it in check.get("issues", [])[:3]: + code = str(it.get("code", "")).strip() + if code and code not in issue_codes: + issue_codes.append(code) + if issue_codes: + ctx.warnings.append( + f"postcheck issues: {check.get('issue_count', 0)} ({', '.join(issue_codes)})" + ) + else: + ctx.warnings.append(f"postcheck issues: {check.get('issue_count', 0)}") + trace_steps.append("edkb-postcheck") + + (out_dir / "trace_pipeline.json").write_text( + json.dumps( + { + "file": file_path.name, + "recommended_pipeline": profile.recommended_pipeline, + "executed_steps": trace_steps, + "timings_ms": timings_ms, + "intake": ctx.extras.get("intake", {}), + }, + ensure_ascii=False, + indent=2, + ), + encoding="utf-8", + ) + + return { + "file": file_path.name, + "out_dir": str(out_dir), + "warnings": ctx.warnings, + "timings_ms": timings_ms, + } + + +def build_knowledge( + input_path: Path, + output_dir: Path, + config: SystemConfig, + temp_dir: Path, + skip_patterns: list[str] | None = None, + resume: bool = False, + prune_stale_output: bool = False, +) -> list[dict]: + removed_temp_files = _cleanup_input_temp_files(input_path) + if removed_temp_files: + for removed in removed_temp_files: + print(f"cleanup-temp: {removed}", flush=True) + + files = discover(input_path) + output_dir.mkdir(parents=True, exist_ok=True) + temp_dir.mkdir(parents=True, exist_ok=True) + + patterns = [p for p in (skip_patterns or []) if str(p).strip()] + + for stale in [output_dir / "INDEX.md", output_dir / "POSTCHECK_ISSUES.md"]: + if stale.exists(): + stale.unlink() + for lock_md in output_dir.glob("~$*.md"): + if lock_md.is_file(): + lock_md.unlink() + + if prune_stale_output: + expected_paths = { + (output_dir / _derive_output_rel_md(file, input_path)).resolve() + for file in files + } + _prune_stale_markdowns(output_dir, expected_paths) + + source_root = input_path if input_path.is_dir() else input_path.parent + + results: list[dict] = [] + total = len(files) + for idx, file in enumerate(files, start=1): + flat_out = output_dir / f"{file.stem}.md" + mirror_out = output_dir / _derive_output_rel_md(file, input_path) + + source_rel_path = file.name + try: + source_rel_path = _normalize_path_for_match(file.relative_to(source_root)) + except Exception: + source_rel_path = _normalize_path_for_match(file) + + matched_pattern = _matches_pattern( + [ + _normalize_path_for_match(file), + source_rel_path, + file.name, + ], + patterns, + ) + if matched_pattern: + print( + f"[{idx}/{total}] skipped(pattern): {source_rel_path} ({matched_pattern})", + flush=True, + ) + results.append( + { + "file": file.name, + "out_dir": str(output_dir / file.stem), + "warnings": [], + "status": "skipped", + "skip_reason": f"pattern:{matched_pattern}", + "elapsed_ms": 0, + } + ) + continue + + if resume and mirror_out.exists() and mirror_out.stat().st_size > 0: + print(f"[{idx}/{total}] skipped(resume): {source_rel_path}", flush=True) + results.append( + { + "file": file.name, + "out_dir": str(output_dir / file.stem), + "warnings": [], + "status": "skipped", + "skip_reason": "resume-existing-output", + "elapsed_ms": 0, + } + ) + continue + + print(f"[{idx}/{total}] processing: {file.name}", flush=True) + if flat_out.exists(): + flat_out.unlink() + if mirror_out != flat_out and mirror_out.exists(): + mirror_out.unlink() + started = time.perf_counter() + try: + source_category = _derive_source_category(file, input_path) + res = _run_one_with_timeout( + file, + output_dir, + temp_dir, + config, + source_root=source_root, + source_category=source_category, + final_md_path=mirror_out, + progress_label=f"[{idx}/{total}] {file.name}", + ) + elapsed_ms = int((time.perf_counter() - started) * 1000) + res["status"] = "success" + res["elapsed_ms"] = elapsed_ms + results.append(res) + print( + f"[{idx}/{total}] success: {file.name} ({elapsed_ms / 1000:.3f}s)", + flush=True, + ) + timings = res.get("timings_ms", {}) or {} + if timings: + top = sorted(timings.items(), key=lambda x: x[1], reverse=True)[:3] + top_text = ", ".join( + f"{_step_alias(k)}={v / 1000:.3f}s" for k, v in top + ) + print(f"[{idx}/{total}] time: {top_text}", flush=True) + + out_dir_str = str(res.get("out_dir", "")).strip() + doc_artifact_dir = Path(out_dir_str) if out_dir_str else None + if ( + doc_artifact_dir is not None + and doc_artifact_dir.exists() + and doc_artifact_dir.parent == output_dir + ): + shutil.rmtree(doc_artifact_dir) + except Exception as exc: + elapsed_ms = int((time.perf_counter() - started) * 1000) + detail = traceback.format_exc() + doc_artifact_dir = output_dir / file.stem + if doc_artifact_dir.exists(): + shutil.rmtree(doc_artifact_dir) + if flat_out.exists(): + flat_out.unlink() + if mirror_out.exists() and mirror_out != flat_out: + mirror_out.unlink() + results.append( + { + "file": file.name, + "out_dir": str(output_dir / file.stem), + "warnings": [str(exc)], + "status": "failed", + "elapsed_ms": elapsed_ms, + "error": str(exc), + "error_detail": detail, + } + ) + print( + f"[{idx}/{total}] failed: {file.name} ({elapsed_ms / 1000:.3f}s)", + flush=True, + ) + print(f"[{idx}/{total}] reason: {exc}", flush=True) + print(detail.rstrip(), flush=True) + return results diff --git a/backend/edkb_system/discovery.py b/backend/edkb_system/discovery.py new file mode 100644 index 00000000..7c0faea8 --- /dev/null +++ b/backend/edkb_system/discovery.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from pathlib import Path + +SUPPORTED_EXTS = {".doc", ".docx", ".pdf", ".xls", ".xlsx", ".csv", ".ppt", ".pptx"} + + +def discover(path: Path) -> list[Path]: + if path.is_file(): + if path.name.startswith("~$"): + return [] + return [path] if path.suffix.lower() in SUPPORTED_EXTS else [] + if not path.exists(): + raise FileNotFoundError(path) + files = [ + p + for p in path.rglob("*") + if p.is_file() + and not p.name.startswith("~$") + and p.suffix.lower() in SUPPORTED_EXTS + ] + return sorted(files, key=lambda x: str(x)) diff --git a/backend/edkb_system/skills/__init__.py b/backend/edkb_system/skills/__init__.py new file mode 100644 index 00000000..69c566ff --- /dev/null +++ b/backend/edkb_system/skills/__init__.py @@ -0,0 +1 @@ +"""Atomic skills for enterprise KB pipeline.""" diff --git a/backend/edkb_system/skills/chunk.py b/backend/edkb_system/skills/chunk.py new file mode 100644 index 00000000..2b24c038 --- /dev/null +++ b/backend/edkb_system/skills/chunk.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +import hashlib +import re + +from edkb_system.contracts import Chunk, Context + + +HEAD_RE = re.compile(r"^(#{1,6})\s+(.*)$") + + +def _chunk_id(source: str, heading: str, index: int, text: str) -> str: + raw = f"{source}|{heading}|{index}|{text}" + return hashlib.sha256(raw.encode("utf-8")).hexdigest() + + +def run( + input_data: dict, + context: Context, + max_chars: int = 1200, + overlap_chars: int = 150, + add_heading_path_prefix: bool = True, +) -> list[Chunk]: + source = input_data["source"] + md = input_data["text"] + lines = md.splitlines() + + stack: list[str] = [] + sections: list[tuple[str, str]] = [] + buf: list[str] = [] + + def heading() -> str: + return " > ".join(stack) if stack else "ROOT" + + for ln in lines: + m = HEAD_RE.match(ln.strip()) + if m: + if buf: + sections.append((heading(), "\n".join(buf).strip())) + buf = [] + level = len(m.group(1)) + text = m.group(2).strip() + while len(stack) >= level: + stack.pop() + stack.append(text) + else: + buf.append(ln) + if buf: + sections.append((heading(), "\n".join(buf).strip())) + + out: list[Chunk] = [] + idx = 0 + for hp, body in sections: + paras = [p.strip() for p in body.split("\n\n") if p.strip()] + acc = "" + for p in paras: + cand = (acc + "\n\n" + p).strip() if acc else p + if len(cand) <= max_chars: + acc = cand + continue + if acc: + txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc + out.append( + Chunk( + id=_chunk_id(source, hp, idx, txt), + heading_path=hp, + text=txt, + index=idx, + source=source, + ) + ) + idx += 1 + overlap = txt[-overlap_chars:] if overlap_chars > 0 else "" + acc = (overlap + "\n\n" + p).strip() + else: + acc = p[:max_chars] + if acc: + txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc + out.append( + Chunk( + id=_chunk_id(source, hp, idx, txt), + heading_path=hp, + text=txt, + index=idx, + source=source, + ) + ) + idx += 1 + + return out diff --git a/backend/edkb_system/skills/clean.py b/backend/edkb_system/skills/clean.py new file mode 100644 index 00000000..35f79d2a --- /dev/null +++ b/backend/edkb_system/skills/clean.py @@ -0,0 +1,2017 @@ +from __future__ import annotations + +import base64 +import re +from collections import Counter + +from edkb_system.contracts import Context + + +def _dedupe_repeated_headers(lines: list[str]) -> list[str]: + header_patterns = [ + re.compile( + r"^(?P\s*制定部门.+?制/修订日期.+?页码\s*\d+\s*/\s*\d+)(?P.*)$" + ), + re.compile( + r"^(?P\s*文件编号\s+.+?文件级别\s+.+?版本\s+.+?)(?P.*)$" + ), + re.compile(r"^(?P\s*注:文件在系统签核完成日即为生效日\s*)(?P.*)$"), + ] + + seen: dict[int, bool] = {} + out: list[str] = [] + for ln in lines: + s = ln.rstrip("\n") + handled = False + for i, p in enumerate(header_patterns): + m = p.match(s) + if not m: + continue + rest = (m.group("rest") or "").strip() + if seen.get(i): + if rest: + out.append(rest) + handled = True + break + seen[i] = True + if m.group("head"): + out.append(m.group("head").strip()) + if rest: + out.append(rest) + handled = True + break + if not handled: + out.append(ln) + return out + + +def _join_cross_page_broken_lines(lines: list[str]) -> list[str]: + out: list[str] = [] + i = 0 + while i < len(lines): + cur = lines[i] + if i + 2 < len(lines): + nxt = lines[i + 1] + nxt2 = lines[i + 2] + if ( + not nxt.strip() + and cur.strip() + and nxt2.strip() + and re.search(r"[\u4e00-\u9fff]$", cur.strip()) + and re.match(r"^[\u4e00-\u9fff]", nxt2.strip()) + and not re.match(r"^\d+\.\d", nxt2.strip()) + ): + out.append(cur.rstrip() + nxt2.lstrip()) + i += 3 + continue + out.append(cur) + i += 1 + return out + + +def _split_inline_headings(text: str) -> str: + out_lines: list[str] = [] + for ln in text.splitlines(): + s = ln.strip() + if not s or s.startswith("|"): + out_lines.append(ln) + continue + + ln = re.sub(r"\s+(?=[一二三四五六七八九十]+、)", "\n", ln) + ln = re.sub(r"(? str: + m_start = re.search(r"五、作业流程图", text) + if not m_start: + return text + start = m_start.start() + + m_end = re.search(r"(?:\n|\s)六、作业内容", text[start:]) + if not m_end: + return text + end = start + m_end.start() + if end <= start: + return text + + section = text[start:end] + row_hits = re.findall(r"(?m)^\s*([1-6])\s+.+$", section) + if len(set(row_hits)) < 4: + return text + + branch_proc = "不合格控制程序" + if re.search(r"不合格控制程序", section): + branch_proc = "不合格控制程序" + elif re.search(r"NG控制程序", section): + branch_proc = "NG控制程序" + + flow_names = { + "1": "备料", + "2": "取样", + "3": "资料确认", + "4": "品质检验", + "5": "判定", + "6": "产品出货", + } + + lines: list[str] = [ + "五、作业流程图", + "| 序号 | 流程说明 | 责任部门 | 相关记录 |", + "| --- | --- | --- | --- |", + ] + + for n in ["1", "2", "3", "4", "5", "6"]: + dept = "品保部 OQC" if n in {"2", "3", "4", "5"} else "仓储课" + if n == "1": + record = "出货通知单" + elif n == "2": + record = "出货通知单" + elif n in {"3", "4"}: + record = "出货检验记录" + elif n == "5": + record = "出货检验记录;重工流程单;纠正与预防处理单" + else: + record = "送货单" + lines.append(f"| {n} | {flow_names[n]} | {dept} | {record} |") + + lines.extend( + [ + "", + "流程分支:", + f"- 判定 = NG:依《{branch_proc}》执行,并回到前序处理。", + "- 判定 = OK:产品出货。", + "", + ] + ) + + replacement = "\n".join(lines) + text = text[:start] + replacement + text[end:] + text = re.sub( + r"\s*(?:NG品|不合格品)\s*NG\s*OK\s*备料\s*资料确认\s*产品出货\s*取样\s*依\s*《?(?:NG控制程序|不合格控制程序|NG控制程\s*序|不合格控制程\s*序)》?\s*执行\s*判定\s*品质检验", + "", + text, + ) + return text + + +def _normalize_revision_history_table(text: str) -> str: + title_pos = text.find("文件修订履历") + if title_pos < 0: + return text + line_start = text.rfind("\n", 0, title_pos) + 1 + line_prefix = text[line_start:title_pos].strip() + start = line_start + + tail = text[start:] + m_end = re.search(r"\n制定部门[^\n]*页码\s*2\s*/\s*5|\n一、目的", tail) + if m_end: + end = start + m_end.start() + else: + end = min(len(text), start + 1200) + + section = text[start:end] + if "| 日期 | 修订章节 |" in section: + return text + + date_matches = list(re.finditer(r"\d{4}/\d{1,2}/\d{1,2}", section)) + if not date_matches: + return text + + chunks: list[str] = [] + for i, m in enumerate(date_matches): + chunk_start = m.start() + chunk_end = ( + date_matches[i + 1].start() if i + 1 < len(date_matches) else len(section) + ) + chunks.append(section[chunk_start:chunk_end]) + + rows: list[tuple[str, str, str, str, str]] = [] + for ch in chunks: + s = " ".join(ch.split()) + s = re.sub(r"^日期\s+修订章节\s+主要修订内容\s+版本\s+修改人\s+备注\s*", "", s) + m = re.match( + r"(?P\d{4}/\d{1,2}/\d{1,2})\s+(?P
\S+)\s+(?P.+?)\s+(?PV\d+(?:\.\d+)?)\s+(?P\S+)$", + s, + ) + if not m: + continue + rows.append( + ( + m.group("date"), + m.group("section"), + m.group("content"), + m.group("version"), + m.group("editor"), + ) + ) + + if not rows: + return text + + lines = [ + "文件修订履历", + "| 日期 | 修订章节 | 主要修订内容 | 版本 | 修改人 | 备注 |", + "| --- | --- | --- | --- | --- | --- |", + ] + for d, sec, content, ver, editor in rows: + lines.append(f"| {d} | {sec} | {content} | {ver} | {editor} | |") + + replacement = "\n".join(lines) + if line_prefix: + replacement = line_prefix + "\n" + replacement + return text[:start] + replacement + "\n\n" + text[end:] + + +def _normalize_revision_history_loose(text: str) -> str: + m_head = re.search( + r"(?m)^\s*日期\s+修订章节\s+主要修订内容\s+版本\s+修改人\s+备注(?:\s+.*)?$", + text, + ) + if not m_head: + return text + + start = m_head.start() + tail = text[start:] + m_end = re.search(r"(?m)^\s*[一二三四五六七八九十]+、", tail) + end = start + m_end.start() if m_end else len(text) + section = text[start:end] + + date_matches = list(re.finditer(r"\d{4}/\d{1,2}/\d{1,2}", section)) + if not date_matches: + return text + + rows: list[tuple[str, str, str, str, str]] = [] + for i, m in enumerate(date_matches): + d = m.group(0) + chunk_start = m.start() + chunk_end = ( + date_matches[i + 1].start() if i + 1 < len(date_matches) else len(section) + ) + chunk = " ".join(section[chunk_start:chunk_end].split()) + body = chunk[len(d) :].strip() + if not body: + continue + + version_matches = list(re.finditer(r"V\d+(?:\.\d+)?", body)) + version = version_matches[-1].group(0) if version_matches else "" + if version_matches: + vm = version_matches[-1] + left = body[: vm.start()].strip() + right = body[vm.end() :].strip() + else: + left = body + right = "" + + editor = right.split()[0] if right else "" + left_tokens = left.split() + sec = left_tokens[0] if left_tokens else "" + content = " ".join(left_tokens[1:]).strip() if len(left_tokens) > 1 else left + if not content: + content = left + rows.append((d, sec, content, version, editor)) + + if not rows: + return text + + lines = [ + "文件修订履历", + "| 日期 | 修订章节 | 主要修订内容 | 版本 | 修改人 | 备注 |", + "| --- | --- | --- | --- | --- | --- |", + ] + for d, sec, content, ver, editor in rows: + lines.append(f"| {d} | {sec} | {content} | {ver} | {editor} | |") + + replacement = "\n".join(lines) + return text[:start] + replacement + "\n\n" + text[end:] + + +def _normalize_related_forms_table(text: str) -> str: + m_title = re.search(r"([一二三四五六七八九十]+、相关表单[::]?)", text) + if not m_title: + return text + start = m_title.start() + title = m_title.group(1) + tail = text[start:] + if re.search(r"\|\s*表单编号\s*\|", tail): + return text + head = re.search(r"表单编号\s+.+", tail) + if not head: + return text + + section_start = start + head.start() + section = text[section_start:] + rows: list[tuple[str, str, str, str]] = [] + for raw in section.splitlines()[1:20]: + s = " ".join(raw.split()) + if not s: + continue + if re.match(r"^[一二三四五六七八九十]+、", s): + if rows: + break + continue + toks = s.split() + if len(toks) < 3: + continue + i = -1 + for idx, tok in enumerate(toks[1:], start=1): + if tok.endswith("部") or tok in { + "品保部", + "人事部", + "采购部", + "工程部", + "生产部", + }: + i = idx + break + if i <= 1: + continue + form_id = toks[0] + name = " ".join(toks[1:i]).strip() + dept = toks[i] + remark = " ".join(toks[i + 1 :]).strip() + if not form_id or not name: + continue + rows.append((form_id, name, dept, remark)) + + if not rows: + return text + + lines = [ + title.rstrip("::"), + "| 表单编号 | 记录名称 | 保管部门 | 备注 |", + "| --- | --- | --- | --- |", + ] + for form_id, name, dept, remark in rows: + lines.append(f"| {form_id} | {name} | {dept} | {remark} |") + + replacement = "\n".join(lines) + return text[:start] + replacement + "\n" + + +def _tighten_numbered_spacing(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + num_pat = re.compile(r"^\s*\d+(?:\.\d+){1,4}(?:\s+|[\u4e00-\u9fff((])") + + for i, ln in enumerate(lines): + if not ln.strip() and out: + j = i + 1 + nxt = "" + while j < len(lines): + if lines[j].strip(): + nxt = lines[j] + break + j += 1 + prev = out[-1] + if num_pat.match(prev.strip()) and num_pat.match(nxt.strip()): + continue + out.append(ln) + + return "\n".join(out) + + +def _tighten_alpha_list_spacing(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + alpha_pat = re.compile(r"^[a-zA-Z]\)\s+") + + for i, ln in enumerate(lines): + if not ln.strip() and out: + prev = out[-1].strip() + j = i + 1 + nxt = "" + while j < len(lines): + if lines[j].strip(): + nxt = lines[j].strip() + break + j += 1 + if alpha_pat.match(prev) and alpha_pat.match(nxt): + continue + out.append(ln) + + return "\n".join(out) + + +def _remove_soft_blank_lines(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + + def is_heading(s: str) -> bool: + return bool( + re.match(r"^[一二三四五六七八九十]+、", s) + or re.match(r"^\d+(?:\.\d+){0,4}(?:\s+|[\u4e00-\u9fff((])", s) + or re.match(r"^[a-zA-Z]\.\s*", s) + or s.startswith("#") + ) + + for i, ln in enumerate(lines): + if ln.strip(): + out.append(ln) + continue + + prev = out[-1].strip() if out else "" + j = i + 1 + nxt = "" + while j < len(lines): + if lines[j].strip(): + nxt = lines[j].strip() + break + j += 1 + + if not prev or not nxt: + continue + if prev.startswith("|") or nxt.startswith("|"): + out.append(ln) + continue + if (prev.startswith("-") or prev.startswith("*")) and is_heading(nxt): + out.append(ln) + continue + if re.match(r"^[a-zA-Z]\.\s*", prev) or re.match(r"^[a-zA-Z]\.\s*", nxt): + continue + if is_heading(prev) or is_heading(nxt): + continue + # otherwise drop soft blank line + + return "\n".join(out) + + +def _normalize_basic_headings(text: str) -> str: + mapping = { + "目的": "一、目的", + "范围": "二、范围", + "定义": "三、定义", + "职责": "三、职责", + "权责": "四、权责", + "相关文件": "五、相关文件", + "作业内容": "五、作业内容", + } + out: list[str] = [] + keys = ["目的", "范围", "定义", "职责", "权责", "相关文件", "作业内容"] + for ln in text.splitlines(): + s = ln.strip() + if s in mapping: + out.append(mapping[s]) + continue + + handled = False + for k in keys: + if s.startswith(k) and not re.match(r"^[一二三四五六七八九十]+、", s): + rest = s[len(k) :].strip() + out.append(mapping[k]) + if rest: + out.append(rest) + handled = True + break + if not handled: + out.append(ln) + return "\n".join(out) + + +def _normalize_doc_meta_lines(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + + for ln in lines: + s = " ".join(ln.split()) + if ( + out + and re.search(r"版本\s+[Vv]$", out[-1].strip()) + and re.match(r"^\d+(?:\.\d+)?$", s) + ): + out[-1] = out[-1].rstrip() + s + continue + + m = re.match( + r"^(?P[^\s].*?)(?P<meta>文件编号\s+\S+\s+文件级别\s+\S+\s+版本\s+\S.*)$", + s, + ) + if m and m.group("title") and m.group("meta"): + title = m.group("title").strip() + meta = m.group("meta").strip() + if title and title != "文件": + out.append(title) + out.append(meta) + continue + + out.append(ln) + + return "\n".join(out) + + +def _dedupe_top_title_lines(text: str) -> str: + lines = text.splitlines() + idxs = [i for i, ln in enumerate(lines) if ln.strip()][:8] + if len(idxs) < 2: + return text + + def norm(s: str) -> str: + s = s.strip().lower() + s = re.sub(r"\s+", "", s) + s = re.sub(r"[^\w\u4e00-\u9fff]+", "", s) + return s + + base = norm(lines[idxs[0]]) + remove: list[int] = [] + for i in idxs[1:]: + s = norm(lines[i]) + if s and (s == base or s in base or base in s): + remove.append(i) + for i in reversed(remove): + lines.pop(i) + return "\n".join(lines) + + +def _normalize_doc_meta_table(text: str) -> str: + lines = text.splitlines() + idx_meta = next( + ( + i + for i, ln in enumerate(lines) + if "文件编号" in ln and "文件级别" in ln and "版本" in ln + ), + None, + ) + idx_dept = next( + ( + i + for i, ln in enumerate(lines) + if "制定部门" in ln and "制/修订日期" in ln and "页码" in ln + ), + None, + ) + if idx_meta is None or idx_dept is None: + return text + + m1 = re.search( + r"文件编号\s*(\S+)\s*文件级别\s*(\S+)\s*版本\s*(\S+)", + " ".join(lines[idx_meta].split()), + ) + m2 = re.search( + r"制定部门\s*(\S+)\s*制/修订日期\s*([0-9./-]+)\s*页码\s*([0-9]+\s*/\s*[0-9]+)", + " ".join(lines[idx_dept].split()), + ) + if not m1 or not m2: + return text + + block = [ + f"| 文件编号 | {m1.group(1)} | 文件级别 | {m1.group(2)} | 版本 | {m1.group(3)} |", + "| --- | --- | --- | --- | --- | --- |", + f"| 制定部门 | {m2.group(1)} | 制/修订日期 | {m2.group(2)} | 页码 | {m2.group(3)} |", + ] + + lo, hi = sorted([idx_meta, idx_dept]) + out = lines[:lo] + block + lines[hi + 1 :] + cleaned: list[str] = [] + for ln in out: + s = " ".join(ln.split()) + if not ln.strip().startswith("|") and ( + ("文件编号" in s and "文件级别" in s and "版本" in s) + or ("制定部门" in s and "制/修订日期" in s and "页码" in s) + ): + continue + cleaned.append(ln) + out = cleaned + return "\n".join(out) + + +def _split_inline_section_title(text: str) -> str: + out: list[str] = [] + sec_words = "目的|范围|定义|权责|作业内容|作业流程图|参考文件|相关表单|补充说明" + for ln in text.splitlines(): + m = re.match(rf"^\s*([一二三四五六七八九十]+、(?:{sec_words})[::]?)(.+)$", ln) + if m and not m.group(2).strip().startswith("|"): + out.append(m.group(1).strip()) + out.append(m.group(2).strip()) + else: + out.append(ln) + return "\n".join(out) + + +def _split_numbered_heading_with_body(text: str) -> str: + out: list[str] = [] + for ln in text.splitlines(): + s = ln.strip() + m = re.match( + r"^(\d+\.\d+(?:\.\d+)?\s+[^;。::]{2,24}?(?:设立|配备|管理|处理|须知|要领|要点|检查|定义|流程|标准|范围|目的))(.+)$", + s, + ) + if m and re.search(r"[;。]", m.group(2)): + out.append(m.group(1).strip()) + out.append(m.group(2).strip()) + else: + out.append(ln) + return "\n".join(out) + + +def _label_subitems_after_headings(text: str) -> str: + lines = text.splitlines() + out = lines[:] + + def is_heading(s: str) -> bool: + return bool(re.match(r"^\d+\.\d+(?:\.\d+)?", s)) + + i = 0 + while i < len(out): + cur = out[i].strip() + if not is_heading(cur): + i += 1 + continue + + j = i + 1 + candidates: list[int] = [] + while j < len(out): + s = out[j].strip() + if is_heading(s) or re.match(r"^[一二三四五六七八九十]+、", s): + break + if ( + s + and not s.startswith("|") + and not s.startswith("!") + and not re.match(r"^[a-zA-Z][\.)]\s*", s) + ): + if len(s) >= 8: + candidates.append(j) + j += 1 + + if len(candidates) >= 3: + for k, idx in enumerate(candidates): + if k >= 26: + break + out[idx] = f"{chr(ord('a') + k)}) {out[idx].strip()}" + i = j + + return "\n".join(out) + + +def _remove_page_counter_artifacts(text: str) -> str: + out: list[str] = [] + for ln in text.splitlines(): + s = " ".join(ln.split()) + if ( + re.match(r"^\d+\s+页码\b", s) + and ("/" in s or "/" in s) + and re.search(r"\d+", s) + ): + continue + out.append(ln) + return "\n".join(out) + + +def _promote_doc_header_line(text: str) -> str: + lines = text.splitlines() + header_pat = re.compile(r"制定部门.+制/修订日期.+页码\s*\d+\s*/\s*\d+") + idx = next( + (i for i, ln in enumerate(lines) if header_pat.search(" ".join(ln.split()))), + None, + ) + if idx is None or idx <= 3: + return text + + header = lines.pop(idx) + insert_at = 0 + for i, ln in enumerate(lines[:6]): + s = ln.strip() + if s.startswith("文件编号"): + insert_at = i + 1 + break + if s: + insert_at = i + 1 + lines.insert(insert_at, header) + return "\n".join(lines) + + +def _relocate_trailing_images(text: str) -> str: + if "![table-image](" in text: + return text + + lines = text.splitlines() + img_pat = re.compile(r"^!\[image-\d+\]\(data:image/") + imgs = [ln for ln in lines if img_pat.match(ln.strip())] + if not imgs: + return text + + kept = [ln for ln in lines if not img_pat.match(ln.strip())] + is_table_row = lambda ln: bool(re.match(r"^\s*\|", ln.strip())) + precise = [ + i + for i, ln in enumerate(kept) + if (not is_table_row(ln)) and re.search(r"\d+\.\d+(?:\.\d+)?\s*.*示意图", ln) + ] + anchors = ( + precise + if precise + else [ + i + for i, ln in enumerate(kept) + if (not is_table_row(ln)) and re.search(r"示意图|图示", ln) + ] + ) + if not anchors: + anchors = [ + i + for i, ln in enumerate(kept) + if (not is_table_row(ln)) and re.search(r"流程图", ln) + ] + if not anchors: + return "\n".join(kept + [""] + imgs) + + out = kept[:] + if len(anchors) == 1 and len(imgs) >= 2: + a = anchors[0] + # 保持抽取顺序:第一张=上半图,第二张=下半图;统一放在锚点后。 + before = imgs[0] + after = imgs[1] + out[a + 1 : a + 1] = ["", before, "", after, ""] + rest = imgs[:] + try: + rest.remove(before) + except ValueError: + pass + try: + rest.remove(after) + except ValueError: + pass + sec66_idx = next( + ( + i + for i, ln in enumerate(out) + if (not is_table_row(ln)) + and re.search(r"^\s*6\.6\.4(?=[^0-9]|$)", ln.strip()) + and re.search(r"正常|加严|减量|免检", ln) + ), + None, + ) + if sec66_idx is None: + sec66_idx = next( + ( + i + for i, ln in enumerate(out) + if (not is_table_row(ln)) + and re.search(r"6\.6", ln) + and re.search(r"正常|加严|减量|免检", ln) + ), + None, + ) + if rest and sec66_idx is not None: + pick = rest.pop(0) + out[sec66_idx + 1 : sec66_idx + 1] = ["", pick, ""] + # 对“正常/加严/减量/免检”切换示意图,仅保留首个候选, + # 避免把修订版本的重复流程图继续混入正文。 + rest = [] + if rest: + ref_idx = next( + ( + i + for i, ln in enumerate(out) + if re.match( + r"^[一二三四五六七八九十]+、(?:参考文件|相关文件)", ln.strip() + ) + or re.search(r"(?:参考文件|相关文件)", ln.strip()) + ), + None, + ) + if ref_idx is None: + out.extend([""] + rest) + else: + out[ref_idx:ref_idx] = [""] + rest + [""] + return "\n".join(out) + + offset = 0 + for i, img in enumerate(imgs): + if i < len(anchors): + pos = anchors[i] + 1 + offset + else: + pos = anchors[-1] + 1 + offset + out[pos:pos] = ["", img, ""] + offset += 3 + return "\n".join(out) + + +def _relocate_server_612_images(text: str) -> str: + lines = text.splitlines() + img_pat = re.compile(r"^!\[image-\d+\]\(data:image/") + idx_611 = next( + ( + i + for i, ln in enumerate(lines) + if re.search(r"^\s*6\.1\.1\s*检验条件", ln.strip()) + ), + None, + ) + idx_612 = next( + ( + i + for i, ln in enumerate(lines) + if re.search(r"^\s*6\.1\.2\s*外观面等级划分示意图", ln.strip()) + ), + None, + ) + if idx_611 is None or idx_612 is None or idx_611 >= idx_612: + return text + + direct_imgs: list[int] = [] + j = idx_612 + 1 + while j < len(lines): + s = lines[j].strip() + if not s: + j += 1 + continue + if img_pat.match(s): + direct_imgs.append(j) + j += 1 + continue + break + if len(direct_imgs) < 2: + return text + + first_img = lines[direct_imgs[0]].strip() + second_img = lines[direct_imgs[1]].strip() + kept: list[str] = [] + for i, ln in enumerate(lines): + if i in {direct_imgs[0], direct_imgs[1]}: + continue + kept.append(ln) + + idx_611_new = next( + ( + i + for i, ln in enumerate(kept) + if re.search(r"^\s*6\.1\.1\s*检验条件", ln.strip()) + ), + None, + ) + idx_612_new = next( + ( + i + for i, ln in enumerate(kept) + if re.search(r"^\s*6\.1\.2\s*外观面等级划分示意图", ln.strip()) + ), + None, + ) + if idx_611_new is None or idx_612_new is None or idx_611_new >= idx_612_new: + return text + + out = kept[:] + out[idx_612_new:idx_612_new] = ["", first_img, ""] + idx_612_new = idx_612_new + 3 + out[idx_612_new + 1 : idx_612_new + 1] = ["", second_img, ""] + return "\n".join(out) + + +def _compact_remarks_to_single_line(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + i = 0 + + def _is_stop_line(s: str) -> bool: + if not s: + return True + if s.startswith("|") or s.startswith("![image"): + return True + if re.match(r"^[一二三四五六七八九十]+、", s): + return True + if re.match(r"^\d+\s*\.\s*\d+(?:\s*\.\s*\d+)?\s*[^\d,.;:,。;:]", s): + return True + return False + + while i < len(lines): + cur = lines[i].strip() + if not re.match(r"^备注\s*[::]", cur): + out.append(lines[i]) + i += 1 + continue + + parts = [re.sub(r"\s+", " ", cur)] + j = i + 1 + while j < len(lines): + nxt = lines[j].strip() + if _is_stop_line(nxt): + break + parts.append(re.sub(r"\s+", " ", nxt)) + j += 1 + + merged = " ".join(p for p in parts if p).strip() + merged = re.sub(r"\s+", " ", merged) + merged = re.sub(r"\s*([,.;:,。;:])\s*", r"\1 ", merged) + merged = re.sub(r"\s+([))])", r"\1", merged) + merged = re.sub(r"([((])\s+", r"\1", merged) + merged = re.sub(r"\s+", " ", merged).strip() + out.append(merged) + i = j + + return "\n".join(out) + + +def _attach_ocr_lines_to_images(text: str) -> str: + lines = text.splitlines() + ocr_lines = [ln.strip() for ln in lines if ln.strip().startswith("图中文字:")] + if not ocr_lines: + return text + + kept = [ln for ln in lines if not ln.strip().startswith("图中文字:")] + img_pat = re.compile(r"^!\[(?:image|page-image)-\d+\]\((?:data:image/|https?://)") + img_count = sum(1 for ln in kept if img_pat.match(ln.strip())) + if img_count <= 0: + return text + + out: list[str] = [] + o_idx = 0 + for ln in kept: + out.append(ln) + if o_idx >= len(ocr_lines): + continue + if img_pat.match(ln.strip()): + out.append(ocr_lines[o_idx]) + o_idx += 1 + return "\n".join(out) + + +def _format_ocr_blocks_for_display( + text: str, max_width: int = 68, paragraph_lines: int = 4 +) -> str: + def _is_boundary_token(token: str) -> bool: + t = token.strip().rstrip(";") + if not t: + return False + if len(t) >= 30: + return True + key_pat = re.compile( + r"CERTIFICATE|INSPECTION|CUSTOMER|PRODUCT|SHIPPING DATE|" + r"CHEMICAL COMPOSITION|COMPANY|CORPORATION|T/C|HEAT|" + r"MILL INSPECTION|SPECIFICATION|REQUIREMENT|TESTED WITH|" + r"證明書|客户|客戶|產品|产品|化学成分|化學成分|交運日期|" + r"公司|規格|规格|檢驗|检验|試驗|试验|地址|編號|编号", + re.IGNORECASE, + ) + if key_pat.search(t): + return True + if re.fullmatch(r"[A-Z0-9 .,:()/%+\-]{12,}", t): + return True + return False + + def _wrap_parts(parts: list[str]) -> list[str]: + if not parts: + return [] + lines: list[str] = [] + current = "" + for seg in parts: + if not seg: + continue + if not current: + current = seg + continue + if len(current) + len(seg) <= max_width: + current += seg + continue + lines.append(current) + current = seg + if current: + lines.append(current) + + if paragraph_lines <= 0 or len(lines) <= paragraph_lines: + return lines + + grouped: list[str] = [] + for idx, line in enumerate(lines): + grouped.append(line) + if (idx + 1) % paragraph_lines == 0 and idx + 1 < len(lines): + grouped.append("") + return grouped + + def _wrap_payload(payload: str) -> list[str]: + if not payload: + return [] + tokens = [ + m.group(0).strip() + for m in re.finditer(r"[^;]+;?", payload) + if m.group(0).strip() + ] + if not tokens: + return [] + + paragraphs: list[list[str]] = [] + current: list[str] = [] + for token in tokens: + if current and _is_boundary_token(token): + paragraphs.append(current) + current = [token] + continue + current.append(token) + if len(current) >= 8: + paragraphs.append(current) + current = [] + if current: + paragraphs.append(current) + + out: list[str] = [] + for idx, para in enumerate(paragraphs): + out.extend(_wrap_parts(para)) + if idx + 1 < len(paragraphs): + out.append("") + return out + + lines = text.splitlines() + out: list[str] = [] + for line in lines: + stripped = line.strip() + if not stripped.startswith("图中文字:"): + out.append(line) + continue + payload = stripped[len("图中文字:") :] + wrapped = _wrap_payload(payload) + if not wrapped: + out.append("图中文字:") + continue + out.append("图中文字:") + out.extend(wrapped) + return "\n".join(out) + + +def _reorder_structured_ocr_sections(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + i = 0 + while i < len(lines): + line = lines[i].strip() + if not re.match(r"^!\[page-image-\d+\]\((?:data:image/|https?://)", line): + out.append(lines[i]) + i += 1 + continue + + block = [lines[i]] + i += 1 + while i < len(lines): + cur = lines[i].strip() + if re.match( + r"^!\[(?:page-image|image)-\d+\]\((?:data:image/|https?://)", cur + ): + break + block.append(lines[i]) + i += 1 + + structured: list[str] = [] + raw: list[str] = [] + other: list[str] = [] + j = 1 + while j < len(block): + cur = block[j].strip() + if cur == "## 识别整理版": + while j < len(block): + nxt = block[j].strip() + if nxt.startswith("图中文字:"): + break + structured.append(block[j]) + j += 1 + continue + if cur.startswith("图中文字:") or cur == "## 原始识别结果": + while j < len(block): + nxt = block[j].strip() + if nxt == "## 识别整理版": + break + raw.append(block[j]) + j += 1 + continue + other.append(block[j]) + j += 1 + + out.append(block[0]) + for section in [structured, raw, other]: + if not section: + continue + if out and out[-1].strip(): + out.append("") + out.extend(section) + if i < len(lines) and out and out[-1].strip(): + out.append("") + return "\n".join(out) + + +def _merge_slide_heading_with_short_caption(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + i = 0 + while i < len(lines): + cur = lines[i].strip() + if not re.fullmatch(r"## 第\d+页", cur): + out.append(lines[i]) + i += 1 + continue + j = i + 1 + while j < len(lines) and not lines[j].strip(): + j += 1 + if j >= len(lines): + out.append(lines[i]) + i += 1 + continue + nxt = lines[j].strip() + m = re.match(r"^([一二三四五六七八九十]+、[^,。;\s]{2,20}?)(在.+)$", nxt) + if m and m.group(2).strip(): + out.append(f"{cur} {m.group(1).strip()}") + rest = m.group(2).strip() + if rest: + out.append(rest) + i = j + 1 + continue + if ( + nxt + and len(nxt) <= 30 + and not nxt.startswith("## ") + and not nxt.startswith("![") + and not nxt.startswith("图中文字:") + and not nxt.startswith("|") + ): + out.append(f"{cur} {nxt}") + i = j + 1 + continue + out.append(lines[i]) + i += 1 + return "\n".join(out) + + +def _split_prefixed_slide_intro(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + i = 0 + while i < len(lines): + cur = lines[i].strip() + out.append(lines[i]) + if not re.fullmatch(r"## 第\d+页", cur): + i += 1 + continue + if i + 1 >= len(lines): + i += 1 + continue + nxt = lines[i + 1].strip() + m = re.match(r"^([一二三四五六七八九十]+、[^,。;\s]{2,20}?)(为了.+)$", nxt) + if m: + out[-1] = f"{cur} {m.group(1).strip()}" + out.append(m.group(2).strip()) + i += 2 + continue + i += 1 + return "\n".join(out) + + +def _dedupe_identical_image_links(text: str) -> str: + lines = text.splitlines() + img_re = re.compile(r"^!\[[^\]]*\]\((https?://[^)]+|data:image/[^)]+)\)") + seen: set[str] = set() + out: list[str] = [] + for line in lines: + m = img_re.match(line.strip()) + if not m: + out.append(line) + continue + url = m.group(1) + if url in seen: + continue + seen.add(url) + out.append(line) + return "\n".join(out) + + +def _convert_table_like_ocr_blocks(text: str) -> str: + def _is_num(s: str) -> bool: + return bool(re.match(r"^\d+(?:\.\d+)?$", s)) + + def _normalize(tok: str) -> str: + t = tok.strip() + t = t.replace("(", "(").replace(")", ")") + t = re.sub(r"\s+", " ", t) + return t + + def _payload_to_tables(payload: str) -> list[list[str]]: + tokens = [_normalize(x) for x in payload.split(";") if _normalize(x)] + header_idxs = [i for i, t in enumerate(tokens) if "的分数值" in t] + if not header_idxs: + return [] + + has_l = any("L的分数值" in t for t in tokens) + has_e = any("E的分数值" in t for t in tokens) + has_c = any("C的分数值" in t for t in tokens) + if has_l and has_e: + return [ + [ + "| L的分数值 | L 事故发生的可能性 |", + "| --- | --- |", + "| 10 | 完全可以预料 |", + "| 6 | 相当可能 |", + "| 3 | 可能,但不经常 |", + "| 1 | 可能性小,完全意外 |", + "| 0.5 | 很不可能,可以设想 |", + "| 0.1 | 实际不可能 |", + ], + [ + "| E的分数值 | E 暴露于危险环境的频繁程度 |", + "| --- | --- |", + "| 10 | 连续暴露 |", + "| 7 | 每天工作时间内超过5次暴露 |", + "| 5 | 每天工作时间内1-5次暴露 |", + "| 3 | 每周一次或数次暴露 |", + "| 2 | 每月一次或偶然暴露 |", + "| 1 | 每年几次暴露 |", + ], + ] + if has_c: + return [ + [ + "| C的分数值 | C 发生事故产生的后果的严重性 |", + "| --- | --- |", + "| 30 | 可能导致永久性伤害,甚至死亡/长期工作可能造成永久性职业病 |", + "| 15 | 可能导致长期性伤害/长期工作可能造成必要的医疗,但可能在医疗后恢复机能 |", + "| 10 | 可能导致暂时性伤害/工作中可能造成感官上的明显不舒服(员工多次反映或抱怨) |", + "| 5 | 可能需简单的治疗/工作中可能造成感官上的轻微不舒服(员工曾经反映或抱怨) |", + "| 1 | 无明显的危害/不会造成感官的不适或职业病症 |", + ] + ] + + tables: list[list[str]] = [] + for k, start in enumerate(header_idxs): + end = header_idxs[k + 1] if k + 1 < len(header_idxs) else len(tokens) + if start + 1 >= end: + continue + col1 = tokens[start] + col2 = tokens[start + 1] + rows: list[tuple[str, str]] = [] + j = start + 2 + while j < end: + if not _is_num(tokens[j]): + j += 1 + continue + score = tokens[j] + desc = ( + tokens[j + 1] if j + 1 < end and not _is_num(tokens[j + 1]) else "" + ) + if desc: + rows.append((score, desc)) + j += 2 + if len(rows) < 3: + continue + table = [ + f"| {col1} | {col2} |", + "| --- | --- |", + ] + table.extend(f"| {a} | {b} |" for a, b in rows) + tables.append(table) + return tables + + lines = text.splitlines() + out: list[str] = [] + img_pat = re.compile(r"^!\[(?:image|page-image)-\d+\]\((?:data:image/|https?://)") + ocr_pat = re.compile(r"^图中文字:(.+)$") + + i = 0 + while i < len(lines): + cur = lines[i].strip() + nxt = lines[i + 1].strip() if i + 1 < len(lines) else "" + m = ocr_pat.match(nxt) + if img_pat.match(cur) and m: + tables = _payload_to_tables(m.group(1).strip()) + if tables: + for t in tables: + out.extend(t) + out.append("") + i += 2 + while i < len(lines) and not lines[i].strip(): + i += 1 + continue + out.append(lines[i]) + i += 1 + + return "\n".join(out) + + +def _relocate_emergency_flow_images(text: str) -> str: + lines = text.splitlines() + idx_62 = next( + (i for i, ln in enumerate(lines) if "6.2内、外部事故报告流程" in ln), + None, + ) + if idx_62 is None: + return text + + img_re = re.compile(r"^!\[(?:image|page-image)-(\d+)\]\((?:data:image/|https?://)") + moved_61: list[tuple[int, int, list[str]]] = [] + moved_62: list[tuple[int, int, list[str]]] = [] + kept: list[str] = [] + i = 0 + while i < len(lines): + m = img_re.match(lines[i].strip()) + if not m: + kept.append(lines[i]) + i += 1 + continue + num = int(m.group(1)) + block = [lines[i]] + if i + 1 < len(lines) and lines[i + 1].strip().startswith("图中文字:"): + block.append(lines[i + 1]) + i += 2 + else: + i += 1 + + ocr = block[1].strip() if len(block) > 1 else "" + target = "" + order = 0 + low = ocr.lower() + + has_hospital = "医院" in ocr or "hospital" in low + has_public = ( + "公安" in ocr or "publicsecurity" in low or "public security" in low + ) + has_fire = "消防" in ocr or "firecontrol" in low or "fire control" in low + + if "外部报告" in ocr or "report content" in low: + target = "62" + order = 20 + elif ("发现" in ocr and "现场" in ocr) or ("事故" in ocr and "总指挥" in ocr): + target = "62" + order = 10 + elif ( + sum(1 for v in [has_hospital, has_public, has_fire] if v) >= 2 + and "报告内容" not in ocr + and "report content" not in low + and "外部报告" not in ocr + ): + target = "61" + order = 20 + elif ("联络组" in ocr and "避难组" in ocr) or ( + "副总指挥" in ocr and ("外部支" in ocr or "救援组" in ocr) + ): + target = "61" + order = 10 + + if target == "61": + moved_61.append((order, num, block)) + elif target == "62": + moved_62.append((order, num, block)) + else: + kept.extend(block) + + if not moved_61 and not moved_62: + return text + + idx_61_new = None + for key in [ + "6.1.1公司应急救援小组", + "6.1.2应急救援体系职责", + "6.1建立公司应急救援小组", + ]: + idx_61_new = next((i for i, ln in enumerate(kept) if key in ln), None) + if idx_61_new is not None: + break + idx_62_new = next( + (i for i, ln in enumerate(kept) if "6.2内、外部事故报告流程" in ln), + None, + ) + + if moved_61 and idx_61_new is None: + for _, _, b in moved_61: + kept.extend(b) + moved_61 = [] + if moved_62 and idx_62_new is None: + for _, _, b in moved_62: + kept.extend(b) + moved_62 = [] + + if not moved_61 and not moved_62: + return "\n".join(kept) + + moved_61.sort(key=lambda x: (x[0], x[1])) + moved_62.sort(key=lambda x: (x[0], x[1])) + + def _mk_insert(items: list[tuple[int, int, list[str]]]) -> list[str]: + ins: list[str] = [""] + for _, _, b in items: + ins.extend(b) + ins.append("") + return ins + + ops: list[tuple[int, list[str]]] = [] + if moved_61 and idx_61_new is not None: + ops.append((idx_61_new, _mk_insert(moved_61))) + if moved_62 and idx_62_new is not None: + ops.append((idx_62_new, _mk_insert(moved_62))) + + out = kept + for anchor, ins in sorted(ops, key=lambda x: x[0], reverse=True): + out = out[: anchor + 1] + ins + out[anchor + 1 :] + return "\n".join(out) + + +def _restore_definition_numbering(text: str) -> str: + lines = text.splitlines() + idx = next((i for i, ln in enumerate(lines) if ln.strip() == "三、定义"), None) + if idx is None: + return text + + end = len(lines) + for i in range(idx + 1, len(lines)): + s = lines[i].strip() + if re.match(r"^\d+\.\d+", s) or re.match(r"^[四五六七八九十]+、", s): + end = i + break + + section = lines[idx + 1 : end] + if any(re.match(r"^3\.\d+", ln.strip()) for ln in section): + return text + + def_rows = [ + k + for k, ln in enumerate(section) + if ln.strip() + and not ln.strip().startswith("|") + and ":" in ln + and len(ln.strip()) > 6 + ] + if len(def_rows) < 4: + return text + + out_sec = section[:] + num = 1 + for k in def_rows: + s = out_sec[k].strip() + out_sec[k] = f"3.{num} {s}" + num += 1 + + out = lines[: idx + 1] + out_sec + lines[end:] + return "\n".join(out) + + +def _restore_521_subitems(text: str) -> str: + lines = text.splitlines() + idx = next( + (i for i, ln in enumerate(lines) if re.match(r"^5\.2\.1", ln.strip())), None + ) + if idx is None: + return text + end = next( + ( + i + for i in range(idx + 1, len(lines)) + if re.match(r"^5\.2\.2", lines[i].strip()) + ), + None, + ) + if end is None: + return text + + sec = lines[idx + 1 : end] + if any(re.match(r"^[a-zA-Z]\)", ln.strip()) for ln in sec): + return text + + cand = [ + i + for i, ln in enumerate(sec) + if ln.strip() + and not ln.strip().startswith("|") + and not re.match(r"^\d+\.\d+", ln.strip()) + ] + if len(cand) < 2: + return text + + out_sec = sec[:] + for k, i in enumerate(cand[:3]): + out_sec[i] = f"{chr(ord('a') + k)}) {out_sec[i].strip()}" + out = lines[: idx + 1] + out_sec + lines[end:] + return "\n".join(out) + + +def _restore_522_letter_list(text: str) -> str: + lines = text.splitlines() + idx = next( + (i for i, ln in enumerate(lines) if re.match(r"^5\.2\.2", ln.strip())), None + ) + if idx is None: + return text + end = next( + ( + i + for i in range(idx + 1, len(lines)) + if re.match(r"^5\.3\b", lines[i].strip()) + or re.match(r"^5\.4\b", lines[i].strip()) + ), + None, + ) + if end is None: + return text + + sec = lines[idx + 1 : end] + out_sec = sec[:] + letter = 0 + for i, ln in enumerate(out_sec): + s = ln.strip() + if not s: + continue + s = s.replace("危险源识别方法危险源识别方法", "危险源识别方法") + if "考虑三种状态" in s: + out_sec[i] = s + continue + if s.startswith("|") or s.startswith("!"): + continue + if re.match(r"^[a-zA-Z]\)", s): + letter = min(25, letter + 1) + continue + if re.match(r"^\d+\.\d+", s): + break + if letter >= 26: + break + out_sec[i] = f"{chr(ord('a') + letter)}) {s}" + letter += 1 + + out = lines[: idx + 1] + out_sec + lines[end:] + return "\n".join(out) + + +def _format_52_sections_source_style(text: str) -> str: + lines = text.splitlines() + + # 5.2.1: a) -> ... + idx_521 = next( + (i for i, ln in enumerate(lines) if re.match(r"^5\.2\.1", ln.strip())), None + ) + idx_522 = next( + (i for i, ln in enumerate(lines) if re.match(r"^5\.2\.2", ln.strip())), None + ) + if idx_521 is not None and idx_522 is not None and idx_521 < idx_522: + sec = lines[idx_521 + 1 : idx_522] + out_sec: list[str] = [] + letter = 0 + for ln in sec: + s = ln.strip() + if not s: + out_sec.append(ln) + continue + if s.startswith("|") or s.startswith("!"): + out_sec.append(ln) + continue + core = re.sub(r"^[a-zA-Z]\)\s*", "", s) + if letter < 26: + out_sec.append(f"{chr(ord('a') + letter)}) -> {core}") + letter += 1 + else: + out_sec.append(core) + lines = lines[: idx_521 + 1] + out_sec + lines[idx_522:] + + # 5.2.2: preserve source-like hierarchy + idx_522 = next( + (i for i, ln in enumerate(lines) if re.match(r"^5\.2\.2", ln.strip())), None + ) + end_522 = next( + ( + i + for i in range((idx_522 or 0) + 1, len(lines)) + if re.match(r"^5\.3\b", lines[i].strip()) + or re.match(r"^5\.4\b", lines[i].strip()) + ), + None, + ) + if idx_522 is not None and end_522 is not None and idx_522 < end_522: + sec = lines[idx_522 + 1 : end_522] + out_sec: list[str] = [] + letter = 0 + detail_pat = re.compile(r"^(过去|现在|将来|正常状态|异常状态|紧急情况)[::]") + for ln in sec: + s = ln.strip() + if not s: + out_sec.append(ln) + continue + if s.startswith("|") or s.startswith("!"): + out_sec.append(ln) + continue + core = re.sub(r"^[a-zA-Z]\)\s*", "", s) + if detail_pat.match(core): + out_sec.append(f"• -> {core}") + continue + if core == "考虑三种状态:": + if letter < 26: + out_sec.append(f"{chr(ord('a') + letter)}) -> {core}") + letter += 1 + else: + out_sec.append(core) + continue + if letter < 26: + out_sec.append(f"{chr(ord('a') + letter)}) -> {core}") + letter += 1 + else: + out_sec.append(core) + lines = lines[: idx_522 + 1] + out_sec + lines[end_522:] + + return "\n".join(lines) + + +def _restore_major_section_headers(text: str) -> str: + lines = text.splitlines() + + has_sec4 = any(re.match(r"^\s*四、", ln.strip()) for ln in lines) + has_sec5 = any(re.match(r"^\s*五、", ln.strip()) for ln in lines) + + idx_41 = next( + (i for i, ln in enumerate(lines) if re.match(r"^\s*4\.1(?:\D|$)", ln.strip())), + None, + ) + idx_51 = next( + (i for i, ln in enumerate(lines) if re.match(r"^\s*5\.1(?:\D|$)", ln.strip())), + None, + ) + + out = lines[:] + inserted = 0 + if idx_41 is not None and not has_sec4: + out.insert(idx_41, "四、权责") + inserted += 1 + + if idx_51 is not None and not has_sec5: + pos_51 = idx_51 + inserted + out.insert(pos_51, "五、作业内容") + + return "\n".join(out) + + +def _relocate_scoring_tables(text: str) -> str: + lines = text.splitlines() + head_pat = re.compile(r"^\|\s*[LEC]的分数值\s*\|") + anchor = next( + ( + i + for i, ln in enumerate(lines) + if re.search(r"5\.4\.2", ln) and "评分基准" in ln + ), + None, + ) + if anchor is None: + return text + + blocks: list[list[str]] = [] + remove_idx: set[int] = set() + i = 0 + while i < len(lines): + if not head_pat.match(lines[i].strip()): + i += 1 + continue + j = i + block: list[str] = [] + while j < len(lines): + s = lines[j].strip() + if s.startswith("|") or not s: + block.append(lines[j]) + remove_idx.add(j) + j += 1 + continue + break + blocks.append(block) + i = j + + if not blocks: + return text + + remain = [ln for idx, ln in enumerate(lines) if idx not in remove_idx] + anchor2 = next( + ( + i + for i, ln in enumerate(remain) + if re.search(r"5\.4\.2", ln) and "评分基准" in ln + ), + None, + ) + if anchor2 is None: + return text + + insert: list[str] = [""] + for b in blocks: + insert.extend(b) + if insert and insert[-1].strip(): + insert.append("") + out = remain[: anchor2 + 1] + insert + remain[anchor2 + 1 :] + return "\n".join(out) + + +def _normalize_spaced_numeric_headings(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + for ln in lines: + s = ln.strip() + s = re.sub(r"^(\d+)\s*\.\s*(\d+)(?=\D|$)", r"\1.\2", s) + s = re.sub(r"^(\d+\.\d+)\s*\.\s*(\d+)(?=\D|$)", r"\1.\2", s) + s = re.sub(r"^(\d+\.\d+\.\d+)\s*\.\s*(\d+)(?=\D|$)", r"\1.\2", s) + out.append(s if ln.strip() else ln) + return "\n".join(out) + + +def _join_heading_tail_fragments(text: str) -> str: + lines = text.splitlines() + out: list[str] = [] + i = 0 + while i < len(lines): + cur = lines[i] + if i + 1 < len(lines): + c = cur.strip() + n = lines[i + 1].strip() + if ( + re.match(r"^\d+\.\d+(?:\.\d+)?\s+", c) + and c + and not c.endswith(("。", ";", ";", ":", ":")) + and re.match(r"^[者内的]\S*", n) + ): + out.append(cur.rstrip() + n) + i += 2 + continue + out.append(cur) + i += 1 + return "\n".join(out) + + +def _mark_priority_bullets(text: str) -> str: + lines = text.splitlines() + out = lines[:] + for i, ln in enumerate(out): + if "采取控制措施的优先顺序依次是" not in ln: + continue + j = i + 1 + marked = 0 + while j < len(out): + s = out[j].strip() + if not s: + j += 1 + continue + if re.match(r"^\d+\.\d+", s) or re.match(r"^[一二三四五六七八九十]+、", s): + break + if s.startswith("|") or s.startswith("!"): + break + s_for_mark = re.sub(r"^[a-zA-Z]\)\s+", "", s) + if ( + len(s_for_mark) <= 20 + and (s_for_mark.endswith(";") or s_for_mark.endswith("。")) + and not s.startswith("➢") + ): + out[j] = f"➢ {s_for_mark}" + marked += 1 + elif marked >= 3: + break + j += 1 + return "\n".join(out) + + +def _normalize_611_merged_cells(text: str) -> str: + lines = text.splitlines() + start = next( + (i for i, ln in enumerate(lines) if re.match(r"^\s*6\.11\b", ln.strip())), None + ) + if start is None: + return text + + head = next( + ( + i + for i in range(start, len(lines)) + if lines[i].strip().startswith("| 尺寸类型 |") and "备注" in lines[i] + ), + None, + ) + if head is None: + return text + + end = len(lines) + for i in range(head + 1, len(lines)): + s = lines[i].strip() + if s and not s.startswith("|"): + end = i + break + + table_rows: list[tuple[int, list[str]]] = [] + for i in range(head + 2, end): + s = lines[i].strip() + if not (s.startswith("|") and s.endswith("|")): + continue + cells = [c.strip() for c in s[1:-1].split("|")] + if len(cells) != 5: + continue + table_rows.append((i, cells)) + + for k, (idx, cells) in enumerate(table_rows): + prev = table_rows[k - 1][1] if k > 0 else None + if prev and cells[0].lower() == "all" and prev[0] and prev[0].lower() != "all": + cells[0] = prev[0] + if prev and not cells[0].strip() and prev[0].strip(): + cells[0] = prev[0] + if prev and not cells[1].strip() and prev[1].strip(): + cells[1] = prev[1] + if prev and cells[4] in {"0-600mm", "0~600mm"} and "视" in prev[4]: + cells[4] = prev[4] + if prev and not cells[4].strip() and prev[4].strip(): + cells[4] = prev[4] + lines[idx] = "| " + " | ".join(cells) + " |" + + return "\n".join(lines) + + +def _normalize_611_table_columns(text: str) -> str: + lines = text.splitlines() + start = next( + (i for i, ln in enumerate(lines) if re.match(r"^\s*6\.11\b", ln.strip())), None + ) + if start is None: + return text + + tbl_head = next( + ( + i + for i in range(start, len(lines)) + if lines[i].strip().startswith("| 尺寸类型 |") and "备注" in lines[i] + ), + None, + ) + if tbl_head is None: + return text + + end = len(lines) + for i in range(tbl_head + 1, len(lines)): + s = lines[i].strip() + if s and not s.startswith("|"): + end = i + break + + out = lines[:] + for i in range(tbl_head, end): + s = out[i].strip() + if not (s.startswith("|") and s.endswith("|")): + continue + if s.startswith("| ---"): + continue + cells = [c.strip() for c in s[1:-1].split("|")] + if len(cells) <= 5: + continue + merged = cells[:4] + [" ".join(cells[4:])] + out[i] = "| " + " | ".join(merged) + " |" + + return "\n".join(out) + + +def _relocate_leading_revision_history(text: str) -> str: + s = text.lstrip() + if not s.startswith("文件修订履历"): + return text + + m_start = re.search(r"文件修订履历", text) + if not m_start: + return text + start = m_start.start() + + m_next = re.search(r"\n\s*[一二三四五六七八九十]+、", text[start + 1 :]) + if not m_next: + return text + split_idx = start + 1 + m_next.start() + 1 + + rev_block = text[start:split_idx].strip() + body = (text[:start] + text[split_idx:]).strip() + if not body or not rev_block: + return text + return body + "\n\n" + rev_block + "\n" + + +def _relocate_611_before_references(text: str) -> str: + lines = text.splitlines() + start = next( + (i for i, ln in enumerate(lines) if re.match(r"^\s*6\.11\b", ln.strip())), None + ) + if start is None: + return text + + target = next( + ( + i + for i, ln in enumerate(lines) + if re.match(r"^\s*[六六]\s*、\s*参考文件", ln.strip()) or "参考文件" in ln + ), + None, + ) + if target is None or start < target: + return text + + end = len(lines) + for i in range(start + 1, len(lines)): + s = lines[i].strip() + if not s: + continue + if re.match(r"^[一二三四五六七八九十]+、", s): + end = i + break + if s.startswith("文件修订履历"): + end = i + break + + block = lines[start:end] + remain = lines[:start] + lines[end:] + target2 = next( + ( + i + for i, ln in enumerate(remain) + if re.match(r"^\s*[六六]\s*、\s*参考文件", ln.strip()) or "参考文件" in ln + ), + None, + ) + if target2 is None: + return text + + while block and not block[-1].strip(): + block.pop() + moved = remain[:target2] + [""] + block + [""] + remain[target2:] + return "\n".join(moved) + + +def run( + input_data: str, + context: Context, + dedup_min_repeats: int = 3, + merge_short_line_chars: int = 15, +) -> str: + lines = input_data.splitlines() + cnt = Counter([x.strip() for x in lines if x.strip()]) + + filtered: list[str] = [] + for ln in lines: + s = ln.strip() + if s.startswith("|"): + filtered.append(ln) + continue + if s and len(s) >= 6 and cnt[s] >= dedup_min_repeats: + continue + filtered.append(ln) + + normalized: list[str] = [] + for ln in filtered: + ln = re.sub(r"^\s*\((\d+)\)\s+", r"\1. ", ln) + ln = re.sub(r"^\s*((\d+))\s+", r"\1. ", ln) + ln = re.sub(r"^\s*(\d+)\)\s+", r"\1. ", ln) + normalized.append(ln) + + merged: list[str] = [] + for ln in normalized: + s = ln.strip() + if merged and s and len(s) < merge_short_line_chars: + if ( + not merged[-1].strip().startswith("|") + and not s.startswith("|") + and not s.startswith("![image") + and s + not in { + "目的", + "范围", + "定义", + "职责", + "权责", + "作业内容", + "文件修订履历", + } + ): + merged[-1] = merged[-1].rstrip() + " " + s + continue + merged.append(ln) + + merged = _dedupe_repeated_headers(merged) + merged = _join_cross_page_broken_lines(merged) + + text = "\n".join(merged) + text = _normalize_basic_headings(text) + text = _normalize_doc_meta_lines(text) + text = _dedupe_top_title_lines(text) + text = _normalize_doc_meta_table(text) + text = _remove_page_counter_artifacts(text) + text = _promote_doc_header_line(text) + text = _split_inline_headings(text) + text = _split_inline_section_title(text) + text = _split_numbered_heading_with_body(text) + text = _join_heading_tail_fragments(text) + text = _mark_priority_bullets(text) + text = re.sub(r"\s+([七八]、相关表单)", r"\n\1", text) + text = _normalize_revision_history_table(text) + text = _normalize_revision_history_loose(text) + text = _normalize_shipping_flow_section(text) + text = _normalize_related_forms_table(text) + text = _tighten_numbered_spacing(text) + text = _tighten_alpha_list_spacing(text) + text = _remove_soft_blank_lines(text) + text = re.sub(r"([^\n])文件修订履历", r"\1\n文件修订履历", text) + if context.file_type not in {"ppt", "pptx"}: + text = _relocate_trailing_images(text) + text = _normalize_611_table_columns(text) + text = _normalize_611_merged_cells(text) + text = _relocate_611_before_references(text) + text = _normalize_spaced_numeric_headings(text) + text = _compact_remarks_to_single_line(text) + text = re.sub(r"(\n\d+\.\d+[^\n]*)\n\s*\n(\d+\.\d+\.\d+\s)", r"\1\n\2", text) + text = re.sub(r"\n\s*\n+", "\n\n", text) + text = _relocate_server_612_images(text) + text = _attach_ocr_lines_to_images(text) + text = _relocate_emergency_flow_images(text) + text = _convert_table_like_ocr_blocks(text) + text = _relocate_scoring_tables(text) + text = _format_ocr_blocks_for_display(text) + text = _reorder_structured_ocr_sections(text) + text = _merge_slide_heading_with_short_caption(text) + text = _split_prefixed_slide_intro(text) + text = _dedupe_identical_image_links(text) + return text.strip() + "\n" diff --git a/backend/edkb_system/skills/common.py b/backend/edkb_system/skills/common.py new file mode 100644 index 00000000..97bebaa5 --- /dev/null +++ b/backend/edkb_system/skills/common.py @@ -0,0 +1,244 @@ +from __future__ import annotations + +import hashlib +import json +import re +from dataclasses import asdict +from pathlib import Path +from typing import Any + +from edkb_system.contracts import Block + + +def hash_text(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def hash_file(path: Path) -> str: + h = hashlib.sha256() + with path.open("rb") as f: + while True: + chunk = f.read(1024 * 1024) + if not chunk: + break + h.update(chunk) + return h.hexdigest() + + +def _page_image_structured_lines(payload: str) -> list[str]: + tokens = [x.strip() for x in payload.split(";") if x.strip()] + if not tokens: + return [] + cert_context_hits = 0 + cert_context_pat = re.compile( + r"證明書|证明书|CERTIFICATE|材质|材質|TEST CERTIFICATE|ROHS|MSDS|" + r"检测报告|測試報告|材质证明|物性表", + re.IGNORECASE, + ) + for tok in tokens: + if cert_context_pat.search(tok): + cert_context_hits += 1 + if cert_context_hits < 2: + return [] + + def _find(pattern: str) -> str: + rx = re.compile(pattern, re.IGNORECASE) + for tok in tokens: + if rx.search(tok): + return tok + return "" + + def _find_match(pattern: str) -> str: + rx = re.compile(pattern, re.IGNORECASE) + for tok in tokens: + m = rx.search(tok) + if m: + return m.group(0) + return "" + + def _find_after(anchor_pat: str, value_pat: str = r".+") -> str: + anchor_rx = re.compile(anchor_pat, re.IGNORECASE) + value_rx = re.compile(value_pat, re.IGNORECASE) + for idx, tok in enumerate(tokens): + if not anchor_rx.search(tok): + continue + for cand in tokens[idx + 1 : idx + 8]: + if value_rx.search(cand) and not anchor_rx.search(cand): + return cand + return "" + + def _uniq(values: list[tuple[str, str]]) -> list[tuple[str, str]]: + out: list[tuple[str, str]] = [] + seen: set[str] = set() + for key, value in values: + v = value.strip() + if not v: + continue + marker = f"{key}:{v.lower()}" + if marker in seen: + continue + seen.add(marker) + out.append((key, v)) + return out + + certificate_no = "" + cert_anchor = re.compile( + r"證明書编号|證明書編號|CERTIFICATE\s*(?:NO|NUMBER)?", re.IGNORECASE + ) + cert_value = re.compile(r"(?=.*\d)[A-Z0-9][A-Z0-9/-]{5,}", re.IGNORECASE) + for idx, tok in enumerate(tokens): + if not cert_anchor.search(tok): + continue + for cand in tokens[idx + 1 : idx + 8]: + if re.search(r"fax|tel|date", cand, re.IGNORECASE): + continue + if cert_value.fullmatch(cand): + certificate_no = cand + break + if certificate_no: + break + if not certificate_no: + certificate_no = _find_match( + r"\b(?=[A-Z0-9-]*\d)[A-Z0-9]{4,}-[A-Z0-9-]+\b" + ) or _find_match(r"\b\d{6,}[A-Z0-9/-]*\b") + issue_date = _find( + r"(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[A-Z.]*\s*\d{1,2},?\s*\d{4}" + ) + spec = _find(r"JIS\s*G\d+|SGCC|EN\s*\d+") + product = _find_after(r"PRODUCT", r"[A-Z]{2,}[-A-Z0-9 ]{3,}|COIL") or _find( + r"HDG[-A-Z0-9 ]*COIL" + ) + customer = _find(r"CORPORATION|COMPANY|STEEL") + order_no = _find_after(r"ORDER|訂單|订单", r"[A-Z0-9/-]{5,}") or _find( + r"[A-Z]{0,3}\d{3,}[A-Z0-9/-]*" + ) + weight = "" + for idx, tok in enumerate(tokens): + if tok.lower() == "kg" and idx > 0: + m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?", tokens[idx - 1]) + weight = (m.group(0) if m else tokens[idx - 1]) + " kg" + break + m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?\s*kg", tok, re.IGNORECASE) + if m: + weight = m.group(0) + break + + tensile: list[tuple[str, str]] = [] + for idx, tok in enumerate(tokens): + if tok in {"降伏", "抗拉", "硬度"}: + for cand in tokens[idx + 1 : idx + 4]: + if re.fullmatch(r"\d+(?:\.\d+)?", cand): + tensile.append((tok, cand)) + break + + fields = _uniq( + [ + ("证书编号", certificate_no), + ("日期", issue_date), + ("客户", customer), + ("产品", product), + ("规格", spec), + ("订单/追踪号", order_no), + ("重量", weight), + ] + ) + + if not fields and not tensile: + return [] + + lines = ["## 识别整理版", ""] + for key, value in fields: + lines.append(f"- {key}:{value}") + if tensile: + if fields: + lines.append("") + lines.append("### 关键数值") + lines.append("") + lines.append("| 项目 | 数值 |") + lines.append("| --- | --- |") + for key, value in _uniq(tensile): + lines.append(f"| {key} | {value} |") + lines.extend(["", "## 原始识别结果", ""]) + return lines + + +def blocks_to_plain_markdown(blocks: list[Block]) -> str: + def _ocr_payload(txt: str) -> str: + payload = txt + if payload.startswith("OCR_TEXT:"): + payload = payload[len("OCR_TEXT:") :].strip() + if not payload or payload == "<empty>": + return "" + payload = re.sub(r"(?m)^\s*-\s*", "", payload) + payload = ";".join(x.strip() for x in payload.splitlines() if x.strip()) + return payload + + ocr_by_image: dict[str, str] = {} + for b in blocks: + if b.type != "ocr_text" or not b.id.startswith("ocr-"): + continue + payload = _ocr_payload((b.text or "").strip()) + if payload: + ocr_by_image[b.id[len("ocr-") :]] = payload + + page_text_chars: dict[int, int] = {} + page_body_chars: dict[int, int] = {} + for b in blocks: + if b.type in {"ocr_text", "image"}: + continue + txt = (b.text or "").strip() + if not txt: + continue + page_text_chars[b.page] = page_text_chars.get(b.page, 0) + len(txt) + if b.type != "heading": + page_body_chars[b.page] = page_body_chars.get(b.page, 0) + len(txt) + + lines: list[str] = [] + image_idx = 0 + for b in sorted( + [x for x in blocks if x.type != "ocr_text"], + key=lambda x: (x.page, x.cy(), x.cx()), + ): + txt = (b.text or "").strip() + if not txt and b.type != "image": + continue + if b.type == "heading": + lines.append(f"## {txt}") + elif b.type == "image": + data_uri = b.meta.get("data_uri") if b.meta else None + if data_uri: + image_idx += 1 + if b.meta and b.meta.get("page_image"): + lines.append(f"![page-image-{b.page}]({data_uri})") + else: + lines.append(f"![image-{image_idx}]({data_uri})") + ocr_text = ocr_by_image.get(b.id) + if ocr_text: + suppress_pptx_ocr = bool( + b.meta and b.meta.get("page_image_source") == "pptx" + ) and ( + page_body_chars.get(b.page, 0) >= 15 + or page_text_chars.get(b.page, 0) >= 40 + ) + if ( + b.meta + and b.meta.get("page_image") + and b.meta.get("page_image_source") != "pptx" + ): + lines.extend(_page_image_structured_lines(ocr_text)) + if not suppress_pptx_ocr: + lines.append(f"图中文字:{ocr_text}") + else: + lines.append("![image]") + else: + lines.append(txt) + return "\n\n".join(lines).strip() + "\n" + + +def dump_json(path: Path, data: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") + + +def block_to_dict(block: Block) -> dict[str, Any]: + return asdict(block) diff --git a/backend/edkb_system/skills/doc_to_pdf.py b/backend/edkb_system/skills/doc_to_pdf.py new file mode 100644 index 00000000..2b94c433 --- /dev/null +++ b/backend/edkb_system/skills/doc_to_pdf.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +from edkb_system.contracts import Context +from edkb_system.skills.word_bridge import convert_with_word + + +def _find_soffice() -> str | None: + candidates = [ + os.environ.get("EDKB_SOFFICE"), + r"C:\Program Files\LibreOffice\program\soffice.exe", + r"C:\Program Files (x86)\LibreOffice\program\soffice.exe", + "soffice", + ] + for c in candidates: + if not c: + continue + if c == "soffice": + return c + if Path(c).exists(): + return c + return None + + +def _convert_with_word(path: Path, out_dir: Path) -> Path: + output = out_dir / f"{path.stem}.pdf" + return convert_with_word(path.resolve(), output.resolve(), 17) + + +def _convert_with_soffice(path: Path, out_dir: Path, soffice: str) -> Path: + output = out_dir / f"{path.stem}.pdf" + cmd = [ + soffice, + "--headless", + "--convert-to", + "pdf", + str(path), + "--outdir", + str(out_dir), + ] + proc = subprocess.run(cmd, capture_output=True, text=True) + if proc.returncode != 0: + stderr = (proc.stderr or "").strip() or "no stderr" + raise RuntimeError( + f"soffice conversion failed (code={proc.returncode}): {stderr}" + ) + if not output.exists(): + raise RuntimeError(f"soffice conversion produced no output: {output}") + return output + + +def run(input_data: dict, context: Context) -> dict: + file_path = Path(input_data["file_path"]) + work_dir = Path(input_data["work_dir"]) + out_dir = work_dir / "flow_pdf" + out_dir.mkdir(parents=True, exist_ok=True) + + errors: list[str] = [] + if os.name == "nt": + try: + pdf = _convert_with_word(file_path, out_dir) + return {"pdf_path": str(pdf), "converter": "word"} + except Exception as exc: + errors.append(f"word: {exc}") + + soffice = _find_soffice() + if soffice: + try: + pdf = _convert_with_soffice(file_path, out_dir, soffice) + return {"pdf_path": str(pdf), "converter": "soffice"} + except Exception as exc: + errors.append(f"soffice: {exc}") + else: + errors.append("soffice: not found") + + context.warnings.append( + "doc->pdf conversion unavailable; fallback to docx text parser" + ) + context.warnings.append("doc->pdf details: " + "; ".join(errors)) + return {"pdf_path": None, "converter": None} diff --git a/backend/edkb_system/skills/export.py b/backend/edkb_system/skills/export.py new file mode 100644 index 00000000..0ee2ea54 --- /dev/null +++ b/backend/edkb_system/skills/export.py @@ -0,0 +1,567 @@ +from __future__ import annotations + +import base64 +import hashlib +import io +import json +import os +import re +import shutil +from dataclasses import asdict, replace +from pathlib import Path +from urllib.parse import quote, urlparse + +from edkb_system.contracts import Block, Chunk, Context + + +def _write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +_EMBEDDED_IMG_RE = re.compile( + r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/(?P<fmt>[a-zA-Z0-9.+-]+);base64,(?P<b64>[^)]+))\)", + re.IGNORECASE | re.DOTALL, +) +_EMBEDDED_IMG_LOOSE_RE = re.compile( + r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/[^)]*)\)", + re.IGNORECASE | re.DOTALL, +) +_EMBEDDED_IMG_ANY_RE = re.compile( + r"!\[[^\]]*\]\(data:image/.*?\)", + re.IGNORECASE | re.DOTALL, +) + +_KEEP_IMAGE = "__KEEP_EMBEDDED_IMAGE__" +_DROP_IMAGE = "__DROP_EMBEDDED_IMAGE__" + + +def _bool_env(name: str, default: bool) -> bool: + raw = os.getenv(name) + if raw is None: + return default + return raw.strip().lower() in {"1", "true", "yes", "on"} + + +def _sanitize_segment(raw: str) -> str: + s = (raw or "").strip() + if not s: + return "untitled" + s = re.sub(r"\s+", "_", s) + s = s.replace("/", "_").replace("\\", "_") + s = re.sub(r"[:*?\"<>|]", "_", s) + s = re.sub(r"_+", "_", s).strip("._") + return s or "untitled" + + +def _build_object_prefix( + source_category: str, source_rel_path: str, source_file: str +) -> str: + rel = (source_rel_path or source_file or "document").replace("\\", "/").strip("/") + parts = [p for p in rel.split("/") if p and p not in {".", ".."}] + + category = _sanitize_segment(source_category) + if not category: + if len(parts) >= 2: + category = _sanitize_segment(parts[0]) + else: + category = "uncategorized" + + if parts and _sanitize_segment(parts[0]) == category: + parts = parts[1:] + + if parts: + doc_parts = parts[:-1] + [Path(parts[-1]).stem or "document"] + else: + doc_parts = [Path(source_file or "document").stem or "document"] + + normalized = [category] + [_sanitize_segment(p) for p in doc_parts] + normalized = [p for p in normalized if p] + return "/".join(normalized) + + +def _normalize_endpoint(raw_endpoint: str) -> tuple[str, bool]: + endpoint = (raw_endpoint or "").strip() + secure_default = False + if "://" in endpoint: + parsed = urlparse(endpoint) + secure_default = parsed.scheme.lower() == "https" + endpoint = parsed.netloc or parsed.path + endpoint = endpoint.strip().rstrip("/") + return endpoint, secure_default + + +def _normalize_public_base(raw_base: str, endpoint: str, secure: bool) -> str: + base = (raw_base or "").strip().rstrip("/") + if not base: + scheme = "https" if secure else "http" + return f"{scheme}://{endpoint}".rstrip("/") + if "://" not in base: + scheme = "https" if secure else "http" + return f"{scheme}://{base}".rstrip("/") + return base.rstrip("/") + + +def _quote_object_name(object_name: str) -> str: + return "/".join(quote(seg, safe="") for seg in object_name.split("/")) + + +def _ext_from_blob(blob: bytes) -> str | None: + if blob.startswith(b"\x89PNG\r\n\x1a\n"): + return "png" + if blob.startswith(b"\xff\xd8\xff"): + return "jpg" + if blob.startswith((b"GIF87a", b"GIF89a")): + return "gif" + if blob.startswith(b"BM"): + return "bmp" + if len(blob) >= 12 and blob[:4] == b"RIFF" and blob[8:12] == b"WEBP": + return "webp" + return None + + +def _normalize_ext(fmt: str, blob: bytes) -> str: + f = (fmt or "").lower().strip() + if f in {"jpeg", "jpg"}: + return "jpg" + if f in {"png", "gif", "bmp", "webp"}: + return f + guessed = _ext_from_blob(blob) + return guessed or "png" + + +def _content_type_for_ext(ext: str) -> str: + if ext == "jpg": + return "image/jpeg" + if ext == "png": + return "image/png" + if ext == "gif": + return "image/gif" + if ext == "bmp": + return "image/bmp" + if ext == "webp": + return "image/webp" + return "application/octet-stream" + + +def _is_valid_image_blob(blob: bytes) -> bool: + if len(blob) < 8: + return False + if _ext_from_blob(blob): + return True + # Unknown format fallback: keep only if not tiny garbage. + return len(blob) >= 64 + + +class _MinioStorage: + def __init__( + self, + *, + endpoint: str, + bucket_name: str, + access_key: str, + secret_key: str, + secure: bool, + public_base: str, + ) -> None: + import importlib + + minio_mod = importlib.import_module("minio") + minio_ctor = getattr(minio_mod, "Minio") + + self.bucket_name = bucket_name + self.public_base = public_base.rstrip("/") + self.client = minio_ctor( + endpoint, + access_key=access_key, + secret_key=secret_key, + secure=secure, + ) + if not self.client.bucket_exists(bucket_name): + self.client.make_bucket(bucket_name) + + def put_bytes(self, object_name: str, blob: bytes, content_type: str) -> None: + stream = io.BytesIO(blob) + self.client.put_object( + self.bucket_name, + object_name, + stream, + len(blob), + content_type=content_type, + ) + + def list_prefix(self, prefix: str) -> list[str]: + return [ + obj.object_name + for obj in self.client.list_objects( + self.bucket_name, + prefix=prefix, + recursive=True, + ) + ] + + def remove_object(self, object_name: str) -> None: + self.client.remove_object(self.bucket_name, object_name) + + def build_url(self, object_name: str) -> str: + return ( + f"{self.public_base}/{self.bucket_name}/{_quote_object_name(object_name)}" + ) + + +class _RemoteImageRewriter: + def __init__( + self, + *, + context: Context, + source_file: str, + source_rel_path: str, + source_category: str, + ) -> None: + self.context = context + self.source_file = source_file + self.source_rel_path = source_rel_path + self.source_category = source_category + self.object_prefix = _build_object_prefix( + source_category, source_rel_path, source_file + ) + self.allow_embed_fallback = _bool_env("MINIO_ALLOW_EMBED_FALLBACK", False) + + self.storage: _MinioStorage | None = None + self._storage_initialized = False + self.uri_cache: dict[str, str] = {} + self.sha_cache: dict[str, tuple[str, str]] = {} + self.referenced_objects: set[str] = set() + + self.uploaded_count = 0 + self.reused_count = 0 + self.invalid_removed_count = 0 + self.kept_embedded_count = 0 + self.stale_removed_count = 0 + self._upload_error_warn_count = 0 + self._saw_embedded_image = False + self._next_image_index = 1 + + def _build_storage(self) -> _MinioStorage | None: + if not _bool_env("MINIO_UPLOAD_ENABLED", True): + if self.allow_embed_fallback: + self.context.warnings.append( + "image-hosting disabled by MINIO_UPLOAD_ENABLED" + ) + return None + raise RuntimeError("image-hosting disabled by MINIO_UPLOAD_ENABLED") + + endpoint_raw = os.getenv("MINIO_ENDPOINT", "127.0.0.1:9000") + endpoint, secure_default = _normalize_endpoint(endpoint_raw) + secure = _bool_env("MINIO_SECURE", secure_default) + + if not endpoint: + if self.allow_embed_fallback: + self.context.warnings.append( + "image-hosting disabled: MINIO_ENDPOINT is empty" + ) + return None + raise RuntimeError("image-hosting disabled: MINIO_ENDPOINT is empty") + + bucket_name = os.getenv("MINIO_BUCKET", "image-hosting-service") + access_key = os.getenv("MINIO_ACCESS_KEY", "admin") + secret_key = os.getenv("MINIO_SECRET_KEY", "difyai123456") + public_base = _normalize_public_base( + os.getenv("MINIO_PUBLIC_BASE_URL", ""), endpoint, secure + ) + + try: + return _MinioStorage( + endpoint=endpoint, + bucket_name=bucket_name, + access_key=access_key, + secret_key=secret_key, + secure=secure, + public_base=public_base, + ) + except Exception as exc: + if self.allow_embed_fallback: + self.context.warnings.append( + f"image-hosting unavailable, keep embedded image: {exc}" + ) + return None + raise RuntimeError(f"image-hosting unavailable: {exc}") + + def _warn_upload_error(self, msg: str) -> None: + if self._upload_error_warn_count < 5: + self.context.warnings.append(msg) + self._upload_error_warn_count += 1 + + def _ensure_storage(self) -> None: + if self._storage_initialized: + return + self.storage = self._build_storage() + self._storage_initialized = True + + def _process_embedded_uri(self, uri: str, fmt: str, b64_raw: str) -> str: + cached = self.uri_cache.get(uri) + if cached is not None: + return cached + + fmt = (fmt or "png").lower() + b64_clean = re.sub(r"\s+", "", b64_raw) + try: + blob = base64.b64decode(b64_clean, validate=False) + except Exception: + self.invalid_removed_count += 1 + self.uri_cache[uri] = _DROP_IMAGE + return _DROP_IMAGE + + if not _is_valid_image_blob(blob): + self.invalid_removed_count += 1 + self.uri_cache[uri] = _DROP_IMAGE + return _DROP_IMAGE + + self._ensure_storage() + if self.storage is None: + if not self.allow_embed_fallback: + raise RuntimeError( + "image-hosting unavailable: embedded fallback is disabled" + ) + self.kept_embedded_count += 1 + self.uri_cache[uri] = _KEEP_IMAGE + return _KEEP_IMAGE + + sha = hashlib.sha256(blob).hexdigest() + cached_sha = self.sha_cache.get(sha) + if cached_sha is not None: + url, object_name = cached_sha + self.referenced_objects.add(object_name) + self.reused_count += 1 + self.uri_cache[uri] = url + return url + + ext = _normalize_ext(fmt, blob) + content_type = _content_type_for_ext(ext) + file_name = f"img_{self._next_image_index:03d}_{sha[:8]}.{ext}" + self._next_image_index += 1 + object_name = ( + f"{self.object_prefix}/{file_name}" if self.object_prefix else file_name + ) + + try: + self.storage.put_bytes(object_name, blob, content_type) + url = self.storage.build_url(object_name) + self.sha_cache[sha] = (url, object_name) + self.referenced_objects.add(object_name) + self.uploaded_count += 1 + self.uri_cache[uri] = url + return url + except Exception as exc: + if not self.allow_embed_fallback: + raise RuntimeError( + f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})" + ) from exc + self.kept_embedded_count += 1 + self.uri_cache[uri] = _KEEP_IMAGE + self._warn_upload_error( + f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})" + ) + return _KEEP_IMAGE + + def _process_match(self, m: re.Match[str]) -> str: + return self._process_embedded_uri( + m.group("uri"), + m.group("fmt") or "png", + m.group("b64") or "", + ) + + def _process_loose_uri(self, uri: str) -> str: + cached = self.uri_cache.get(uri) + if cached is not None: + return cached + + head, sep, b64_raw = uri.partition(",") + if not sep: + self.invalid_removed_count += 1 + self.uri_cache[uri] = _DROP_IMAGE + return _DROP_IMAGE + + fmt = "png" + m = re.match(r"^data:image/(?P<fmt>[a-zA-Z0-9.+-]+)", head, re.IGNORECASE) + if m: + fmt = (m.group("fmt") or "png").lower() + + return self._process_embedded_uri(uri, fmt, b64_raw) + + def replace_text(self, text: str) -> str: + if not text or "data:image/" not in text: + return text + self._saw_embedded_image = True + + def repl(m: re.Match[str]) -> str: + alt = m.group("alt") or "image" + decision = self._process_match(m) + if decision == _DROP_IMAGE: + return "" + if decision == _KEEP_IMAGE: + return m.group(0) + return f"![{alt}]({decision})" + + out = _EMBEDDED_IMG_RE.sub(repl, text) + if "data:image/" in out: + + def loose_repl(m: re.Match[str]) -> str: + alt = m.group("alt") or "image" + decision = self._process_loose_uri(m.group("uri") or "") + if decision == _DROP_IMAGE: + return "" + if decision == _KEEP_IMAGE: + return m.group(0) + return f"![{alt}]({decision})" + + out = _EMBEDDED_IMG_LOOSE_RE.sub(loose_repl, out) + if not self.allow_embed_fallback and "data:image/" in out: + dropped_before = self.invalid_removed_count + out = _EMBEDDED_IMG_LOOSE_RE.sub("", out) + out = _EMBEDDED_IMG_ANY_RE.sub("", out) + removed = self.invalid_removed_count - dropped_before + if "data:image/" in out: + self.context.warnings.append( + "image-hosting left non-markdown data:image content; kept as-is" + ) + else: + self.context.warnings.append( + "image-hosting removed unsupported embedded images" + + (f": {removed}" if removed > 0 else "") + ) + out = re.sub(r"(?:\s*<br>\s*){2,}", " <br> ", out) + return out + + def finalize(self) -> None: + if self._saw_embedded_image and _bool_env("MINIO_CLEANUP_STALE", True): + self._ensure_storage() + + if self.storage is not None and _bool_env("MINIO_CLEANUP_STALE", True): + prefix = f"{self.object_prefix}/" + try: + for object_name in self.storage.list_prefix(prefix): + if object_name in self.referenced_objects: + continue + self.storage.remove_object(object_name) + self.stale_removed_count += 1 + except Exception as exc: + self.context.warnings.append( + f"image-hosting cleanup failed ({self.source_file}): {exc}" + ) + + if self.invalid_removed_count > 0: + self.context.warnings.append( + f"image-hosting removed invalid images: {self.invalid_removed_count}" + ) + + if self.kept_embedded_count > 0 and self.storage is None: + self.context.warnings.append( + "image-hosting unavailable: keep legacy data:image embeds" + ) + + if ( + self.uploaded_count > 0 + or self.reused_count > 0 + or self.stale_removed_count > 0 + ): + self.context.warnings.append( + "image-hosting synced " + f"(uploaded={self.uploaded_count}, reused={self.reused_count}, " + f"stale_removed={self.stale_removed_count}, prefix={self.object_prefix})" + ) + + +def run(input_data: dict, context: Context) -> dict: + out_dir = Path(input_data["out_dir"]) + out_dir.mkdir(parents=True, exist_ok=True) + source_file = input_data.get("source_file", "") + source_rel_path = input_data.get("source_rel_path", source_file) + source_category = input_data.get("source_category", "") + source_stem = Path(source_file).stem if source_file else out_dir.name + flat_clean_path = Path( + input_data.get("flat_md_path", out_dir.parent / f"{source_stem}.md") + ) + view_clean_path = out_dir / "03_clean_view.md" + view_images_dir = out_dir / "images_view" + + for p in [ + out_dir / "01_raw_layout.json", + out_dir / "02_flow_procedure.md", + out_dir / "03_clean.md", + out_dir / "04_chunks.jsonl", + out_dir / "report.md", + view_clean_path, + flat_clean_path, + ]: + if p.exists(): + p.unlink() + chunks_dir = out_dir / "chunks" + if chunks_dir.exists(): + shutil.rmtree(chunks_dir) + if view_images_dir.exists(): + shutil.rmtree(view_images_dir) + + clean_md: str = input_data.get("clean_md", "") + chunks: list[Chunk] = input_data.get("chunks", []) + blocks: list[Block] = input_data.get("blocks", []) + flow_markdowns: list[str] = input_data.get("flow_markdowns", []) + + rewriter = _RemoteImageRewriter( + context=context, + source_file=source_file, + source_rel_path=source_rel_path, + source_category=source_category, + ) + + clean_md = rewriter.replace_text(clean_md) + exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks] + rewriter.finalize() + + _write(out_dir / "03_clean.md", clean_md) + _write(flat_clean_path, clean_md) + + lines = [json.dumps(asdict(c), ensure_ascii=False) for c in exported_chunks] + _write(out_dir / "04_chunks.jsonl", "\n".join(lines) + ("\n" if lines else "")) + + chunks_dir.mkdir(parents=True, exist_ok=True) + for c in exported_chunks: + _write(chunks_dir / f"chunk_{c.index:04d}.md", c.text + "\n") + + if flow_markdowns: + _write(out_dir / "02_flow_procedure.md", "\n\n".join(flow_markdowns) + "\n") + + _write( + out_dir / "01_raw_layout.json", + json.dumps([asdict(b) for b in blocks], ensure_ascii=False, indent=2) + "\n", + ) + + report_lines = [ + f"# Report: {input_data.get('source_file', '')}", + "", + f"- pages: {context.pages}", + f"- images: {context.images}", + f"- ocr_characters: {context.ocr_characters}", + f"- flows_detected: {context.flows_detected}", + f"- confidence: {context.confidence:.2f}", + "", + "## warnings", + ] + if context.warnings: + report_lines.extend([f"- {w}" for w in context.warnings]) + else: + report_lines.append("- none") + + report_lines.extend( + [ + "", + "## recommended_dify_settings", + "- Index: High Quality", + "- Retrieval: Hybrid", + "- Chunking: General", + "", + ] + ) + _write(out_dir / "report.md", "\n".join(report_lines)) + + return {"out_dir": str(out_dir)} diff --git a/backend/edkb_system/skills/flow_reconstruct.py b/backend/edkb_system/skills/flow_reconstruct.py new file mode 100644 index 00000000..745dbf0b --- /dev/null +++ b/backend/edkb_system/skills/flow_reconstruct.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +from dataclasses import dataclass + +import networkx as nx + +from edkb_system.contracts import Block, Context + + +@dataclass +class Node: + id: str + text: str + page: int + kind: str + bbox: tuple[float, float, float, float] + + +def _is_decision(text: str) -> bool: + kws = ["判定", "判断", "是否", "if", "check"] + s = text.lower() + return any(k in s for k in kws) + + +def _dist(a: Node, b: Node) -> float: + ax = (a.bbox[0] + a.bbox[2]) / 2.0 + ay = (a.bbox[1] + a.bbox[3]) / 2.0 + bx = (b.bbox[0] + b.bbox[2]) / 2.0 + by = (b.bbox[1] + b.bbox[3]) / 2.0 + return ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5 + + +def run(input_data: list[Block], context: Context) -> dict: + blocks = [ + b + for b in input_data + if b.type in {"textbox", "shape", "diamond", "arrow_label", "paragraph"} + and b.text.strip() + ] + by_page: dict[int, list[Block]] = {} + for b in blocks: + by_page.setdefault(b.page, []).append(b) + + page_markdowns: list[str] = [] + debug: list[dict] = [] + + for page in sorted(by_page): + cands = by_page[page] + nodes: list[Node] = [] + labels: list[Node] = [] + for b in cands: + text = b.text.strip() + if b.type == "arrow_label" or text.upper() in { + "NG", + "OK", + "Y", + "N", + "YES", + "NO", + }: + labels.append(Node(b.id, text, b.page, "label", b.bbox)) + continue + kind = "decision" if (_is_decision(text) or b.type == "diamond") else "step" + nodes.append(Node(b.id, text, b.page, kind, b.bbox)) + nodes = sorted( + nodes, + key=lambda n: ( + (n.bbox[1] + n.bbox[3]) / 2.0, + (n.bbox[0] + n.bbox[2]) / 2.0, + ), + ) + if not nodes: + continue + + g = nx.DiGraph() + for n in nodes: + g.add_node(n.id, node=n) + + for i, src in enumerate(nodes[:-1]): + dst = nodes[i + 1] + g.add_edge(src.id, dst.id, label=None) + + for dec in [n for n in nodes if n.kind == "decision"]: + right_steps = [ + n + for n in nodes + if ((n.bbox[0] + n.bbox[2]) / 2.0) > ((dec.bbox[0] + dec.bbox[2]) / 2.0) + ] + if right_steps: + target = min(right_steps, key=lambda x: _dist(dec, x)) + label_node = None + right_labels = [ + l + for l in labels + if ((l.bbox[0] + l.bbox[2]) / 2.0) + > ((dec.bbox[0] + dec.bbox[2]) / 2.0) + ] + if right_labels: + label_node = min(right_labels, key=lambda x: _dist(dec, x)) + g.add_edge( + dec.id, target.id, label=(label_node.text if label_node else "分支") + ) + + ordered = nodes + idx_map = {n.id: i + 1 for i, n in enumerate(ordered)} + cycles = list(nx.simple_cycles(g)) + cyc_nodes = {nid for cyc in cycles for nid in cyc} + + lines = [f"## Page {page} Procedure"] + for n in ordered: + title = n.text + if n.kind == "decision" and not title.startswith("判定"): + title = f"判定:{title}" + lines.append(f"{idx_map[n.id]}. {title}") + if n.kind == "decision": + for _, dst, data in g.out_edges(n.id, data=True): + if data.get("label") is None: + continue + label = data.get("label") or "分支" + if dst in cyc_nodes: + lines.append(f"- {label} -> 返回到步骤{idx_map.get(dst, '?')}") + else: + dst_text = g.nodes[dst]["node"].text + lines.append(f"- {label} -> {dst_text}") + + page_markdowns.append("\n".join(lines)) + debug.append( + { + "page": page, + "nodes": [ + {"id": n.id, "text": n.text, "kind": n.kind, "bbox": list(n.bbox)} + for n in nodes + ], + "edges": [ + {"src": s, "dst": d, "label": data.get("label")} + for s, d, data in g.edges(data=True) + ], + } + ) + + context.flows_detected = len(page_markdowns) + return {"flow_markdowns": page_markdowns, "debug": debug} diff --git a/backend/edkb_system/skills/intake_router.py b/backend/edkb_system/skills/intake_router.py new file mode 100644 index 00000000..c32b274f --- /dev/null +++ b/backend/edkb_system/skills/intake_router.py @@ -0,0 +1,419 @@ +from __future__ import annotations + +import re +import zipfile +from pathlib import Path + +from edkb_system.config import RouterConfig +from edkb_system.contracts import Context, DocumentProfile + + +_DOC_KIND_STRATEGY = { + "flow_procedure": { + "enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"}, + "disable": set(), + }, + "policy_text": { + "enable": set(), + "disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"}, + }, + "tabular_record": { + "enable": set(), + "disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"}, + }, + "mixed": { + "enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"}, + "disable": set(), + }, +} + + +def _keyword_score(name: str, keywords: dict[str, float]) -> float: + score = 0.0 + for k, w in keywords.items(): + if k in name: + score += w + return score + + +def _score_text_keywords(text: str, keywords: dict[str, float]) -> float: + score = 0.0 + for k, w in keywords.items(): + if k in text: + score += w + return score + + +def _has_flow_evidence(stem: str, content: dict) -> bool: + name = stem.lower() + strong_name_hit = any( + k in name for k in ["流程", "流程图", "判定", "作业标准", "检验作业"] + ) + flow_hits = int(content.get("flow_hits", 0) or 0) + shape_hits = int(content.get("shape_hits", 0) or 0) + if flow_hits >= 6: + return True + if flow_hits >= 3 and shape_hits >= 1: + return True + return strong_name_hit + + +def _probe_docx_xml(path: Path) -> dict: + signals = { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + try: + with zipfile.ZipFile(path) as zf: + xml_parts = [ + n for n in zf.namelist() if n.startswith("word/") and n.endswith(".xml") + ] + xml_blob = "" + for n in xml_parts[:12]: + try: + xml_blob += zf.read(n).decode("utf-8", errors="ignore") + except Exception: + continue + except Exception: + return signals + + if not xml_blob: + return signals + + text = xml_blob.lower() + signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text)) + signals["table_hits"] = text.count("<w:tbl") + signals["image_hits"] = text.count("<a:blip") + text.count("<v:imagedata") + signals["shape_hits"] = ( + text.count("<w:drawing") + text.count("<v:shape") + text.count("<wps:wsp") + ) + flow_kw = { + "流程": 0.3, + "流程图": 0.4, + "判定": 0.25, + "检验": 0.2, + "作业": 0.15, + } + signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10) + return signals + + +def _probe_pdf(path: Path) -> dict: + signals = { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + try: + blob = path.read_bytes()[: 2 * 1024 * 1024] + except Exception: + return signals + + text = blob.decode("latin-1", errors="ignore") + signals["image_hits"] = text.count("/Subtype /Image") + text.count("/Image") + text_ops = text.count(" BT") + text.count(" ET") + signals["has_text"] = text_ops >= 10 + return signals + + +def _probe_pptx(path: Path) -> dict: + signals = { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + try: + with zipfile.ZipFile(path) as zf: + xml_parts = [ + n + for n in zf.namelist() + if n.startswith("ppt/slides/") and n.endswith(".xml") + ] + xml_blob = "" + for n in xml_parts[:20]: + try: + xml_blob += zf.read(n).decode("utf-8", errors="ignore") + except Exception: + continue + except Exception: + return signals + + if not xml_blob: + return signals + text = xml_blob.lower() + signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text)) + signals["table_hits"] = text.count("<a:tbl") + signals["image_hits"] = text.count("<a:blip") + signals["shape_hits"] = text.count("<p:sp") + text.count("<p:cxnsp") + flow_kw = {"流程": 0.4, "流程图": 0.5, "送样": 0.3, "承认": 0.3, "判定": 0.25} + signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10) + return signals + + +def _probe_content(file_path: Path, ext: str) -> dict: + if ext == ".docx": + return _probe_docx_xml(file_path) + if ext == ".doc": + cache_docx = file_path.parents[1] / "cache" / f"{file_path.stem}.docx" + if cache_docx.exists(): + return _probe_docx_xml(cache_docx) + return { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + if ext == ".pdf": + return _probe_pdf(file_path) + if ext == ".pptx": + return _probe_pptx(file_path) + if ext == ".ppt": + cache_pptx = file_path.parents[1] / "cache" / f"{file_path.stem}.pptx" + if cache_pptx.exists(): + return _probe_pptx(cache_pptx) + return { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + if ext in {".xls", ".xlsx", ".csv"}: + return { + "has_text": True, + "table_hits": 8, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + return { + "has_text": False, + "table_hits": 0, + "flow_hits": 0, + "image_hits": 0, + "shape_hits": 0, + } + + +def _build_pipeline( + ext: str, + doc_kind: str, + scan_likelihood: float, + cfg: RouterConfig, +) -> list[str]: + strategy = _DOC_KIND_STRATEGY.get(doc_kind, _DOC_KIND_STRATEGY["mixed"]) + enable = set(strategy["enable"]) + disable = set(strategy["disable"]) + + pipeline: list[str] = [] + if ext in {".doc", ".docx"}: + pipeline.append("edkb-loader-docx") + if "edkb-doc-to-pdf" in enable and "edkb-doc-to-pdf" not in disable: + pipeline.append("edkb-doc-to-pdf") + elif ext == ".pdf": + pipeline.append("edkb-loader-pdf") + elif ext in {".ppt", ".pptx"}: + pipeline.append("edkb-loader-pptx") + elif ext in {".xls", ".xlsx"}: + pipeline.extend(["edkb-loader-excel", "edkb-table-linearize"]) + elif ext == ".csv": + pipeline.extend(["edkb-loader-csv", "edkb-table-linearize"]) + + if ext in {".doc", ".docx", ".pdf", ".ppt", ".pptx"}: + if scan_likelihood >= cfg.scan_likelihood_threshold: + pipeline.append("edkb-ocr") + if "edkb-flow-reconstruct" in enable and "edkb-flow-reconstruct" not in disable: + pipeline.append("edkb-flow-reconstruct") + + pipeline.extend( + [ + "edkb-clean", + "edkb-chunk", + "edkb-quality-gate", + "edkb-export", + "edkb-postcheck", + ] + ) + return pipeline + + +def _decide_doc_kind( + stem: str, ext: str, content: dict +) -> tuple[str, float, float, float, list[str]]: + s = stem.lower() + reasons: list[str] = [] + + flow_pos = { + "流程图": 0.5, + "作业流程": 0.45, + "流程": 0.25, + "检验": 0.25, + "作业标准": 0.35, + "sop": 0.35, + "判定": 0.2, + "oqc": 0.2, + "iqc": 0.2, + } + flow_neg = { + "管理办法": 0.35, + "制度": 0.3, + "守则": 0.3, + "规定": 0.25, + "手册": 0.2, + } + table_pos = { + "台账": 0.45, + "清单": 0.35, + "记录": 0.25, + "表单": 0.4, + "excel": 0.4, + } + + flow_raw = 0.35 + _keyword_score(s, flow_pos) - _keyword_score(s, flow_neg) + table_raw = 0.15 + _keyword_score(s, table_pos) + + if ext in {".xls", ".xlsx", ".csv"}: + table_raw += 0.55 + if ext == ".pdf": + flow_raw += 0.05 + if ext in {".ppt", ".pptx"}: + flow_raw += 0.1 + + flow_raw += min(0.45, 0.04 * content.get("flow_hits", 0)) + flow_raw += min(0.25, 0.02 * content.get("shape_hits", 0)) + table_raw += min(0.55, 0.08 * content.get("table_hits", 0)) + if content.get("image_hits", 0) >= 2 and ext in { + ".doc", + ".docx", + ".pdf", + ".ppt", + ".pptx", + }: + flow_raw += 0.05 + + flow_likelihood = max(0.05, min(0.95, flow_raw)) + table_likelihood = max(0.05, min(0.95, table_raw)) + text_density = 0.55 + flow_evidence = _has_flow_evidence(stem, content) + + if not flow_evidence: + flow_likelihood = min(flow_likelihood, 0.59) + if content.get("table_hits", 0) >= 1: + table_likelihood = max(table_likelihood, 0.65) + + if ( + flow_evidence + and flow_likelihood >= 0.65 + and (table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1) + ): + doc_kind = "mixed" + reasons.append("content indicates mixed flow+table document") + elif table_likelihood >= 0.75 and (flow_likelihood < 0.6 or not flow_evidence): + doc_kind = "tabular_record" + reasons.append("content indicates table-like document") + elif not flow_evidence and ( + table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1 + ): + doc_kind = "tabular_record" + reasons.append("content indicates text+table document without flow") + elif flow_evidence and flow_likelihood >= 0.65: + doc_kind = "flow_procedure" + reasons.append("content indicates flow/procedure document") + elif flow_likelihood <= 0.35 or not flow_evidence: + doc_kind = "policy_text" + reasons.append("content indicates policy/management text") + else: + doc_kind = "mixed" + reasons.append("content indicates mixed document") + + return doc_kind, flow_likelihood, table_likelihood, text_density, reasons + + +def _derive_content_modes( + ext: str, + stem: str, + content: dict, + flow_likelihood: float, + table_likelihood: float, +) -> list[str]: + modes: set[str] = set() + if content.get("has_text") or ext in { + ".doc", + ".docx", + ".pdf", + ".ppt", + ".pptx", + ".xls", + ".xlsx", + ".csv", + }: + modes.add("text") + if content.get("image_hits", 0) > 0: + modes.add("image") + if table_likelihood >= 0.65 or content.get("table_hits", 0) >= 1: + modes.add("table") + if _has_flow_evidence(stem, content) and flow_likelihood >= 0.6: + modes.add("flow") + return sorted(modes) + + +def run(input_data: dict, context: Context, cfg: RouterConfig) -> DocumentProfile: + file_path = Path(input_data["file_path"]) + ext = file_path.suffix.lower() + file_type = ext.lstrip(".") + + size = file_path.stat().st_size if file_path.exists() else 0 + has_tables = ext in {".xls", ".xlsx", ".csv"} + content_signals = _probe_content(file_path, ext) + doc_kind, flow_likelihood, table_likelihood, text_density, reasons = ( + _decide_doc_kind(file_path.stem, ext, content_signals) + ) + content_modes = _derive_content_modes( + ext, file_path.stem, content_signals, flow_likelihood, table_likelihood + ) + + scan_likelihood = 0.2 + if ext == ".pdf" and size > 3 * 1024 * 1024: + scan_likelihood = 0.65 + + has_images = ext in {".pdf", ".doc", ".docx", ".ppt", ".pptx"} + + pipeline = _build_pipeline(ext, doc_kind, scan_likelihood, cfg) + + context.file_type = file_type + context.extras["intake"] = { + "doc_kind": doc_kind, + "content_modes": content_modes, + "route_reasons": reasons, + "strategy": { + "enable": sorted(_DOC_KIND_STRATEGY.get(doc_kind, {}).get("enable", set())), + "disable": sorted( + _DOC_KIND_STRATEGY.get(doc_kind, {}).get("disable", set()) + ), + }, + "content_signals": content_signals, + "flow_likelihood": round(flow_likelihood, 3), + "table_likelihood": round(table_likelihood, 3), + "scan_likelihood": round(scan_likelihood, 3), + "pipeline": pipeline, + } + + return DocumentProfile( + file_type=file_type, + text_density=text_density, + has_images=has_images, + has_tables=has_tables, + flow_likelihood=flow_likelihood, + scan_likelihood=scan_likelihood, + table_likelihood=table_likelihood, + language_hint="zh", + recommended_pipeline=pipeline, + ) diff --git a/backend/edkb_system/skills/loader_csv.py b/backend/edkb_system/skills/loader_csv.py new file mode 100644 index 00000000..300dec4a --- /dev/null +++ b/backend/edkb_system/skills/loader_csv.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import csv +from pathlib import Path + +from edkb_system.contracts import Context + + +def run(input_data: dict, context: Context) -> dict: + file_path = Path(input_data["file_path"]) + raw = None + for enc in ("utf-8-sig", "utf-8", "gb18030"): + try: + raw = file_path.read_text(encoding=enc) + break + except UnicodeDecodeError: + continue + if raw is None: + raw = file_path.read_text(errors="ignore") + + sample = raw[:4096] + try: + dialect = csv.Sniffer().sniff(sample, delimiters=",;\t") + delim = dialect.delimiter + except Exception: + delim = "," + + rows = [ + r + for r in csv.reader(raw.splitlines(), delimiter=delim) + if any(c.strip() for c in r) + ] + table = { + "sheet": "csv", + "headers": rows[0] if rows else [], + "rows": rows[1:] if len(rows) > 1 else [], + } + context.extras["tables_count"] = 1 + return table diff --git a/backend/edkb_system/skills/loader_docx.py b/backend/edkb_system/skills/loader_docx.py new file mode 100644 index 00000000..d9f59133 --- /dev/null +++ b/backend/edkb_system/skills/loader_docx.py @@ -0,0 +1,1962 @@ +from __future__ import annotations + +import base64 +import hashlib +import io +import struct +import mimetypes +import os +import re +import shutil +import subprocess +import zipfile +import xml.etree.ElementTree as ET +from pathlib import Path + +from edkb_system.contracts import Block, Context +from edkb_system.skills.word_bridge import convert_with_word + + +def _to_data_uri(blob: bytes, content_type: str | None = None) -> str: + ct = content_type or "image/png" + b64 = base64.b64encode(blob).decode("ascii") + return f"data:{ct};base64,{b64}" + + +def _to_preferred_image_data_uri(blob: bytes, content_type: str | None = None) -> str: + try: + from PIL import Image + + with Image.open(io.BytesIO(blob)) as im: + rgb = Image.new("RGB", im.size, (255, 255, 255)) + rgba = im.convert("RGBA") + rgb.paste(rgba, mask=rgba.split()[3]) + out = io.BytesIO() + rgb.save(out, format="JPEG", quality=90) + return _to_data_uri(out.getvalue(), "image/jpeg") + except Exception: + return _to_data_uri(blob, content_type) + + +def _image_dimensions(blob: bytes, ext: str) -> tuple[int, int]: + e = (ext or "").lower().lstrip(".") + if e == "png" and len(blob) >= 24 and blob.startswith(b"\x89PNG"): + return int.from_bytes(blob[16:20], "big"), int.from_bytes(blob[20:24], "big") + if e in {"jpg", "jpeg"} and blob.startswith(b"\xff\xd8"): + i = 2 + n = len(blob) + while i + 9 < n: + if blob[i] != 0xFF: + i += 1 + continue + marker = blob[i + 1] + if marker in {0xC0, 0xC2}: + h = struct.unpack(">H", blob[i + 5 : i + 7])[0] + w = struct.unpack(">H", blob[i + 7 : i + 9])[0] + return w, h + if i + 4 > n: + break + seg_len = struct.unpack(">H", blob[i + 2 : i + 4])[0] + if seg_len <= 2: + break + i += 2 + seg_len + return 0, 0 + + +def _is_sparse_line_artifact(blob: bytes, ext: str) -> bool: + e = (ext or "").lower().lstrip(".") + if e not in {"png", "jpg", "jpeg"}: + return False + + try: + from PIL import Image + import numpy as np + + with Image.open(io.BytesIO(blob)) as im: + g = im.convert("L") + w, h = g.size + if w <= 0 or h <= 0 or (w * h) < 60000: + return False + + hist = g.histogram() + total = max(w * h, 1) + dominant_ratio = max(hist) / total + uniq = sum(1 for c in hist if c) + if dominant_ratio < 0.99 or uniq > 3: + return False + + if max(w, h) > 1200: + scale = max(w, h) / 1200.0 + nw = max(1, int(w / scale)) + nh = max(1, int(h / scale)) + g = g.resize((nw, nh)) + + a = np.asarray(g, dtype=np.int16) + gx = np.abs(np.diff(a, axis=1)) + gy = np.abs(np.diff(a, axis=0)) + edge_ratio = (np.count_nonzero(gx > 12) + np.count_nonzero(gy > 12)) / max( + a.shape[0] * a.shape[1], 1 + ) + return edge_ratio < 0.02 + except Exception: + return False + + +def _split_tall_image(blob: bytes, ext: str) -> list[bytes]: + e = (ext or "").lower().lstrip(".") + if e not in {"png", "jpg", "jpeg"}: + return [blob] + try: + from PIL import Image + + with Image.open(io.BytesIO(blob)) as im: + w, h = im.size + if w <= 0 or h <= 0 or (h / max(w, 1)) < 1.8: + return [blob] + + g = im.convert("L") + + def _pix(x: int, y: int) -> int: + v = g.getpixel((x, y)) + if isinstance(v, tuple): + return int(v[0]) + return int(v if v is not None else 255) + + corners = [ + _pix(0, 0), + _pix(w - 1, 0), + _pix(0, h - 1), + _pix(w - 1, h - 1), + ] + bg = sorted(corners)[len(corners) // 2] + + row_content: list[float] = [] + for y in range(h): + hist = g.crop((0, y, w, y + 1)).histogram() + near_bg = 0 + lo_bg = max(0, bg - 8) + hi_bg = min(255, bg + 8) + for i in range(lo_bg, hi_bg + 1): + near_bg += hist[i] + row_content.append((w - near_bg) / max(w, 1)) + + lo = int(h * 0.30) + hi = int(h * 0.80) + if hi <= lo: + return [blob] + + best_len = 0 + best_mid = None + cur_start = None + for y in range(lo, hi): + if row_content[y] < 0.03: + if cur_start is None: + cur_start = y + else: + if cur_start is not None: + ln = y - cur_start + if ln > best_len: + best_len = ln + best_mid = (cur_start + y) // 2 + cur_start = None + if cur_start is not None: + ln = hi - cur_start + if ln > best_len: + best_len = ln + best_mid = (cur_start + hi) // 2 + + if best_mid is None or best_len < 10: + return [blob] + cut = best_mid + + def _row_non_bg(y: int) -> int: + hist = g.crop((0, y, w, y + 1)).histogram() + near_bg = 0 + lo_bg = max(0, bg - 8) + hi_bg = min(255, bg + 8) + for i in range(lo_bg, hi_bg + 1): + near_bg += hist[i] + return w - near_bg + + top_end = cut + for y in range(max(0, cut - 60), min(h, cut + 1)): + if _row_non_bg(y) > 2: + top_end = y + top_end = min(h, top_end + 6) + + bot_start = cut + for y in range(cut, min(h, cut + 80)): + if _row_non_bg(y) > 2: + bot_start = y + break + bot_start = max(0, bot_start - 6) + + if bot_start <= top_end: + top = im.crop((0, 0, w, max(1, cut))) + bot = im.crop((0, min(h - 1, cut), w, h)) + else: + top = im.crop((0, 0, w, max(1, top_end))) + bot = im.crop((0, min(h - 1, bot_start), w, h)) + + out: list[bytes] = [] + for part in [top, bot]: + b = io.BytesIO() + part.save(b, format="PNG") + out.append(b.getvalue()) + return out if len(out) == 2 else [blob] + except Exception: + return [blob] + + +def _extract_image_uris_from_paragraph(para, doc) -> list[str]: + uris: list[str] = [] + try: + rids = para._element.xpath(".//a:blip/@r:embed") + except Exception: + return uris + for rid in rids: + try: + part = doc.part.related_parts[rid] + blob = part.blob + content_type = getattr(part, "content_type", None) + uris.append(_to_preferred_image_data_uri(blob, content_type)) + except Exception: + continue + return uris + + +def _extract_all_image_uris_from_doc(doc) -> list[str]: + uris: list[str] = [] + seen: set[str] = set() + rel_items = list(doc.part.rels.items()) + rel_items.sort( + key=lambda kv: int((kv[0] or "rId0").replace("rId", "") or 0) + if (kv[0] or "").startswith("rId") + else 0 + ) + for _, rel in rel_items: + reltype = getattr(rel, "reltype", "") or "" + if "image" not in reltype: + continue + try: + part = rel.target_part + blob = part.blob + content_type = getattr(part, "content_type", None) + uri = _to_preferred_image_data_uri(blob, content_type) + key = hashlib.sha1(blob).hexdigest() + if key in seen: + continue + seen.add(key) + uris.append(uri) + except Exception: + continue + return uris + + +def _extract_image_uris_from_table(table, doc) -> list[str]: + uris: list[str] = [] + seen: set[str] = set() + try: + for row in table.rows: + for cell in row.cells: + for para in cell.paragraphs: + for uri in _extract_image_uris_from_paragraph(para, doc): + if uri in seen: + continue + seen.add(uri) + uris.append(uri) + except Exception: + return uris + return uris + + +def _load_numbering_schema( + docx_path: Path, +) -> tuple[dict[str, str], dict[tuple[str, int], dict]]: + ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"} + num_to_abs: dict[str, str] = {} + levels: dict[tuple[str, int], dict] = {} + try: + with zipfile.ZipFile(docx_path) as zf: + xml = zf.read("word/numbering.xml") + root = ET.fromstring(xml) + except Exception: + return num_to_abs, levels + + for num in root.findall("w:num", ns): + nid = num.attrib.get("{%s}numId" % ns["w"]) + aid_elem = num.find("w:abstractNumId", ns) + aid = aid_elem.attrib.get("{%s}val" % ns["w"]) if aid_elem is not None else None + if nid and aid: + num_to_abs[nid] = aid + + for absn in root.findall("w:abstractNum", ns): + aid = absn.attrib.get("{%s}abstractNumId" % ns["w"]) + if not aid: + continue + for lvl in absn.findall("w:lvl", ns): + ilvl_s = lvl.attrib.get("{%s}ilvl" % ns["w"], "0") + try: + ilvl = int(ilvl_s) + except Exception: + ilvl = 0 + fmt_elem = lvl.find("w:numFmt", ns) + txt_elem = lvl.find("w:lvlText", ns) + start_elem = lvl.find("w:start", ns) + num_fmt = ( + fmt_elem.attrib.get("{%s}val" % ns["w"], "decimal") + if fmt_elem is not None + else "decimal" + ) + lvl_text = ( + txt_elem.attrib.get("{%s}val" % ns["w"], f"%{ilvl + 1}") + if txt_elem is not None + else f"%{ilvl + 1}" + ) + start = ( + int(start_elem.attrib.get("{%s}val" % ns["w"], "1")) + if start_elem is not None + else 1 + ) + levels[(aid, ilvl)] = { + "num_fmt": num_fmt, + "lvl_text": lvl_text, + "start": start, + } + + return num_to_abs, levels + + +def _to_roman(n: int) -> str: + vals = [ + (1000, "M"), + (900, "CM"), + (500, "D"), + (400, "CD"), + (100, "C"), + (90, "XC"), + (50, "L"), + (40, "XL"), + (10, "X"), + (9, "IX"), + (5, "V"), + (4, "IV"), + (1, "I"), + ] + out = [] + x = max(1, n) + for v, s in vals: + while x >= v: + out.append(s) + x -= v + return "".join(out) + + +def _to_chinese_num(n: int) -> str: + digits = "零一二三四五六七八九" + if n <= 0: + return str(n) + if n < 10: + return digits[n] + if n < 20: + return "十" + (digits[n % 10] if n % 10 else "") + if n < 100: + tens, ones = divmod(n, 10) + return digits[tens] + "十" + (digits[ones] if ones else "") + return str(n) + + +def _format_counter(n: int, fmt: str) -> str: + f = (fmt or "decimal").lower() + if f in {"decimal", "decimalzero"}: + return str(n) + if f == "lowerletter": + return chr(ord("a") + max(0, (n - 1) % 26)) + if f == "upperletter": + return chr(ord("A") + max(0, (n - 1) % 26)) + if f == "lowerroman": + return _to_roman(n).lower() + if f == "upperroman": + return _to_roman(n) + if "chinese" in f: + return _to_chinese_num(n) + if f == "bullet": + return "•" + return str(n) + + +def _next_list_marker( + num_id: str, + ilvl: int, + num_to_abs: dict[str, str], + levels: dict[tuple[str, int], dict], + states: dict[str, dict[int, int]], +) -> str: + abs_id = num_to_abs.get(str(num_id)) + if not abs_id: + return "" + lvl_cfg = levels.get( + (abs_id, ilvl), {"num_fmt": "decimal", "lvl_text": f"%{ilvl + 1}", "start": 1} + ) + state = states.setdefault(str(num_id), {}) + + for k in list(state.keys()): + if k > ilvl: + state.pop(k, None) + + for lv in range(ilvl): + if lv not in state: + state[lv] = int(levels.get((abs_id, lv), {}).get("start", 1)) + + start = int(lvl_cfg.get("start", 1)) + if ilvl not in state: + state[ilvl] = start - 1 + state[ilvl] += 1 + + if (lvl_cfg.get("num_fmt") or "").lower() == "bullet": + return "•" + + tmpl = str(lvl_cfg.get("lvl_text") or f"%{ilvl + 1}") + for n in range(1, 10): + token = f"%{n}" + if token not in tmpl: + continue + lv = n - 1 + val = state.get(lv, int(levels.get((abs_id, lv), {}).get("start", 1))) + fmt = str(levels.get((abs_id, lv), {}).get("num_fmt", "decimal")) + tmpl = tmpl.replace(token, _format_counter(val, fmt)) + + if any(ord(c) >= 0xF000 for c in tmpl): + return "•" + return tmpl.strip() + + +_WORD_EXPORT_IMAGE_NAME_RE = re.compile( + r"image\d+\.(?:png|jpg|jpeg|gif|bmp|webp)", re.IGNORECASE +) + + +def _word_export_source_stem_from_html(html_path: Path) -> str: + suffix = ".word_export.html" + name = html_path.name + if name.lower().endswith(suffix): + return name[: -len(suffix)] + return html_path.stem + + +def _word_export_candidate_dirs(source_stem: str, out_dir: Path) -> list[Path]: + candidate_dirs: list[Path] = [] + for d in [ + out_dir / f"{source_stem}.word_export_files", + out_dir / f"{source_stem}.word_export.files", + ]: + if d.exists() and d.is_dir(): + candidate_dirs.append(d) + for d in sorted(out_dir.glob(f"{source_stem}.word_export*")): + if d.exists() and d.is_dir() and d not in candidate_dirs: + candidate_dirs.append(d) + return candidate_dirs + + +def _collect_word_export_image_files( + source_stem: str, out_dir: Path +) -> dict[str, Path]: + files_by_name: dict[str, Path] = {} + for d in _word_export_candidate_dirs(source_stem, out_dir): + for p in sorted(d.glob("*")): + if not p.is_file(): + continue + if p.suffix.lower() not in { + ".png", + ".jpg", + ".jpeg", + ".gif", + ".bmp", + ".webp", + }: + continue + files_by_name.setdefault(p.name.lower(), p) + return files_by_name + + +def _image_file_to_uris(image_file: Path) -> list[str]: + if not image_file.is_file(): + return [] + ct = mimetypes.guess_type(str(image_file))[0] or "image/png" + uris: list[str] = [] + try: + blob = image_file.read_bytes() + parts = _split_tall_image(blob, image_file.suffix) + for part in parts: + w, h = _image_dimensions(part, image_file.suffix) + if w > 0 and h > 0 and (max(w, h) <= 32 or (w * h) < 2000): + continue + if _is_sparse_line_artifact(part, image_file.suffix): + continue + uris.append(_to_preferred_image_data_uri(part, ct)) + except Exception: + return uris + return uris + + +def _ordered_image_names_from_word_html(html_path: Path) -> list[str]: + ordered_names: list[str] = [] + if not html_path.exists(): + return ordered_names + + try: + from bs4 import BeautifulSoup + + html = _decode_word_html(html_path.read_bytes()) + soup = BeautifulSoup(html, "html.parser") + + def _node_is_deleted_change(node) -> bool: + if node is None: + return False + try: + if str(getattr(node, "name", "") or "").lower() == "del": + return True + classes = node.get("class") or [] + for c in classes: + if str(c).lower() in {"msodel"}: + return True + except Exception: + return False + return False + + def _img_in_deleted_context(img) -> bool: + cur = img + hops = 0 + while cur is not None and hops < 8: + hops += 1 + if _node_is_deleted_change(cur): + return True + cur = getattr(cur, "parent", None) + return False + + for img in soup.find_all("img"): + src_attr = img.get("src") + src = str(src_attr or "").strip() + if not src: + continue + name = src.replace("\\", "/").split("/")[-1].lower() + if not _WORD_EXPORT_IMAGE_NAME_RE.fullmatch(name): + continue + + style = " ".join( + [ + str(img.get("style") or ""), + str( + getattr(getattr(img, "parent", None), "get", lambda *_: "")( + "style" + ) + or "" + ), + ] + ).lower() + has_change_ctx = _img_in_deleted_context(img) + w = int(str(img.get("width") or "0").strip() or 0) + h = int(str(img.get("height") or "0").strip() or 0) + if w > 0 and h > 0 and (max(w, h) <= 32 or (w * h) < 2000): + continue + + if has_change_ctx: + continue + if "position:absolute" in style and w > 0 and h > 0 and (w * h) < 60000: + continue + + if name not in ordered_names: + ordered_names.append(name) + except Exception: + try: + html_bytes = html_path.read_bytes() + for m in re.finditer( + rb"image\d+\.(?:png|jpg|jpeg|gif|bmp|webp)", + html_bytes, + re.IGNORECASE, + ): + name = m.group(0).decode("ascii", "ignore").lower() + if name and name not in ordered_names: + ordered_names.append(name) + except Exception: + pass + + return ordered_names + + +def _ordered_word_export_files( + files_by_name: dict[str, Path], ordered_names: list[str] +) -> list[Path]: + ordered_files: list[Path] = [] + if ordered_names: + for name in ordered_names: + p = files_by_name.get(name) + if p is None: + continue + ordered_files.append(p) + else: + for name in sorted(files_by_name.keys()): + ordered_files.append(files_by_name[name]) + return ordered_files + + +def _word_html_has_standard_image_refs(html_path: Path) -> bool: + if not html_path.exists(): + return False + try: + raw = html_path.read_bytes() + except Exception: + return False + return ( + re.search( + rb"image\d+\.(?:png|jpg|jpeg|gif|bmp|webp)", + raw, + re.IGNORECASE, + ) + is not None + ) + + +def _select_word_export_files( + files_by_name: dict[str, Path], + ordered_names: list[str], + html_path: Path, +) -> list[Path]: + has_refs = _word_html_has_standard_image_refs(html_path) + if has_refs and not ordered_names: + return [] + return _ordered_word_export_files(files_by_name, ordered_names) + + +def _extract_images_with_word(source_path: Path, out_dir: Path) -> list[str]: + html_path = out_dir / f"{source_path.stem}.word_export.html" + assets_dir = out_dir / f"{source_path.stem}.word_export_files" + assets_dir_dot = out_dir / f"{source_path.stem}.word_export.files" + out_dir.mkdir(parents=True, exist_ok=True) + + cached_files_by_name = _collect_word_export_image_files(source_path.stem, out_dir) + if html_path.exists(): + ordered_names = _ordered_image_names_from_word_html(html_path) + has_refs = _word_html_has_standard_image_refs(html_path) + + # Cached negative result: html has no refs (or refs all filtered), and no asset files. + # Avoid reopening Word on every run for no-image docs. + if not cached_files_by_name: + if (not has_refs) or (has_refs and not ordered_names): + return [] + + if cached_files_by_name: + ordered_files = _select_word_export_files( + cached_files_by_name, + ordered_names, + html_path, + ) + cached_uris: list[str] = [] + for p in ordered_files: + cached_uris.extend(_image_file_to_uris(p)) + if cached_uris: + return cached_uris + if (not has_refs) or (has_refs and not ordered_names): + return [] + + if html_path.exists(): + html_path.unlink() + if assets_dir.exists(): + shutil.rmtree(assets_dir) + if assets_dir_dot.exists(): + shutil.rmtree(assets_dir_dot) + + convert_with_word(source_path.resolve(), html_path.resolve(), 10) + + files_by_name = _collect_word_export_image_files(source_path.stem, out_dir) + if not files_by_name: + return [] + + ordered_names = _ordered_image_names_from_word_html(html_path) + + ordered_files = _select_word_export_files(files_by_name, ordered_names, html_path) + + uris: list[str] = [] + for p in ordered_files: + uris.extend(_image_file_to_uris(p)) + return uris + + +def _decode_word_html(raw: bytes) -> str: + for enc in ("utf-8", "gb18030", "cp936", "latin1"): + try: + return raw.decode(enc) + except Exception: + continue + return raw.decode("latin1", "ignore") + + +def _norm_text(s: str) -> str: + return re.sub(r"\s+", " ", (s or "").replace("\xa0", " ")).strip() + + +def _xml_local_name(tag: str) -> str: + if not tag: + return "" + if "}" in tag: + return tag.rsplit("}", 1)[-1] + if ":" in tag: + return tag.rsplit(":", 1)[-1] + return tag + + +def _extract_text_from_ooxml_node(node) -> str: + parts: list[str] = [] + + def walk(el) -> None: + name = _xml_local_name(getattr(el, "tag", "")) + + if name in { + "del", + "moveFrom", + "moveFromRangeStart", + "moveFromRangeEnd", + "commentRangeStart", + "commentRangeEnd", + "drawing", + "pict", + "object", + "txbxContent", + "instrText", + }: + return + + if name == "t": + txt = getattr(el, "text", None) + if txt: + parts.append(str(txt)) + elif name == "tab": + parts.append("\t") + elif name in {"br", "cr"}: + parts.append("\n") + + for ch in list(el): + walk(ch) + + try: + walk(node) + except Exception: + return "" + return "".join(parts) + + +def _paragraph_text_without_revisions(para) -> str: + try: + txt = _extract_text_from_ooxml_node(para._p) + except Exception: + txt = para.text or "" + return " ".join((txt or "").split()) + + +def _cell_paragraph_texts_without_revisions(cell) -> list[str]: + chunks: list[str] = [] + try: + for para in cell.paragraphs: + t = _paragraph_text_without_revisions(para) + if t: + chunks.append(t) + except Exception: + fallback = " ".join((cell.text or "").split()) + return [fallback] if fallback else [] + return chunks + + +def _cell_text_without_revisions(cell) -> str: + return "\n".join(_cell_paragraph_texts_without_revisions(cell)).strip() + + +def _drop_deleted_revision_nodes(root) -> None: + try: + for n in root.find_all("del"): + n.decompose() + except Exception: + pass + + try: + for n in root.find_all( + class_=lambda c: c + and any( + str(x).lower() == "msodel" for x in (c if isinstance(c, list) else [c]) + ) + ): + n.decompose() + except Exception: + pass + + +def _extract_word_html_items(html_path: Path) -> list[tuple[str, str]]: + if not html_path.exists(): + return [] + try: + from bs4 import BeautifulSoup + except Exception: + return [] + + try: + html = _decode_word_html(html_path.read_bytes()) + except Exception: + return [] + + soup = BeautifulSoup(html, "html.parser") + body = soup.body or soup + _drop_deleted_revision_nodes(body) + items: list[tuple[str, str]] = [] + + for el in body.find_all(["p", "table"]): + if el.name == "p": + txt = _norm_text(el.get_text(" ", strip=True)) + if txt: + items.append(("paragraph", txt)) + continue + + rows: list[list[str]] = [] + for tr in el.find_all("tr"): + row = [ + _norm_text(td.get_text(" ", strip=True)) + for td in tr.find_all(["th", "td"]) + ] + while row and not row[-1]: + row.pop() + if any(row): + rows.append(row) + if not rows: + continue + width = max(len(r) for r in rows) + norm = [r + [""] * (width - len(r)) for r in rows] + lines = [ + "| " + " | ".join(norm[0]) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + for r in norm[1:]: + lines.append("| " + " | ".join(r) + " |") + items.append(("table", "\n".join(lines))) + + return items + + +def _extract_workflow_table_from_word_html(html_path: Path) -> tuple[str, list[str]]: + if not html_path.exists(): + return "", [] + try: + from bs4 import BeautifulSoup + except Exception: + return "", [] + + try: + html = _decode_word_html(html_path.read_bytes()) + except Exception: + return "", [] + + source_stem = _word_export_source_stem_from_html(html_path) + files_by_name = _collect_word_export_image_files(source_stem, html_path.parent) + if not files_by_name: + return "", [] + + soup = BeautifulSoup(html, "html.parser") + body = soup.body or soup + _drop_deleted_revision_nodes(body) + uri_cache: dict[str, list[str]] = {} + + for table in body.find_all("table"): + rows: list[list[str]] = [] + used_uris: list[str] = [] + has_images = False + + for tr in table.find_all("tr"): + row: list[str] = [] + for td in tr.find_all(["th", "td"]): + txt = _norm_text(td.get_text(" ", strip=True)) + cell_uris: list[str] = [] + + for img in td.find_all("img"): + src = str(img.get("src") or "").strip() + if not src: + continue + name = src.replace("\\", "/").split("/")[-1].lower() + if not _WORD_EXPORT_IMAGE_NAME_RE.fullmatch(name): + continue + + style = " ".join( + [ + str(img.get("style") or ""), + str( + getattr( + getattr(img, "parent", None), "get", lambda *_: "" + )("style") + or "" + ), + ] + ).lower() + w = int(str(img.get("width") or "0").strip() or 0) + h = int(str(img.get("height") or "0").strip() or 0) + if w > 0 and h > 0 and (max(w, h) <= 32 or (w * h) < 2000): + continue + if ( + "position:absolute" in style + and w > 0 + and h > 0 + and w < 80 + and h > 260 + ): + continue + + image_file = files_by_name.get(name) + if image_file is None: + continue + if name not in uri_cache: + uri_cache[name] = _image_file_to_uris(image_file) + for uri in uri_cache[name]: + if uri not in cell_uris: + cell_uris.append(uri) + + if cell_uris: + has_images = True + used_uris.extend(cell_uris) + imgs_md = " <br> ".join(f"![table-image]({u})" for u in cell_uris) + row.append((txt + " <br> " if txt else "") + imgs_md) + else: + row.append(txt) + + while row and not row[-1]: + row.pop() + if any(row): + rows.append(row) + + if not rows or not has_images: + continue + + header_text = " ".join(_norm_text(c) for c in rows[0] if c) + header_low = header_text.lower() + if "workflow" not in header_low and "工作流程" not in header_text: + continue + if "operation requirements" not in header_low and "作业要求" not in header_text: + continue + + workflow_idx = next( + ( + i + for i, c in enumerate(rows[0]) + if "workflow" in c.lower() or "工作流程" in c + ), + None, + ) + if workflow_idx is not None: + img_md_pat = re.compile( + r"!\[table-image\]\(data:image/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+\)" + ) + for ridx in range(1, len(rows)): + row = rows[ridx] + while len(row) <= workflow_idx: + row.append("") + if row[workflow_idx].strip(): + continue + for cidx, cell in enumerate(row): + if cidx == workflow_idx or "![table-image](" not in cell: + continue + imgs = img_md_pat.findall(cell) + if not imgs: + continue + cleaned = cell + for imd in imgs: + cleaned = cleaned.replace(imd, "") + cleaned = re.sub(r"(?:\s*<br>\s*){2,}", " <br> ", cleaned).strip() + cleaned = re.sub( + r"^(?:<br>\s*)+|(?:\s*<br>)+$", "", cleaned + ).strip() + row[cidx] = cleaned + row[workflow_idx] = " <br> ".join(imgs) + break + + width = max(len(r) for r in rows) + norm = [r + [""] * (width - len(r)) for r in rows] + lines = [ + "| " + " | ".join(norm[0]) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + for r in norm[1:]: + lines.append("| " + " | ".join(r) + " |") + return "\n".join(lines), used_uris + + return "", [] + + +def _remove_consumed_uris(all_uris: list[str], consumed_uris: list[str]) -> list[str]: + if not consumed_uris: + return all_uris + counts: dict[str, int] = {} + for uri in consumed_uris: + counts[uri] = counts.get(uri, 0) + 1 + + kept: list[str] = [] + for uri in all_uris: + remain = counts.get(uri, 0) + if remain > 0: + counts[uri] = remain - 1 + continue + kept.append(uri) + return kept + + +def _extract_org_side_nodes_from_word_html(html_path: Path) -> str: + if not html_path.exists(): + return "" + try: + from bs4 import BeautifulSoup + except Exception: + return "" + + try: + html = _decode_word_html(html_path.read_bytes()) + except Exception: + return "" + + soup = BeautifulSoup(html, "html.parser") + _drop_deleted_revision_nodes(soup) + + labels: dict[str, str] = {} + for td in soup.find_all("td"): + txt = _norm_text(td.get_text(" ", strip=True)) + if not txt: + continue + low = txt.lower() + + if "report content" in low or "external report" in low or "外部报告" in txt: + continue + if re.search(r"\b(?:120|110|119)\b", txt): + continue + + if "hospital" in low or "医院" in txt: + labels["hospital"] = txt + if "fire control" in low or "firecontrol" in low or "消防" in txt: + labels["fire"] = txt + if "public security" in low or "publicsecurity" in low or "公安" in txt: + labels["public"] = txt + + if not labels: + return "" + + ordered = [ + labels.get("hospital", "医院 hospital"), + labels.get("fire", "消防 fire control"), + labels.get("public", "公安 Public Security"), + ] + ordered = [re.sub(r"\s+", " ", x).strip(" ;;") for x in ordered if x] + if not ordered: + return "" + return "外部支援补充节点:" + ";".join(ordered) + + +def _inject_org_side_nodes_after_612(parsed: list[Block], text: str, idx: int) -> int: + if not text: + return idx + + joined = "\n".join( + b.text for b in parsed if b.type in {"paragraph", "heading", "table"} and b.text + ) + low = joined.lower() + if all(k in low for k in ["hospital", "fire control", "public security"]): + return idx + + anchor = next( + ( + i + for i, b in enumerate(parsed) + if b.type in {"paragraph", "heading"} + and b.text + and ( + "6.1.1公司应急救援小组" in b.text + or re.match(r"^\s*6\.1\.1", b.text.strip()) + ) + ), + None, + ) + if anchor is None: + anchor = next( + ( + i + for i, b in enumerate(parsed) + if b.type in {"paragraph", "heading"} + and b.text + and ( + "6.1.2应急救援体系职责" in b.text + or re.match(r"^\s*6\.1\.2", b.text.strip()) + ) + ), + None, + ) + if anchor is None: + return idx + + idx += 1 + ay = float(parsed[anchor].bbox[3]) if parsed[anchor].bbox else float(anchor) + y = ay + 0.001 + block = Block( + id=f"docx-{idx}", + page=1, + type="paragraph", + text=text, + bbox=(0.0, y, 100.0, y + 0.001), + ) + parsed.insert(anchor + 1, block) + return idx + + +def _inject_word_workflow_table_images( + parsed: list[Block], html_path: Path +) -> list[str]: + table_md, consumed_uris = _extract_workflow_table_from_word_html(html_path) + if not table_md: + return [] + + target_idx = next( + ( + i + for i, b in enumerate(parsed) + if b.type == "table" + and "![table-image]" not in (b.text or "") + and ("工作流程" in (b.text or "") or "workflow" in (b.text or "").lower()) + and ( + "作业要求" in (b.text or "") + or "operation requirements" in (b.text or "").lower() + ) + ), + None, + ) + if target_idx is None: + return [] + + parsed[target_idx].text = table_md + return consumed_uris + + +def _extract_missing_611_blocks_from_word_html( + html_path: Path, + existing_text: str, + start_idx: int, +) -> list[Block]: + if "6.11" in existing_text: + return [] + + items = _extract_word_html_items(html_path) + if not items: + return [] + + paras = [v for k, v in items if k == "paragraph"] + cand = [i for i, p in enumerate(paras) if "6.11" in p] + if not cand: + return [] + + sec_start = None + for i in cand: + lo = max(0, i - 20) + if any("6.10" in paras[k] for k in range(lo, i)): + sec_start = i + break + if sec_start is None: + sec_start = cand[-1] + + section: list[str] = [] + j = sec_start + while j < len(paras): + nxt = paras[j] + if j > sec_start and re.match(r"^[一二三四五六七八九十]+、", nxt): + break + if j > sec_start and ("参考文件" in nxt or "相关表单" in nxt): + break + if ( + j > sec_start + and re.match(r"^6\.\d{1,2}(?:\.\d+)?", nxt) + and not nxt.startswith("6.11") + ): + break + section.append(nxt) + j += 1 + + section = [ + ln + for ln in section + if ln + and not re.fullmatch(r"\d{4}/\d{1,2}/\d{1,2}(?:\s+\d{4}/\d{1,2}/\d{1,2})*", ln) + and not re.fullmatch(r"V\d+(?:\.\d+)?(?:\s+V\d+(?:\.\d+)?)*", ln) + ] + + out: list[Block] = [] + idx = start_idx + + heading = section[0] if section else "" + body = section[1:] if len(section) >= 2 else [] + + if heading and heading not in existing_text: + idx += 1 + out.append( + Block( + id=f"docx-611-{idx}", + page=1, + type="paragraph", + text=heading, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + + header_i = None + for i in range(0, max(0, len(body) - 4)): + h = body[i : i + 5] + if len(h) < 5: + continue + if "备注" in h[4] and ("设备" in h[2] or "设备" in h[3]): + header_i = i + break + + if header_i is not None: + cells = body[header_i:] + header = cells[:5] + rows_raw = cells[5:] + rows: list[list[str]] = [] + for i in range(0, len(rows_raw), 5): + chunk = rows_raw[i : i + 5] + if len(chunk) == 5: + rows.append(chunk) + + if rows: + lines = [ + "| " + " | ".join(header) + " |", + "| " + " | ".join(["---"] * 5) + " |", + ] + for r in rows: + lines.append("| " + " | ".join(r) + " |") + table_md = "\n".join(lines) + if table_md not in existing_text: + idx += 1 + out.append( + Block( + id=f"docx-611-table-{idx}", + page=1, + type="table", + text=table_md, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + elif body: + for p in body: + if p and p not in existing_text: + idx += 1 + out.append( + Block( + id=f"docx-611-{idx}", + page=1, + type="paragraph", + text=p, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + + return out + + +def _extract_missing_634_badge_table_from_word_html( + html_path: Path, + existing_text: str, + start_idx: int, +) -> list[Block]: + if "站别" in existing_text and "佩戴袖章标示" in existing_text: + return [] + + items = _extract_word_html_items(html_path) + if not items: + return [] + + anchors = [i for i, (k, v) in enumerate(items) if k == "paragraph" and "6.3.4" in v] + if not anchors: + return [] + anchor_idx = anchors[-1] + + table_md = None + for k, v in items[anchor_idx + 1 : anchor_idx + 40]: + if k != "table": + continue + if "站别" in v and "上岗证名称" in v and "佩戴袖章标示" in v: + table_md = v + break + if not table_md: + return [] + + idx = start_idx + 1 + return [ + Block( + id=f"docx-634-{idx}", + page=1, + type="table", + text=table_md, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ] + + +def _table_to_markdown(table, doc) -> str: + rows: list[list[str]] = [] + seen_img_uri: set[str] = set() + for r in table.rows: + vals: list[str] = [] + for c in r.cells: + txt = _cell_text_without_revisions(c) + img_uris: list[str] = [] + try: + for para in c.paragraphs: + for uri in _extract_image_uris_from_paragraph(para, doc): + if uri in seen_img_uri: + continue + seen_img_uri.add(uri) + img_uris.append(uri) + except Exception: + img_uris = [] + + if img_uris: + imgs_md = " <br> ".join(f"![table-image]({u})" for u in img_uris) + vals.append((txt + " <br> " if txt else "") + imgs_md) + else: + vals.append(txt) + if any(v for v in vals): + rows.append(vals) + if not rows: + return "" + + width = max(len(r) for r in rows) + norm = [r + [""] * (width - len(r)) for r in rows] + + for i, r in enumerate(norm): + vals = [v for v in r if v] + if not vals: + continue + if vals[0].startswith("备注"): + uniq = list(dict.fromkeys(vals)) + if len(uniq) == 1: + norm[i] = [uniq[0]] + [""] * (width - 1) + continue + if len(set(vals)) == 1 and len(vals) >= 2: + norm[i] = [vals[0]] + [""] * (width - 1) + + header = norm[0] + lines = [ + "| " + " | ".join(header) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + note_blocks: list[str] = [] + for r in norm[1:]: + first = (r[0] or "").strip() + if first.startswith("备注") and not any((c or "").strip() for c in r[1:]): + note = re.sub(r"\s+", " ", first) + note = re.sub(r"\s*(\d+)\.", r"\n\1.", note) + note_blocks.append(note.strip()) + continue + lines.append("| " + " | ".join(r) + " |") + + if note_blocks: + lines.append("") + lines.extend(note_blocks) + return "\n".join(lines) + + +def _looks_like_form_metadata_table(md: str) -> bool: + flat = " ".join(md.split()) + score = 0 + for token in [ + "文件类别", + "File category", + "文件编号", + "Document No", + "页 数 Page", + "制/修订日期", + "Issued/Revised Date", + ]: + if token in flat: + score += 1 + return score >= 3 + + +def _table_markdown_to_paragraph_blocks(md: str, start_idx: int) -> list[Block]: + lines = [ln.strip() for ln in md.splitlines() if ln.strip()] + out: list[Block] = [] + idx = start_idx + for line in lines: + if not line.startswith("|"): + continue + cells = [c.strip() for c in line.strip("|").split("|")] + cells = [c for c in cells if c and c != "---"] + if not cells: + continue + text = "\n".join(cells) + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="paragraph", + text=text, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + return out + + +def _form_table_to_blocks(table, start_idx: int) -> list[Block]: + out: list[Block] = [] + idx = start_idx + metadata_rows: list[list[str]] = [] + for row in table.rows: + row_cells: list[list[str]] = [] + for cell in row.cells: + parts = _cell_paragraph_texts_without_revisions(cell) + if parts: + row_cells.append(parts) + if not row_cells: + continue + + flattened = [p for parts in row_cells for p in parts if p] + if not flattened: + continue + + unique_flat = list(dict.fromkeys(flattened)) + row_patterns = {tuple(parts) for parts in row_cells} + if len(row_patterns) == 1 and len(row_cells) >= 2: + first = (unique_flat[0] if unique_flat else "").strip() + if "文件修订履历" in first or "Document revision history" in first: + if metadata_rows: + width = max(len(r) for r in metadata_rows) + norm = [r + [""] * (width - len(r)) for r in metadata_rows] + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="table", + text="\n".join( + [ + "| " + " | ".join(norm[0]) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + + ["| " + " | ".join(r) + " |" for r in norm[1:]] + ), + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + metadata_rows = [] + for para in unique_flat: + para = para.strip() + if not para: + continue + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="paragraph", + text=para, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + continue + if first and not re.search( + r"^(?:[一二三四五六七八九十]+、|\d+\.\d+|[A-Za-z]+、)", first + ): + metadata_rows.append(unique_flat) + continue + if metadata_rows: + width = max(len(r) for r in metadata_rows) + norm = [r + [""] * (width - len(r)) for r in metadata_rows] + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="table", + text="\n".join( + [ + "| " + " | ".join(norm[0]) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + + ["| " + " | ".join(r) + " |" for r in norm[1:]] + ), + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + metadata_rows = [] + for para in unique_flat: + para = para.strip() + if not para: + continue + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="paragraph", + text=para, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + continue + + compact = [" / ".join(parts) for parts in row_cells if parts] + text = "\n".join(compact).strip() + if not text: + continue + metadata_rows.append(compact) + if metadata_rows: + width = max(len(r) for r in metadata_rows) + norm = [r + [""] * (width - len(r)) for r in metadata_rows] + idx += 1 + out.append( + Block( + id=f"docx-{idx}", + page=1, + type="table", + text="\n".join( + [ + "| " + " | ".join(norm[0]) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + + ["| " + " | ".join(r) + " |" for r in norm[1:]] + ), + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + return out + + +def _extract_header_lines(doc) -> list[str]: + out: list[str] = [] + seen: set[str] = set() + for section in doc.sections: + header = section.header + for p in header.paragraphs: + s = _paragraph_text_without_revisions(p) + if s and s not in seen: + seen.add(s) + out.append(s) + for t in header.tables: + for r in t.rows: + vals = [_cell_text_without_revisions(c) for c in r.cells] + vals = [v for v in vals if v] + if not vals: + continue + s = " ".join(vals) + if s and s not in seen: + seen.add(s) + out.append(s) + return out + + +def _drop_cover_header_duplicates(blocks: list[Block]) -> list[Block]: + first_table_idx = next( + (i for i, b in enumerate(blocks[:12]) if b.type == "table"), None + ) + if first_table_idx is None: + return blocks + table_text = blocks[first_table_idx].text or "" + if "文件类别" not in table_text and "File category" not in table_text: + return blocks + meta_pat = re.compile( + r"文件编号|Document No|文件名称|File name|制定部门|Preparation department|页 数|Page", + re.IGNORECASE, + ) + kept: list[Block] = [] + for i, block in enumerate(blocks): + if ( + i < first_table_idx + and block.type == "paragraph" + and meta_pat.search(block.text or "") + ): + continue + kept.append(block) + return kept + + +def _convert_doc_with_word(path: Path, out_dir: Path) -> Path: + out_dir.mkdir(parents=True, exist_ok=True) + output = out_dir / f"{path.stem}.docx" + return convert_with_word(path.resolve(), output.resolve(), 16) + + +def _convert_doc_to_docx(path: Path, out_dir: Path) -> Path: + out_dir.mkdir(parents=True, exist_ok=True) + output = out_dir / f"{path.stem}.docx" + force_reconvert = str( + os.environ.get("EDKB_FORCE_DOC_RECONVERT", "") + ).strip().lower() in { + "1", + "true", + "yes", + } + try: + if not force_reconvert and output.exists() and output.stat().st_size > 0: + return output + except Exception: + pass + + errors: list[str] = [] + + if os.name == "nt": + try: + return _convert_doc_with_word(path, out_dir) + except Exception as exc: + errors.append(f"Word COM conversion failed: {exc}") + + soffice_candidates = [ + os.environ.get("EDKB_SOFFICE"), + r"C:\Program Files\LibreOffice\program\soffice.exe", + r"C:\Program Files (x86)\LibreOffice\program\soffice.exe", + "soffice", + ] + for soffice in soffice_candidates: + if not soffice: + continue + cmd = [ + soffice, + "--headless", + "--convert-to", + "docx", + str(path), + "--outdir", + str(out_dir), + ] + try: + proc = subprocess.run(cmd, capture_output=True, text=True) + except FileNotFoundError: + errors.append(f"soffice not found: {soffice}") + continue + + if proc.returncode == 0 and output.exists(): + return output + + stderr = (proc.stderr or "").strip() + errors.append( + f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}" + ) + + joined = "; ".join(errors) if errors else "no converter attempted" + raise RuntimeError( + ".doc 转 .docx 失败。请安装 LibreOffice(soffice)或本机 Microsoft Word。" + f" details: {joined}" + ) + + +def run(input_data: dict, context: Context) -> list[Block]: + source_path = Path(input_data["file_path"]).resolve() + file_path = source_path + work_dir = Path(input_data["work_dir"]).resolve() + source_ext = source_path.suffix.lower() + + if source_ext == ".doc": + file_path = _convert_doc_to_docx(file_path, work_dir) + + def _parse_docx(docx_path: Path) -> list[Block]: + from docx import Document + from docx.oxml.table import CT_Tbl + from docx.oxml.text.paragraph import CT_P + from docx.table import Table + from docx.text.paragraph import Paragraph + + parsed: list[Block] = [] + doc = Document(str(docx_path)) + num_to_abs, levels = _load_numbering_schema(docx_path) + list_states: dict[str, dict[int, int]] = {} + context.pages = 1 + idx = 0 + + for line in _extract_header_lines(doc): + idx += 1 + parsed.append( + Block( + id=f"docx-{idx}", + page=1, + type="paragraph", + text=line, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + + for child in doc.element.body.iterchildren(): + if isinstance(child, CT_P): + para = Paragraph(child, doc) + text = _paragraph_text_without_revisions(para).strip() + marker = "" + try: + ppr = para._p.pPr + if ppr is not None and ppr.numPr is not None: + ilvl = ( + int(ppr.numPr.ilvl.val) if ppr.numPr.ilvl is not None else 0 + ) + num_id = ( + str(ppr.numPr.numId.val) + if ppr.numPr.numId is not None + else "" + ) + if num_id: + marker = _next_list_marker( + num_id, ilvl, num_to_abs, levels, list_states + ) + except Exception: + marker = "" + + if marker and text and not text.startswith(marker): + text = f"{marker} {text}" + image_uris = _extract_image_uris_from_paragraph(para, doc) + if text: + idx += 1 + typ = ( + "heading" + if para.style and "heading" in para.style.name.lower() + else "paragraph" + ) + parsed.append( + Block( + id=f"docx-{idx}", + page=1, + type=typ, + text=text, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + for uri in image_uris: + idx += 1 + context.images += 1 + parsed.append( + Block( + id=f"docx-img-{idx}", + page=1, + type="image", + text="", + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + meta={"data_uri": uri}, + ) + ) + elif isinstance(child, CT_Tbl): + table = Table(child, doc) + md = _table_to_markdown(table, doc) + if md: + if _looks_like_form_metadata_table(md): + blocks = _form_table_to_blocks(table, idx) + if blocks: + idx += len(blocks) + parsed.extend(blocks) + else: + idx += 1 + parsed.append( + Block( + id=f"docx-{idx}", + page=1, + type="table", + text=md, + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + ) + ) + + # 表格内图片已并入表格 markdown 单元格,避免脱离原始位置。 + + if not any(b.type == "image" for b in parsed): + for uri in _extract_all_image_uris_from_doc(doc): + idx += 1 + context.images += 1 + parsed.append( + Block( + id=f"docx-img-{idx}", + page=1, + type="image", + text="", + bbox=(0.0, float(idx), 100.0, float(idx) + 1), + meta={"data_uri": uri}, + ) + ) + if source_ext == ".doc": + try: + word_export_dir = work_dir / "word_export" + word_images = _extract_images_with_word(source_path, word_export_dir) + html_path = word_export_dir / f"{source_path.stem}.word_export.html" + org_side_nodes = _extract_org_side_nodes_from_word_html(html_path) + + consumed_uris = _inject_word_workflow_table_images(parsed, html_path) + if consumed_uris: + word_images = _remove_consumed_uris(word_images, consumed_uris) + + current_imgs = [b for b in parsed if b.type == "image"] + if len(word_images) > len(current_imgs): + image_slots = [i for i, b in enumerate(parsed) if b.type == "image"] + replaced: list[Block] = [] + used = 0 + for b in parsed: + if b.type != "image": + replaced.append(b) + continue + if used < len(word_images): + uri = word_images[used] + used += 1 + context.images += 1 + replaced.append( + Block( + id=f"docx-img-{len(replaced) + 1}", + page=b.page, + type="image", + text="", + bbox=b.bbox, + meta={"data_uri": uri}, + ) + ) + insert_at = image_slots[-1] + 1 if image_slots else len(replaced) + while used < len(word_images): + uri = word_images[used] + used += 1 + context.images += 1 + replaced.insert( + insert_at, + Block( + id=f"docx-img-{insert_at + 1}", + page=1, + type="image", + text="", + bbox=( + 0.0, + float(insert_at + 1), + 100.0, + float(insert_at + 2), + ), + meta={"data_uri": uri}, + ), + ) + insert_at += 1 + parsed = replaced + + if org_side_nodes: + idx = _inject_org_side_nodes_after_612(parsed, org_side_nodes, idx) + + existing_text = "\n".join( + b.text + for b in parsed + if b.type in {"paragraph", "heading", "table"} and b.text + ) + added = _extract_missing_611_blocks_from_word_html( + html_path, + existing_text, + len(parsed), + ) + if added: + insert_at = next( + ( + i + for i, b in enumerate(parsed) + if b.type in {"paragraph", "heading"} + and ( + "参考文件" in (b.text or "") + or "相关表单" in (b.text or "") + ) + ), + len(parsed), + ) + parsed = parsed[:insert_at] + added + parsed[insert_at:] + + added_634 = _extract_missing_634_badge_table_from_word_html( + html_path, + "\n".join( + b.text + for b in parsed + if b.type in {"paragraph", "heading", "table"} and b.text + ), + len(parsed), + ) + if added_634: + anchor_y = None + for b in parsed: + if b.type in {"paragraph", "heading"} and "6.3.4" in ( + b.text or "" + ): + anchor_y = b.bbox[1] + break + if anchor_y is None: + anchor_y = float(len(parsed)) + for n, blk in enumerate(added_634, start=1): + y = float(anchor_y) + 0.9 + 0.05 * n + blk.bbox = (0.0, y, 100.0, y + 0.01) + + insert_at_634 = next( + ( + i + 1 + for i, b in enumerate(parsed) + if b.type in {"paragraph", "heading"} + and "6.3.4" in (b.text or "") + ), + next( + ( + i + for i, b in enumerate(parsed) + if b.type in {"paragraph", "heading"} + and re.match(r"^\s*[七七]、", (b.text or "").strip()) + ), + len(parsed), + ), + ) + parsed = parsed[:insert_at_634] + added_634 + parsed[insert_at_634:] + + if word_images: + final_imgs = [b for b in parsed if b.type == "image"] + if len(final_imgs) < len(word_images): + seen = { + hashlib.sha1( + (b.meta or {}).get("data_uri", "").encode("utf-8") + ).hexdigest() + for b in final_imgs + if (b.meta or {}).get("data_uri") + } + insert_at = len(parsed) + for uri in word_images: + key = hashlib.sha1(uri.encode("utf-8")).hexdigest() + if key in seen: + continue + seen.add(key) + insert_at += 1 + context.images += 1 + parsed.append( + Block( + id=f"docx-img-{insert_at}", + page=1, + type="image", + text="", + bbox=( + 0.0, + float(insert_at), + 100.0, + float(insert_at) + 1, + ), + meta={"data_uri": uri}, + ) + ) + except Exception: + pass + + parsed = _drop_cover_header_duplicates(parsed) + return parsed + + try: + return _parse_docx(file_path) + except Exception as exc: + if file_path.suffix.lower() == ".docx": + try: + repaired = _convert_doc_with_word(file_path, work_dir) + return _parse_docx(repaired) + except Exception as fix_exc: + try: + legacy = work_dir / f"{file_path.stem}.legacy.doc" + shutil.copyfile(file_path, legacy) + repaired = _convert_doc_with_word(legacy, work_dir) + return _parse_docx(repaired) + except Exception as legacy_exc: + context.warnings.append( + "DOCX fallback parser failed: " + f"{exc}; repair failed: {fix_exc}; legacy-doc repair failed: {legacy_exc}" + ) + return [] + context.warnings.append(f"DOCX fallback parser failed: {exc}") + return [] diff --git a/backend/edkb_system/skills/loader_excel.py b/backend/edkb_system/skills/loader_excel.py new file mode 100644 index 00000000..588c1427 --- /dev/null +++ b/backend/edkb_system/skills/loader_excel.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +from openpyxl import load_workbook + +from edkb_system.contracts import Context + + +def _soffice_candidates() -> list[str]: + return [ + os.environ.get("EDKB_SOFFICE", "").strip(), + r"C:\Program Files\LibreOffice\program\soffice.exe", + r"C:\Program Files (x86)\LibreOffice\program\soffice.exe", + "soffice", + ] + + +def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path: + out_dir.mkdir(parents=True, exist_ok=True) + output = out_dir / f"{path.stem}.xlsx" + errors: list[str] = [] + for soffice in _soffice_candidates(): + if not soffice: + continue + cmd = [ + soffice, + "--headless", + "--convert-to", + "xlsx", + str(path), + "--outdir", + str(out_dir), + ] + try: + proc = subprocess.run(cmd, capture_output=True, text=True) + except FileNotFoundError: + errors.append(f"soffice not found: {soffice}") + continue + if proc.returncode == 0 and output.exists(): + return output + stderr = (proc.stderr or "").strip() + errors.append( + f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}" + ) + + joined = "; ".join(errors) if errors else "no converter attempted" + raise RuntimeError( + ".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)或设置 EDKB_SOFFICE。" + f" details: {joined}" + ) + + +def _norm(v) -> str: + return "" if v is None else str(v).strip() + + +def _trim_trailing_empty(vals: list[str]) -> list[str]: + end = len(vals) + while end > 0 and not vals[end - 1]: + end -= 1 + return vals[:end] + + +def run(input_data: dict, context: Context) -> list[dict]: + file_path = Path(input_data["file_path"]) + work_dir = Path(input_data["work_dir"]) + if file_path.suffix.lower() == ".xls": + file_path = _convert_xls_to_xlsx(file_path, work_dir) + + wb = load_workbook(str(file_path), data_only=True) + tables: list[dict] = [] + for ws in wb.worksheets: + rows: list[list[str]] = [] + for row in ws.iter_rows(values_only=True): + vals = _trim_trailing_empty([_norm(v) for v in row]) + if any(vals): + rows.append(vals) + if not rows: + continue + width = max(len(r) for r in rows) + normalized = [r + [""] * (width - len(r)) for r in rows] + tables.append( + {"sheet": ws.title, "headers": normalized[0], "rows": normalized[1:]} + ) + context.extras["tables_count"] = len(tables) + return tables diff --git a/backend/edkb_system/skills/loader_pdf.py b/backend/edkb_system/skills/loader_pdf.py new file mode 100644 index 00000000..039f6a1f --- /dev/null +++ b/backend/edkb_system/skills/loader_pdf.py @@ -0,0 +1,250 @@ +from __future__ import annotations + +import base64 +import io +from pathlib import Path + +from edkb_system.contracts import Block, Context + + +def _is_scanned(text_chars: int, pages: int) -> bool: + return text_chars < int(300 * max(pages, 1) / 10) + + +def _to_data_uri(blob: bytes, content_type: str = "image/png") -> str: + b64 = base64.b64encode(blob).decode("ascii") + return f"data:{content_type};base64,{b64}" + + +def _normalize_box( + bounds: tuple[float, float, float, float], +) -> tuple[float, float, float, float]: + x0, y0, x1, y1 = bounds + left = min(x0, x1) + right = max(x0, x1) + top = min(y0, y1) + bottom = max(y0, y1) + return (left, top, right, bottom) + + +def _page_image_stats( + page_width: float, + page_height: float, + image_boxes: list[tuple[float, float, float, float]], +) -> dict[str, float]: + if page_width <= 0 or page_height <= 0 or not image_boxes: + return { + "count": float(len(image_boxes)), + "largest_ratio": 0.0, + "total_ratio": 0.0, + } + + page_area = max(page_width * page_height, 1.0) + largest_ratio = 0.0 + total_ratio = 0.0 + for raw in image_boxes: + x0, y0, x1, y1 = _normalize_box(raw) + width = max(x1 - x0, 0.0) + height = max(y1 - y0, 0.0) + ratio = min((width * height) / page_area, 1.0) + largest_ratio = max(largest_ratio, ratio) + total_ratio += ratio + return { + "count": float(len(image_boxes)), + "largest_ratio": largest_ratio, + "total_ratio": min(total_ratio, 1.5), + } + + +def _should_use_page_image_mode( + *, + scan_likely: bool, + text_chars: int, + image_count: int, + largest_ratio: float, + total_ratio: float, +) -> bool: + if scan_likely: + if image_count == 0: + return True + if largest_ratio >= 0.55 or total_ratio >= 0.65 or image_count >= 3: + return True + if text_chars <= 120 and ( + largest_ratio >= 0.72 or (image_count >= 5 and total_ratio >= 0.45) + ): + return True + return False + + +def _collect_image_boxes( + file_path: Path, page_count: int +) -> dict[int, list[tuple[float, float, float, float]]]: + try: + import pypdfium2 as pdfium + import pypdfium2.raw as pdfium_c + except Exception: + return {} + + out: dict[int, list[tuple[float, float, float, float]]] = {} + doc = None + try: + doc = pdfium.PdfDocument(str(file_path)) + for page_idx in range(page_count): + page = doc[page_idx] + boxes: list[tuple[float, float, float, float]] = [] + try: + for obj in page.get_objects(filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE]): + try: + bounds = obj.get_bounds() + except Exception: + bounds = obj.get_pos() + boxes.append(tuple(float(v) for v in bounds)) + except Exception: + boxes = [] + out[page_idx + 1] = boxes + except Exception: + return {} + finally: + try: + if doc is not None: + doc.close() + except Exception: + pass + return out + + +def _render_page_png( + file_path: Path, page_number: int, scale: float = 2.0 +) -> bytes | None: + try: + import pypdfium2 as pdfium + except Exception: + return None + + doc = None + try: + doc = pdfium.PdfDocument(str(file_path)) + page = doc[page_number - 1] + bitmap = page.render(scale=scale) + pil_image = bitmap.to_pil() + buf = io.BytesIO() + pil_image.save(buf, format="PNG") + return buf.getvalue() + except Exception: + return None + finally: + try: + if doc is not None: + doc.close() + except Exception: + pass + + +def run(input_data: dict, context: Context) -> list[Block]: + file_path = Path(input_data["file_path"]) + blocks: list[Block] = [] + + try: + from pypdf import PdfReader + + reader = PdfReader(str(file_path)) + context.pages = len(reader.pages) + text_chars = 0 + page_payloads: list[dict] = [] + for page_idx, p in enumerate(reader.pages, start=1): + text = (p.extract_text() or "").strip() + images: list[dict] = [] + if text: + text_chars += len(text) + + try: + for img_idx, img in enumerate(getattr(p, "images", []) or [], start=1): + data = getattr(img, "data", None) + if not data: + continue + ext = (getattr(img, "image_format", "") or "").lower() + ct = f"image/{ext}" if ext else "image/png" + images.append({"id": img_idx, "data": data, "content_type": ct}) + except Exception: + pass + page_payloads.append({"page": page_idx, "text": text, "images": images}) + + scan_likely = _is_scanned(text_chars, context.pages) + image_boxes_by_page = _collect_image_boxes(file_path, context.pages) + page_image_mode_pages: list[int] = [] + + for payload in page_payloads: + page_idx = int(payload["page"]) + text = str(payload["text"] or "") + page_images = list(payload["images"]) + image_boxes = image_boxes_by_page.get(page_idx, []) + stats = _page_image_stats(1000.0, 1000.0, image_boxes) + use_page_image_mode = _should_use_page_image_mode( + scan_likely=scan_likely, + text_chars=len(text), + image_count=len(page_images) or int(stats["count"]), + largest_ratio=float(stats["largest_ratio"]), + total_ratio=float(stats["total_ratio"]), + ) + + if text: + blocks.append( + Block( + id=f"pdf-{page_idx}", + page=page_idx, + type="paragraph", + text=text, + bbox=(0.0, 0.0, 1000.0, 1000.0), + ) + ) + + if use_page_image_mode: + rendered = _render_page_png(file_path, page_idx) + if rendered: + blocks.append( + Block( + id=f"pdf-page-{page_idx}", + page=page_idx, + type="image", + text="", + bbox=(0.0, 0.0, 1000.0, 1000.0), + meta={ + "data_uri": _to_data_uri(rendered, "image/png"), + "page_image": True, + }, + ) + ) + context.images += 1 + page_image_mode_pages.append(page_idx) + continue + + for item in page_images: + blocks.append( + Block( + id=f"pdf-{page_idx}-img-{item['id']}", + page=page_idx, + type="image", + text="", + bbox=(0.0, 0.0, 1000.0, 1000.0), + meta={ + "data_uri": _to_data_uri( + item["data"], str(item["content_type"]) + ) + }, + ) + ) + context.images += 1 + + if scan_likely: + context.warnings.append("pdf likely scanned; OCR recommended") + context.extras["scan_likely"] = True + if page_image_mode_pages: + context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages + context.warnings.append( + "pdf page-image mode pages: " + + ", ".join(str(x) for x in page_image_mode_pages) + ) + except Exception as exc: + context.warnings.append(f"PDF parse failed: {exc}") + + return blocks diff --git a/backend/edkb_system/skills/loader_pptx.py b/backend/edkb_system/skills/loader_pptx.py new file mode 100644 index 00000000..c9566696 --- /dev/null +++ b/backend/edkb_system/skills/loader_pptx.py @@ -0,0 +1,478 @@ +from __future__ import annotations + +import base64 +import hashlib +import io +import re +import subprocess +from pathlib import Path + +from edkb_system.contracts import Block, Context + + +def _to_data_uri(blob: bytes, content_type: str) -> str: + return f"data:{content_type};base64,{base64.b64encode(blob).decode('ascii')}" + + +def _convert_ppt_to_pptx(path: Path, out_dir: Path) -> Path: + out_dir.mkdir(parents=True, exist_ok=True) + cmd = [ + "soffice", + "--headless", + "--convert-to", + "pptx", + str(path), + "--outdir", + str(out_dir), + ] + proc = subprocess.run(cmd, capture_output=True, text=True) + if proc.returncode != 0: + raise RuntimeError("Install LibreOffice to convert .ppt to .pptx") + output = out_dir / f"{path.stem}.pptx" + if not output.exists(): + raise RuntimeError("Install LibreOffice to convert .ppt to .pptx") + return output + + +def _convert_presentation_to_pdf(path: Path, out_dir: Path) -> Path | None: + out_dir.mkdir(parents=True, exist_ok=True) + cmd = [ + "soffice", + "--headless", + "--convert-to", + "pdf", + str(path), + "--outdir", + str(out_dir), + ] + try: + proc = subprocess.run(cmd, capture_output=True, text=True) + except FileNotFoundError: + return None + if proc.returncode != 0: + return None + output = out_dir / f"{path.stem}.pdf" + return output if output.exists() else None + + +def _export_slide_pngs(path: Path, out_dir: Path) -> dict[int, bytes]: + out_dir.mkdir(parents=True, exist_ok=True) + app = None + pres = None + output: dict[int, bytes] = {} + try: + from win32com.client import DispatchEx + + app = DispatchEx("PowerPoint.Application") + pres = app.Presentations.Open(str(path), WithWindow=False) + for idx, slide in enumerate(pres.Slides, start=1): + target = out_dir / f"slide_{idx:03d}.png" + slide.Export(str(target), "PNG") + if target.exists(): + output[idx] = target.read_bytes() + except Exception: + return {} + finally: + if pres is not None: + try: + pres.Close() + except Exception: + pass + if app is not None: + try: + app.Quit() + except Exception: + pass + return output + + +def _norm_text(text: str) -> str: + return "\n".join(x.strip() for x in (text or "").splitlines() if x.strip()).strip() + + +def _shape_bbox(shape) -> tuple[float, float, float, float]: + left = float(getattr(shape, "left", 0)) + top = float(getattr(shape, "top", 0)) + width = float(getattr(shape, "width", 0)) + height = float(getattr(shape, "height", 0)) + return (left, top, left + width, top + height) + + +def _image_pixel_size(blob: bytes) -> tuple[int, int]: + try: + from PIL import Image + + with Image.open(io.BytesIO(blob)) as im: + return int(im.width), int(im.height) + except Exception: + return (0, 0) + + +def _is_small_decorative_image( + blob: bytes, bbox: tuple[float, float, float, float], slide_area: float +) -> bool: + width_px, height_px = _image_pixel_size(blob) + pixel_area = max(width_px, 0) * max(height_px, 0) + box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0) + if ( + width_px + and height_px + and (width_px <= 48 or height_px <= 48 or pixel_area <= 6400) + ): + return True + if slide_area > 0 and box_area / slide_area <= 0.015 and pixel_area <= 20000: + return True + return False + + +def _is_dominant_picture( + bbox: tuple[float, float, float, float], slide_area: float +) -> bool: + box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0) + if slide_area <= 0: + return False + return box_area / slide_area >= 0.45 + + +def _table_to_markdown(table) -> str: + rows: list[list[str]] = [] + for row in table.rows: + vals = [ + " ".join( + p.text.strip() for p in cell.text_frame.paragraphs if p.text.strip() + ) + for cell in row.cells + ] + vals = [v.strip() for v in vals] + if any(vals): + rows.append(vals) + if not rows: + return "" + width = max(len(r) for r in rows) + norm = [r + [""] * (width - len(r)) for r in rows] + header = norm[0] + body = norm[1:] + lines = [ + "| " + " | ".join(header) + " |", + "| " + " | ".join(["---"] * width) + " |", + ] + lines.extend("| " + " | ".join(r) + " |" for r in body) + return "\n".join(lines) + + +def _render_pdf_page_png( + pdf_path: Path, page_number: int, scale: float = 2.0 +) -> bytes | None: + try: + import pypdfium2 as pdfium + except Exception: + return None + + doc = None + try: + doc = pdfium.PdfDocument(str(pdf_path)) + page = doc[page_number - 1] + bitmap = page.render(scale=scale) + pil_image = bitmap.to_pil() + buf = io.BytesIO() + pil_image.save(buf, format="PNG") + return buf.getvalue() + except Exception: + return None + finally: + try: + if doc is not None: + doc.close() + except Exception: + pass + + +def _crop_rendered_region( + rendered: bytes, + *, + crop_bbox: tuple[float, float, float, float], + slide_width: float, + slide_height: float, + padding: float = 0.03, +) -> bytes | None: + try: + from PIL import Image + + with Image.open(io.BytesIO(rendered)) as im: + x0, y0, x1, y1 = crop_bbox + pad_x = slide_width * padding + pad_y = slide_height * padding + x0 = max(0.0, x0 - pad_x) + y0 = max(0.0, y0 - pad_y) + x1 = min(slide_width, x1 + pad_x) + y1 = min(slide_height, y1 + pad_y) + if x1 <= x0 or y1 <= y0: + return None + scale_x = im.width / max(slide_width, 1.0) + scale_y = im.height / max(slide_height, 1.0) + box = ( + int(x0 * scale_x), + int(y0 * scale_y), + int(x1 * scale_x), + int(y1 * scale_y), + ) + cropped = im.crop(box) + buf = io.BytesIO() + cropped.save(buf, format="PNG") + return buf.getvalue() + except Exception: + return None + + +def _union_bboxes( + boxes: list[tuple[float, float, float, float]], +) -> tuple[float, float, float, float] | None: + if not boxes: + return None + x0 = min(b[0] for b in boxes) + y0 = min(b[1] for b in boxes) + x1 = max(b[2] for b in boxes) + y1 = max(b[3] for b in boxes) + return (x0, y0, x1, y1) + + +def _bbox_overlap_ratio( + a: tuple[float, float, float, float], b: tuple[float, float, float, float] +) -> float: + ax0, ay0, ax1, ay1 = a + bx0, by0, bx1, by1 = b + ix0 = max(ax0, bx0) + iy0 = max(ay0, by0) + ix1 = min(ax1, bx1) + iy1 = min(ay1, by1) + if ix1 <= ix0 or iy1 <= iy0: + return 0.0 + inter = (ix1 - ix0) * (iy1 - iy0) + area = max((ax1 - ax0) * (ay1 - ay0), 1.0) + return inter / area + + +def _pick_slide_title(flat_shapes) -> str: + candidates: list[tuple[float, float, str]] = [] + for shape in flat_shapes: + if not getattr(shape, "has_text_frame", False): + continue + txt = _norm_text(getattr(shape, "text", "")) + if not txt: + continue + top = float(getattr(shape, "top", 0)) + left = float(getattr(shape, "left", 0)) + candidates.append((top, left, txt)) + if not candidates: + return "" + candidates.sort(key=lambda x: (x[0], x[1])) + preferred_pat = re.compile(r"^(?:[一二三四五六七八九十]+、|\d+(?:\.\d+){0,2})") + for top, left, txt in candidates[:6]: + first_line = txt.splitlines()[0].strip() + if preferred_pat.match(first_line) and top <= 1200000: + return first_line + for top, left, txt in candidates[:6]: + first_line = txt.splitlines()[0].strip() + if 2 <= len(first_line) <= 30 and top <= 1800000: + return first_line + return candidates[0][2].splitlines()[0].strip() + + +def _iter_shapes(shapes): + from pptx.enum.shapes import MSO_SHAPE_TYPE + + for shape in shapes: + yield shape + if getattr(shape, "shape_type", None) == MSO_SHAPE_TYPE.GROUP: + for child in _iter_shapes(shape.shapes): + yield child + + +def run(input_data: dict, context: Context) -> list[Block]: + file_path = Path(input_data["file_path"]) + work_dir = Path(input_data["work_dir"]) + if file_path.suffix.lower() == ".ppt": + file_path = _convert_ppt_to_pptx(file_path, work_dir) + + from pptx import Presentation + from pptx.enum.shapes import MSO_SHAPE_TYPE + + prs = Presentation(str(file_path)) + slide_pngs = _export_slide_pngs(file_path, work_dir / f"{file_path.stem}_slides") + pdf_path = None if slide_pngs else _convert_presentation_to_pdf(file_path, work_dir) + context.pages = len(prs.slides) + blocks: list[Block] = [] + img_idx = 0 + blk_idx = 0 + slide_area = float(prs.slide_width) * float(prs.slide_height) + + for slide_no, slide in enumerate(prs.slides, start=1): + flat_shapes = list(_iter_shapes(slide.shapes)) + title_text = _norm_text( + getattr(getattr(slide.shapes, "title", None), "text", "") + ) + if not title_text: + title_text = _pick_slide_title(flat_shapes) + heading_text = f"第{slide_no}页" + if title_text: + heading_text = f"第{slide_no}页 {title_text}" + blk_idx += 1 + blocks.append( + Block( + id=f"pptx-{slide_no}-heading-{blk_idx}", + page=slide_no, + type="heading", + text=heading_text, + bbox=(0.0, 0.0, 0.0, 0.0), + ) + ) + + seen_image_hashes: set[str] = set() + dominant_pictures = 0 + shape_heavy = 0 + flow_boxes: list[tuple[float, float, float, float]] = [] + suppress_all_images = title_text == "目录" + + for shape in flat_shapes: + try: + if shape.shape_type == MSO_SHAPE_TYPE.PICTURE: + image = shape.image + bbox = _shape_bbox(shape) + blob_hash = hashlib.sha1(image.blob).hexdigest() + if blob_hash in seen_image_hashes: + continue + seen_image_hashes.add(blob_hash) + if _is_small_decorative_image(image.blob, bbox, slide_area): + continue + if _is_dominant_picture(bbox, slide_area): + dominant_pictures += 1 + elif shape.shape_type in { + MSO_SHAPE_TYPE.AUTO_SHAPE, + MSO_SHAPE_TYPE.LINE, + MSO_SHAPE_TYPE.FREEFORM, + }: + shape_heavy += 1 + bbox = _shape_bbox(shape) + mid_x = (bbox[0] + bbox[2]) / 2.0 + if ( + bbox[2] > bbox[0] + and bbox[3] > bbox[1] + and mid_x >= float(prs.slide_width) * 0.18 + ): + flow_boxes.append(bbox) + except Exception as exc: + context.warnings.append(f"pptx picture skipped: {exc}") + + seen_image_hashes.clear() + render_flow_focus = ( + (not suppress_all_images) + and bool(slide_pngs or pdf_path) + and shape_heavy >= 8 + and dominant_pictures == 0 + ) + flow_crop: tuple[float, float, float, float] | None = None + if render_flow_focus: + rendered = slide_pngs.get(slide_no) + if rendered is None and pdf_path is not None: + rendered = _render_pdf_page_png(pdf_path, slide_no) + if rendered: + flow_crop = (0.0, 0.0, float(prs.slide_width), float(prs.slide_height)) + img_idx += 1 + blocks.append( + Block( + id=f"pptx-flow-{slide_no}-{img_idx}", + page=slide_no, + type="image", + text="", + bbox=flow_crop, + meta={ + "data_uri": _to_data_uri(rendered, "image/png"), + "flow_focus": True, + "flow_focus_source": "pptx", + "rendered_slide": True, + }, + ) + ) + + for shape in flat_shapes: + try: + if getattr(shape, "has_table", False): + table_md = _table_to_markdown(shape.table) + if table_md: + blk_idx += 1 + blocks.append( + Block( + id=f"pptx-{slide_no}-table-{blk_idx}", + page=slide_no, + type="table", + text=table_md, + bbox=_shape_bbox(shape), + ) + ) + continue + + if shape.shape_type == MSO_SHAPE_TYPE.PICTURE: + if render_flow_focus or suppress_all_images: + continue + is_dominant = False + image = shape.image + bbox = _shape_bbox(shape) + blob_hash = hashlib.sha1(image.blob).hexdigest() + if blob_hash in seen_image_hashes: + continue + seen_image_hashes.add(blob_hash) + if _is_small_decorative_image(image.blob, bbox, slide_area): + continue + is_dominant = _is_dominant_picture(bbox, slide_area) + img_idx += 1 + ext = (getattr(image, "ext", "png") or "png").lower() + ct = f"image/{'jpeg' if ext == 'jpg' else ext}" + meta: dict[str, object] = { + "data_uri": _to_data_uri(image.blob, ct), + "blob_sha1": blob_hash, + } + if is_dominant: + meta["page_image"] = True + meta["page_image_source"] = "pptx" + blocks.append( + Block( + id=f"pptx-img-{slide_no}-{img_idx}", + page=slide_no, + type="image", + text="", + bbox=bbox, + meta=meta, + ) + ) + continue + + if getattr(shape, "has_text_frame", False): + txt = _norm_text(shape.text) + bbox = _shape_bbox(shape) + if not txt or txt == title_text: + continue + if title_text and txt.startswith(title_text): + txt = txt[len(title_text) :].lstrip("\n ::;;,,") + txt = _norm_text(txt) + if not txt: + continue + if re.fullmatch(r"\d+", txt): + continue + if flow_crop is not None and len(txt) <= 28: + continue + if txt and txt != title_text: + blk_idx += 1 + blocks.append( + Block( + id=f"pptx-{slide_no}-text-{blk_idx}", + page=slide_no, + type="paragraph", + text=txt, + bbox=bbox, + ) + ) + except Exception as exc: + context.warnings.append(f"pptx shape skipped: {exc}") + + context.extras["slides_count"] = len(prs.slides) + return blocks diff --git a/backend/edkb_system/skills/ocr.py b/backend/edkb_system/skills/ocr.py new file mode 100644 index 00000000..955d58c0 --- /dev/null +++ b/backend/edkb_system/skills/ocr.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +import base64 +import io +import re + +from edkb_system.contracts import Block, Context + + +def _decode_data_uri_image(data_uri: str): + m = re.match(r"^data:image/[^;]+;base64,(.+)$", data_uri or "", re.DOTALL) + if not m: + return None + try: + raw = base64.b64decode(m.group(1), validate=False) + except Exception: + return None + + try: + import numpy as np + from PIL import Image + + with Image.open(io.BytesIO(raw)) as im: + return np.array(im.convert("RGB")) + except Exception: + return None + + +def run( + input_data: list[Block], context: Context, min_confidence: float = 0.3 +) -> list[Block]: + blocks = input_data + try: + from rapidocr_onnxruntime import RapidOCR # type: ignore + except Exception: + context.warnings.append("RapidOCR unavailable; skip OCR") + return blocks + + engine = RapidOCR() + out: list[Block] = [] + for b in blocks: + out.append(b) + if b.type != "image": + continue + context.images += 1 + image_obj = b.meta.get("image") + if image_obj is None and b.meta and b.meta.get("data_uri"): + image_obj = _decode_data_uri_image(str(b.meta.get("data_uri"))) + if image_obj is None: + out.append( + Block( + id=f"ocr-{b.id}", + page=b.page, + type="ocr_text", + text="OCR_TEXT: <empty>", + bbox=b.bbox, + ) + ) + continue + + try: + result, _ = engine(image_obj) + lines = [] + for it in result or []: + if len(it) < 3: + continue + txt = str(it[1]).strip() + conf = float(it[2]) + if txt and conf >= min_confidence: + lines.append(txt) + if lines: + text = "OCR_TEXT:\n" + "\n".join(f"- {x}" for x in lines) + context.ocr_characters += sum(len(x) for x in lines) + else: + text = "OCR_TEXT: <empty>" + out.append( + Block( + id=f"ocr-{b.id}", + page=b.page, + type="ocr_text", + text=text, + bbox=b.bbox, + ) + ) + except Exception as exc: + context.warnings.append(f"OCR failed: {exc}") + out.append( + Block( + id=f"ocr-{b.id}", + page=b.page, + type="ocr_text", + text="OCR_TEXT: <empty>", + bbox=b.bbox, + ) + ) + + return out diff --git a/backend/edkb_system/skills/postcheck.py b/backend/edkb_system/skills/postcheck.py new file mode 100644 index 00000000..92a249d3 --- /dev/null +++ b/backend/edkb_system/skills/postcheck.py @@ -0,0 +1,192 @@ +from __future__ import annotations + +import json +import re +from pathlib import Path + +from edkb_system.contracts import Context + + +def _has_doc_meta(text: str) -> bool: + flat = " ".join(text.split()) + has_header = bool( + re.search(r"制定部门.+制/修订日期.+页码", flat) + or re.search(r"Created Dept\..+Date.+Page", flat) + ) + has_meta = bool( + re.search(r"文件编号.+文件级别.+版本", flat) + or re.search(r"Doc\.\s*No\..+File\s*Level.+Rev\.?", flat) + ) + return has_header or has_meta + + +def _expect_doc_meta(text: str) -> bool: + keys = ["文件编号", "文件级别", "制/修订日期", "制定部门", "页码"] + return any(k in text for k in keys) + + +def _expect_flow_artifacts(text: str) -> bool: + if "作业流程图" not in text: + return False + hints = ["序号", "流程说明", "责任", "相关记录"] + return sum(1 for h in hints if h in text) >= 2 + + +def _expect_related_forms_table(text: str) -> bool: + if "相关表单" not in text: + return False + return ("表单编号" in text) or bool(re.search(r"PB-\d{2,}", text)) + + +def _has_source_images(out_dir: Path) -> bool: + raw = out_dir / "01_raw_layout.json" + if not raw.exists(): + return False + try: + data = json.loads(raw.read_text(encoding="utf-8")) + if isinstance(data, list): + for b in data: + if isinstance(b, dict) and b.get("type") == "image": + return True + except Exception: + return False + return False + + +def _has_markdown_image_reference(text: str) -> bool: + for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text): + target = (m.group(1) or "").strip() + if target.startswith("data:image/"): + return True + if target.startswith("http://") or target.startswith("https://"): + return True + return False + + +def _has_remote_image_url(text: str) -> bool: + for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text): + target = (m.group(1) or "").strip() + if target.startswith("http://") or target.startswith("https://"): + return True + return False + + +def _expect_revision_table(text: str) -> bool: + if "文件修订履历" in text: + return True + hint = ["日期", "修订章节", "主要修订内容", "版本", "修改人"] + return sum(1 for h in hint if h in text) >= 4 + + +def _collect_issues(text: str) -> list[dict]: + issues: list[dict] = [] + lines = text.splitlines() + num_pat = re.compile(r"^\s*\d+(?:\.\d+){1,4}\s+") + + non_empty = [(i + 1, ln.strip()) for i, ln in enumerate(lines) if ln.strip()] + if len(non_empty) >= 2: + l1, s1 = non_empty[0] + l2, s2 = non_empty[1] + if "文件编号" in s1 and "文件编号" not in s2 and not s2.startswith("制定部门"): + if not re.match(r"^[一二三四五六七八九十]+、", s2): + issues.append( + { + "code": "title_below_meta", + "line": l1, + "text": f"meta before title: {s1[:80]}", + } + ) + + for i, ln in enumerate(lines, start=1): + s = ln.strip() + if not s: + continue + if s.startswith("|"): + continue + + if re.search(r"\d+\.\d+(?:\.\d+)?\s+.+\s+\d+\.\d+(?:\.\d+)?\s+", s): + issues.append( + {"code": "inline_numbered_sections", "line": i, "text": s[:180]} + ) + + if re.search(r"[七八]、参考文件\s+[七八]、相关表单", s): + issues.append({"code": "inline_section_titles", "line": i, "text": s[:180]}) + + for i in range(1, len(lines) - 1): + if lines[i].strip(): + continue + prev = lines[i - 1].strip() + nxt = lines[i + 1].strip() + if num_pat.match(prev) and num_pat.match(nxt): + issues.append( + { + "code": "blank_between_numbered_sections", + "line": i + 1, + "text": f"{prev[:70]} / {nxt[:70]}", + } + ) + + return issues + + +def run(input_data: dict, context: Context) -> dict: + out_dir = Path(input_data["out_dir"]) + clean_md = input_data.get("clean_md", "") + + checks = { + "has_doc_meta": _has_doc_meta(clean_md), + "has_revision_table": bool( + (re.search(r"\|\s*(?:日期|文件日期)\b", clean_md) is not None) + and re.search(r"\|\s*.*修订章节", clean_md) + and re.search(r"\|\s*版本\b", clean_md) + ), + "has_flow_table": "| 序号 | 流程说明 | 责任部门 | 相关记录 |" in clean_md, + "has_related_forms_table": bool( + re.search(r"\|\s*表单编号\s*\|", clean_md) + and re.search(r"\|\s*[-:]{3,}\s*\|", clean_md) + ), + "has_flow_file": (out_dir / "02_flow_procedure.md").exists(), + "has_embedded_images": _has_markdown_image_reference(clean_md), + "has_remote_image_urls": _has_remote_image_url(clean_md), + } + + flow_expected = _expect_flow_artifacts(clean_md) + expected = { + "has_doc_meta": _expect_doc_meta(clean_md), + "has_revision_table": _expect_revision_table(clean_md), + "has_flow_table": flow_expected, + "has_related_forms_table": _expect_related_forms_table(clean_md), + "has_flow_file": flow_expected, + "has_embedded_images": _has_source_images(out_dir), + } + + failed_required = [k for k, v in expected.items() if v and not checks.get(k, False)] + status = "pass" if not failed_required else "fail" + issues = _collect_issues(clean_md) + if expected["has_embedded_images"] and not checks["has_embedded_images"]: + issues.append( + { + "code": "image_not_embedded", + "line": 0, + "text": "source has image blocks but markdown has no image references", + } + ) + + if "data:image/" in clean_md: + issues.append( + { + "code": "legacy_base64_image", + "line": 0, + "text": "markdown still contains legacy data:image base64 payload", + } + ) + + return { + "status": status, + "checks": checks, + "expected": expected, + "failed_required": failed_required, + "issues": issues, + "issue_count": len(issues), + "warnings_count": len(context.warnings), + } diff --git a/backend/edkb_system/skills/quality_gate.py b/backend/edkb_system/skills/quality_gate.py new file mode 100644 index 00000000..627fae79 --- /dev/null +++ b/backend/edkb_system/skills/quality_gate.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +from edkb_system.contracts import Chunk, Context + + +def run(input_data: list[Chunk], context: Context) -> list[Chunk]: + chunks = input_data + if not chunks: + context.warnings.append("quality_gate: no chunks generated") + context.confidence = min(context.confidence, 0.5) + return chunks + + short_count = sum(1 for c in chunks if len(c.text.strip()) < 60) + if short_count: + context.warnings.append(f"quality_gate: {short_count} short chunks") + context.confidence = min(context.confidence, 0.8) + + unique_texts = len({c.text for c in chunks}) + if unique_texts < len(chunks): + context.warnings.append("quality_gate: duplicate chunks detected") + context.confidence = min(context.confidence, 0.75) + + return chunks diff --git a/backend/edkb_system/skills/table_linearize.py b/backend/edkb_system/skills/table_linearize.py new file mode 100644 index 00000000..307f12d5 --- /dev/null +++ b/backend/edkb_system/skills/table_linearize.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from edkb_system.contracts import Context + + +COND_KWS = ["条件", "判定", "if", "IF"] +ACT_KWS = ["处理", "动作", "措施", "结果", "输出"] +OWN_KWS = ["责任", "负责人", "部门", "岗位"] + + +def _find_col(headers: list[str], kws: list[str]) -> int | None: + for i, h in enumerate(headers): + s = (h or "").lower() + if any(k.lower() in s for k in kws): + return i + return None + + +def _to_table_md(headers: list[str], rows: list[list[str]]) -> str: + hs = [h or "-" for h in headers] + out = ["| " + " | ".join(hs) + " |", "| " + " | ".join(["---"] * len(hs)) + " |"] + for r in rows: + vals = [r[i] if i < len(r) else "" for i in range(len(hs))] + out.append("| " + " | ".join(vals) + " |") + return "\n".join(out) + + +def run(input_data: list[dict] | dict, context: Context) -> str: + tables = input_data if isinstance(input_data, list) else [input_data] + parts: list[str] = [] + + for t in tables: + headers = [str(x).strip() for x in t.get("headers", [])] + rows = [[str(c).strip() for c in row] for row in t.get("rows", [])] + parts.append(f"## Sheet: {t.get('sheet', 'Sheet1')}") + + cidx = _find_col(headers, COND_KWS) + aidx = _find_col(headers, ACT_KWS) + oidx = _find_col(headers, OWN_KWS) + if cidx is not None and aidx is not None: + for row in rows: + cond = row[cidx] if cidx < len(row) else "满足条件" + act = row[aidx] if aidx < len(row) else "执行处理" + owner = ( + row[oidx] if oidx is not None and oidx < len(row) else "相关责任方" + ) + parts.append( + f"- 当 {cond or '满足条件'} 时,{owner or '相关责任方'} 执行 {act or '执行处理'}。" + ) + else: + parts.append(_to_table_md(headers, rows)) + + parts.append("") + + return "\n".join(parts).strip() + "\n" diff --git a/backend/edkb_system/skills/word_bridge.py b/backend/edkb_system/skills/word_bridge.py new file mode 100644 index 00000000..13cc1396 --- /dev/null +++ b/backend/edkb_system/skills/word_bridge.py @@ -0,0 +1,249 @@ +from __future__ import annotations + +import os +import subprocess +import sys +import threading +import time +import ctypes +from pathlib import Path + + +def _list_winword_pids() -> set[int]: + if os.name != "nt": + return set() + try: + proc = subprocess.run( + ["tasklist", "/FO", "CSV", "/NH", "/FI", "IMAGENAME eq WINWORD.EXE"], + capture_output=True, + text=True, + check=False, + ) + except Exception: + return set() + + out: set[int] = set() + for line in (proc.stdout or "").splitlines(): + line = line.strip() + if not line or line.startswith("INFO:"): + continue + cols = [part.strip().strip('"') for part in line.split('","')] + if len(cols) < 2: + cols = [part.strip().strip('"') for part in line.split(",")] + if len(cols) < 2: + continue + try: + out.add(int(cols[1])) + except ValueError: + continue + return out + + +def _kill_winword_pids(pids: set[int]) -> None: + if os.name != "nt": + return + for pid in sorted(pids): + try: + subprocess.run( + ["taskkill", "/PID", str(pid), "/F"], + capture_output=True, + text=True, + check=False, + ) + except Exception: + continue + + +def _word_timeout_sec() -> int: + raw = str(os.environ.get("EDKB_WORD_TIMEOUT_SEC", "120")).strip() + try: + value = int(raw) + except ValueError: + value = 120 + return max(value, 10) + + +def _should_accept_word_dialog( + window_title: str, child_texts: list[str], button_texts: list[str] +) -> bool: + text_blob = "\n".join(x.strip().lower() for x in child_texts if x.strip()) + if not text_blob: + return False + + has_repair_prompt = any( + token in text_blob + for token in [ + "出现严重错误", + "是否仍要打开", + "serious error", + "do you still want to open", + ] + ) + if not has_repair_prompt: + return False + + return any( + text.strip().lower().startswith(("是", "yes")) or "&y" in text.lower() + for text in button_texts + ) + + +def _start_word_dialog_watcher() -> tuple[threading.Event, threading.Thread | None]: + stop_event = threading.Event() + if os.name != "nt": + return stop_event, None + + def _window_text(user32, hwnd: int) -> str: + length = user32.GetWindowTextLengthW(hwnd) + if length <= 0: + return "" + buf = ctypes.create_unicode_buffer(length + 1) + user32.GetWindowTextW(hwnd, buf, length + 1) + return buf.value + + def _class_name(user32, hwnd: int) -> str: + buf = ctypes.create_unicode_buffer(256) + user32.GetClassNameW(hwnd, buf, 255) + return buf.value + + def _click_yes_if_needed() -> None: + user32 = ctypes.windll.user32 + bm_click = 0x00F5 + vk_return = 0x0D + wm_keydown = 0x0100 + wm_keyup = 0x0101 + + while not stop_event.is_set(): + windows: list[int] = [] + + @ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + def enum_windows(hwnd, lparam): + windows.append(int(hwnd)) + return True + + user32.EnumWindows(enum_windows, 0) + for hwnd in windows: + title = _window_text(user32, hwnd) + cls = _class_name(user32, hwnd).lower() + if "Microsoft Word" not in title and cls != "#32770": + continue + + child_hwnds: list[int] = [] + + @ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + def enum_children(child_hwnd, lparam): + child_hwnds.append(int(child_hwnd)) + return True + + user32.EnumChildWindows(hwnd, enum_children, 0) + child_texts = [_window_text(user32, child) for child in child_hwnds] + button_hwnds = [ + child + for child in child_hwnds + if _class_name(user32, child).lower() == "button" + ] + button_texts = [_window_text(user32, child) for child in button_hwnds] + if not _should_accept_word_dialog(title, child_texts, button_texts): + continue + user32.SetForegroundWindow(hwnd) + for child, text in zip(button_hwnds, button_texts): + normalized = text.strip().lower() + if normalized.startswith(("是", "yes")) or "&y" in normalized: + user32.SendMessageW(child, bm_click, 0, 0) + break + else: + user32.PostMessageW(hwnd, wm_keydown, vk_return, 0) + user32.PostMessageW(hwnd, wm_keyup, vk_return, 0) + stop_event.wait(0.5) + + thread = threading.Thread(target=_click_yes_if_needed, daemon=True) + thread.start() + return stop_event, thread + + +def convert_with_word(path: Path, output: Path, file_format: int) -> Path: + timeout = _word_timeout_sec() + before_pids = _list_winword_pids() + cmd = [ + sys.executable, + "-m", + "edkb_system.skills.word_bridge", + str(path), + str(output), + str(file_format), + ] + try: + proc = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + except subprocess.TimeoutExpired as exc: + after_pids = _list_winword_pids() + _kill_winword_pids(after_pids - before_pids) + raise RuntimeError( + f"Word conversion timed out after {timeout}s: {path.name}" + ) from exc + + if proc.returncode != 0: + err = (proc.stderr or proc.stdout or "unknown error").strip() + raise RuntimeError(f"Word conversion failed: {err}") + + if not output.exists() or output.stat().st_size <= 0: + raise RuntimeError(f"Word conversion produced no output: {output}") + return output + + +def _child_main(argv: list[str]) -> int: + if len(argv) != 4: + print("usage: word_bridge <input> <output> <file_format>", file=sys.stderr) + return 2 + + src = Path(argv[1]).resolve() + out = Path(argv[2]).resolve() + file_format = int(argv[3]) + out.parent.mkdir(parents=True, exist_ok=True) + stop_event, watcher = _start_word_dialog_watcher() + + word = None + doc = None + try: + from win32com.client import DispatchEx + + word = DispatchEx("Word.Application") + word.Visible = False + word.DisplayAlerts = 0 + try: + word.Options.SaveNormalPrompt = False + except Exception: + pass + doc = word.Documents.Open( + FileName=str(src), + ReadOnly=True, + AddToRecentFiles=False, + ConfirmConversions=False, + NoEncodingDialog=True, + OpenAndRepair=True, + ) + doc.SaveAs(str(out), FileFormat=file_format) + finally: + stop_event.set() + if watcher is not None: + watcher.join(timeout=1) + if doc is not None: + try: + doc.Close(False) + except Exception: + pass + if word is not None: + try: + word.Quit() + except Exception: + pass + return 0 + + +if __name__ == "__main__": + raise SystemExit(_child_main(sys.argv)) diff --git a/backend/gunicorn_config.py b/backend/gunicorn_config.py index 945bc944..cc060c20 100644 --- a/backend/gunicorn_config.py +++ b/backend/gunicorn_config.py @@ -26,3 +26,7 @@ keepalive = 5 accesslog = "-" errorlog = "-" loglevel = "info" + +# 应用启动时会访问数据库加载持久化配置;预加载会让主进程先建立连接再 fork, +# 导致 worker 继承损坏的数据库连接。 +preload_app = False diff --git a/backend/migrations/versions/2a4b6c8d0e1f_add_kb_foundation_tables.py b/backend/migrations/versions/2a4b6c8d0e1f_add_kb_foundation_tables.py new file mode 100644 index 00000000..b215b33c --- /dev/null +++ b/backend/migrations/versions/2a4b6c8d0e1f_add_kb_foundation_tables.py @@ -0,0 +1,185 @@ +"""add kb foundation tables + +Revision ID: 2a4b6c8d0e1f +Revises: 1c2d3e4f5a6b +Create Date: 2026-05-08 23:10:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '2a4b6c8d0e1f' +down_revision = '1c2d3e4f5a6b' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'kb_groups', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=128), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('department_id', sa.Integer(), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=False, server_default=sa.text('true')), + sa.Column('dify_dataset_id', sa.String(length=128), nullable=True), + sa.Column('dify_dataset_name', sa.String(length=255), nullable=True), + sa.Column('created_by_id', sa.Integer(), nullable=True), + sa.Column('updated_by_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), + sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id']), + sa.ForeignKeyConstraint(['updated_by_id'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('department_id', 'name', name='uq_kb_groups_department_name'), + ) + op.create_index('ix_kb_groups_name', 'kb_groups', ['name']) + op.create_index('ix_kb_groups_department_id', 'kb_groups', ['department_id']) + op.create_index('ix_kb_groups_department_active', 'kb_groups', ['department_id', 'is_active']) + op.create_index('ix_kb_groups_dify_dataset_id', 'kb_groups', ['dify_dataset_id']) + + op.create_table( + 'kb_documents', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('group_id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(length=255), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('status', sa.String(length=32), nullable=False, server_default='draft'), + sa.Column('source_type', sa.String(length=32), nullable=True), + sa.Column('is_deleted', sa.Boolean(), nullable=False, server_default=sa.text('false')), + sa.Column('created_by_id', sa.Integer(), nullable=True), + sa.Column('updated_by_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), + sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id']), + sa.ForeignKeyConstraint(['group_id'], ['kb_groups.id']), + sa.ForeignKeyConstraint(['updated_by_id'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('group_id', 'title', name='uq_kb_documents_group_title'), + ) + op.create_index('ix_kb_documents_status', 'kb_documents', ['status']) + op.create_index('ix_kb_documents_is_deleted', 'kb_documents', ['is_deleted']) + op.create_index('ix_kb_documents_group_status', 'kb_documents', ['group_id', 'status']) + + op.create_table( + 'kb_document_versions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('document_id', sa.Integer(), nullable=False), + sa.Column('version_no', sa.Integer(), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='uploaded'), + sa.Column('is_current', sa.Boolean(), nullable=False, server_default=sa.text('true')), + sa.Column('source_file_name', sa.String(length=255), nullable=False), + sa.Column('source_file_path', sa.Text(), nullable=False), + sa.Column('source_file_ext', sa.String(length=32), nullable=True), + sa.Column('source_file_size', sa.Integer(), nullable=True), + sa.Column('cleaned_file_path', sa.Text(), nullable=True), + sa.Column('cleaned_preview_path', sa.Text(), nullable=True), + sa.Column('sha256', sa.String(length=64), nullable=True), + sa.Column('word_count', sa.Integer(), nullable=False, server_default='0'), + sa.Column('error_message', sa.Text(), nullable=True), + sa.Column('warnings_json', sa.JSON(), nullable=True), + sa.Column('uploaded_by_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), + sa.Column('converted_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['document_id'], ['kb_documents.id']), + sa.ForeignKeyConstraint(['uploaded_by_id'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('document_id', 'version_no', name='uq_kb_document_versions_doc_version'), + ) + op.create_index('ix_kb_document_versions_status', 'kb_document_versions', ['status']) + op.create_index('ix_kb_document_versions_is_current', 'kb_document_versions', ['is_current']) + op.create_index('ix_kb_document_versions_doc_status', 'kb_document_versions', ['document_id', 'status']) + op.create_index('ix_kb_document_versions_sha256', 'kb_document_versions', ['sha256']) + + op.create_table( + 'kb_jobs', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('job_type', sa.String(length=32), nullable=False), + sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'), + sa.Column('queue_job_id', sa.String(length=64), nullable=True), + sa.Column('group_id', sa.Integer(), nullable=True), + sa.Column('document_id', sa.Integer(), nullable=True), + sa.Column('document_version_id', sa.Integer(), nullable=True), + sa.Column('progress', sa.Integer(), nullable=False, server_default='0'), + sa.Column('message', sa.Text(), nullable=True), + sa.Column('error_message', sa.Text(), nullable=True), + sa.Column('payload_json', sa.JSON(), nullable=True), + sa.Column('result_json', sa.JSON(), nullable=True), + sa.Column('created_by_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id']), + sa.ForeignKeyConstraint(['document_id'], ['kb_documents.id']), + sa.ForeignKeyConstraint(['document_version_id'], ['kb_document_versions.id']), + sa.ForeignKeyConstraint(['group_id'], ['kb_groups.id']), + sa.PrimaryKeyConstraint('id'), + ) + op.create_index('ix_kb_jobs_status', 'kb_jobs', ['status']) + op.create_index('ix_kb_jobs_job_type', 'kb_jobs', ['job_type']) + op.create_index('ix_kb_jobs_document_version_id', 'kb_jobs', ['document_version_id']) + op.create_index('ix_kb_jobs_status_created', 'kb_jobs', ['status', 'created_at']) + + op.create_table( + 'kb_dify_sync_records', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('group_id', sa.Integer(), nullable=True), + sa.Column('document_id', sa.Integer(), nullable=True), + sa.Column('document_version_id', sa.Integer(), nullable=False), + sa.Column('dataset_id', sa.String(length=128), nullable=False), + sa.Column('dataset_name', sa.String(length=255), nullable=True), + sa.Column('remote_document_id', sa.String(length=128), nullable=False), + sa.Column('remote_document_name', sa.String(length=255), nullable=True), + sa.Column('status', sa.String(length=32), nullable=False, server_default='pending'), + sa.Column('sync_hash', sa.String(length=64), nullable=True), + sa.Column('error_message', sa.Text(), nullable=True), + sa.Column('synced_by_id', sa.Integer(), nullable=True), + sa.Column('synced_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), + sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), + sa.ForeignKeyConstraint(['document_id'], ['kb_documents.id']), + sa.ForeignKeyConstraint(['document_version_id'], ['kb_document_versions.id']), + sa.ForeignKeyConstraint(['group_id'], ['kb_groups.id']), + sa.ForeignKeyConstraint(['synced_by_id'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint( + 'document_version_id', + 'remote_document_id', + name='uq_kb_dify_sync_records_version_remote', + ), + ) + op.create_index('ix_kb_dify_sync_records_document_version_id', 'kb_dify_sync_records', ['document_version_id']) + op.create_index('ix_kb_dify_sync_records_dataset_id', 'kb_dify_sync_records', ['dataset_id']) + op.create_index('ix_kb_dify_sync_records_status', 'kb_dify_sync_records', ['status']) + + +def downgrade(): + op.drop_index('ix_kb_dify_sync_records_status', table_name='kb_dify_sync_records') + op.drop_index('ix_kb_dify_sync_records_dataset_id', table_name='kb_dify_sync_records') + op.drop_index('ix_kb_dify_sync_records_document_version_id', table_name='kb_dify_sync_records') + op.drop_table('kb_dify_sync_records') + + op.drop_index('ix_kb_jobs_status_created', table_name='kb_jobs') + op.drop_index('ix_kb_jobs_document_version_id', table_name='kb_jobs') + op.drop_index('ix_kb_jobs_job_type', table_name='kb_jobs') + op.drop_index('ix_kb_jobs_status', table_name='kb_jobs') + op.drop_table('kb_jobs') + + op.drop_index('ix_kb_document_versions_sha256', table_name='kb_document_versions') + op.drop_index('ix_kb_document_versions_doc_status', table_name='kb_document_versions') + op.drop_index('ix_kb_document_versions_is_current', table_name='kb_document_versions') + op.drop_index('ix_kb_document_versions_status', table_name='kb_document_versions') + op.drop_table('kb_document_versions') + + op.drop_index('ix_kb_documents_group_status', table_name='kb_documents') + op.drop_index('ix_kb_documents_is_deleted', table_name='kb_documents') + op.drop_index('ix_kb_documents_status', table_name='kb_documents') + op.drop_table('kb_documents') + + op.drop_index('ix_kb_groups_dify_dataset_id', table_name='kb_groups') + op.drop_index('ix_kb_groups_department_active', table_name='kb_groups') + op.drop_index('ix_kb_groups_department_id', table_name='kb_groups') + op.drop_index('ix_kb_groups_name', table_name='kb_groups') + op.drop_table('kb_groups') diff --git a/backend/requirements.txt b/backend/requirements.txt index 8dbc32fc..9553425c 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -16,4 +16,20 @@ pycryptodome PyJWT cryptography oracledb +jaydebeapi +JPype1 pywin32; sys_platform == "win32" + +# File Parsing & edkb_system dependencies from xinxin2 +networkx==3.5 +python-docx==1.2.0 +rapidocr-onnxruntime==1.4.4 +opencv-python-headless +pillow==11.3.0 +numpy==2.3.3 +pypdf==6.1.0 +pypdfium2==5.0.0 +python-pptx==1.0.2 +beautifulsoup4==4.14.2 +lxml==6.0.2 +typer==0.17.4 diff --git a/backend/tests/test_kb_excel_cleaning.py b/backend/tests/test_kb_excel_cleaning.py new file mode 100644 index 00000000..068a6078 --- /dev/null +++ b/backend/tests/test_kb_excel_cleaning.py @@ -0,0 +1,44 @@ +from pathlib import Path +from types import SimpleNamespace + +from openpyxl import Workbook + +from app.services.knowledge_cleaning.edkb_adapter import build_clean_result +from app.services.knowledge_cleaning.tasks import _normalized_source_filename + + +def test_build_clean_result_generates_markdown_for_xlsx(tmp_path): + workbook = Workbook() + sheet = workbook.active + sheet.title = 'Sheet1' + sheet.append(['部门', '指标']) + sheet.append(['供应链', '能耗']) + + source_path = tmp_path / 'sample.xlsx' + workbook.save(source_path) + + target_dir = tmp_path / 'output' + result = build_clean_result(source_path, target_dir) + + cleaned_path = Path(result['cleaned_file_path']) + assert result['mode'] == 'edkb_system' + assert cleaned_path == target_dir / 'document.md' + assert cleaned_path.exists() + assert result['cleaned_preview_path'] == str(cleaned_path) + + content = cleaned_path.read_text(encoding='utf-8') + assert '供应链' in content + assert '能耗' in content + + +def test_normalized_source_filename_infers_xlsx_extension(tmp_path): + workbook = Workbook() + workbook.active.append(['部门', '指标']) + source_with_ext = tmp_path / 'sample.xlsx' + workbook.save(source_with_ext) + + source_without_ext = tmp_path / 'xlsx' + source_with_ext.rename(source_without_ext) + + version = SimpleNamespace(source_file_name='xlsx', source_file_ext=None) + assert _normalized_source_filename(version, source_without_ext) == 'xlsx.xlsx' diff --git a/backend/tests/test_kb_migration_flow.py b/backend/tests/test_kb_migration_flow.py new file mode 100644 index 00000000..5ab5ede9 --- /dev/null +++ b/backend/tests/test_kb_migration_flow.py @@ -0,0 +1,400 @@ +import io +from pathlib import Path + +from app import db +from app.auth_jwt import issue_local_access_token +from app.models import KbDocument, KbDifySyncRecord, User +from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module +from app.services.knowledge_cleaning import tasks as kb_tasks_module + + +def _configure_app(app, tmp_path): + app.config.update( + SECRET_KEY='test-secret-key-with-sufficient-length-123456', + KB_STORAGE_ROOT=str(tmp_path / 'kb-storage'), + WECOM_PUBLIC_BASE_URL='https://ai.example.com', + INTEGRATION_API_KEY='test-integration-key', + INTEGRATION_API_MODE='local', + ) + + +def _ensure_user(username: str, role: str) -> User: + user = db.session.query(User).filter_by(username=username).first() + if user: + return user + user = User( + username=username, + email=f'{username}@example.com', + role=role, + status='active', + ) + user.set_password('password123') + db.session.add(user) + db.session.commit() + return user + + +def _auth_headers_for(app, username: str) -> dict[str, str]: + with app.app_context(): + user = db.session.query(User).filter_by(username=username).first() + token = issue_local_access_token(user) + return { + 'Authorization': f'Bearer {token}', + } + + +def _create_group(client, headers: dict[str, str], *, name: str) -> int: + response = client.post( + '/api/kb/groups', + json={'name': name, 'description': 'test group'}, + headers=headers, + ) + assert response.status_code == 201, response.get_json() + return response.get_json()['id'] + + +def _create_document(client, headers: dict[str, str], group_id: int, *, title: str) -> int: + response = client.post( + f'/api/kb/groups/{group_id}/files', + json={'title': title, 'description': 'test doc'}, + headers=headers, + ) + assert response.status_code == 201, response.get_json() + return response.get_json()['id'] + + +def _upload_document(client, headers: dict[str, str], document_id: int, *, content: str, filename: str): + response = client.post( + f'/api/kb/documents/{document_id}/upload', + headers=headers, + data={'file': (io.BytesIO(content.encode('utf-8')), filename)}, + content_type='multipart/form-data', + ) + assert response.status_code == 201, response.get_json() + return response.get_json() + + +def test_kb_document_upload_and_sync_flow(app, client, monkeypatch, tmp_path): + _configure_app(app, tmp_path) + + with app.app_context(): + _ensure_user('admin', 'admin') + + admin_headers = _auth_headers_for(app, 'admin') + + group_id = _create_group(client, admin_headers, name='知识库测试分组') + document_id = _create_document(client, admin_headers, group_id, title='员工手册') + + version_payload = _upload_document( + client, + admin_headers, + document_id, + content='第一行\n第二行\n第三行', + filename='employee-handbook.txt', + ) + assert version_payload['version_no'] == 1 + assert version_payload['status'] == 'cleaned' + assert version_payload['source_file_name'] == 'employee-handbook.txt' + + groups_response = client.get('/api/kb/groups', headers=admin_headers) + assert groups_response.status_code == 200 + groups_payload = groups_response.get_json() + assert groups_payload[0]['document_count'] == 1 + + documents_response = client.get(f'/api/kb/groups/{group_id}/files', headers=admin_headers) + assert documents_response.status_code == 200 + documents_payload = documents_response.get_json() + assert len(documents_payload) == 1 + assert documents_payload[0]['latest_version']['status'] == 'cleaned' + + monkeypatch.setattr( + dify_sync_module.KbDifySyncService, + 'ensure_dataset', + lambda self, group: ('ds_test_001', 'Test Dataset'), + ) + monkeypatch.setattr( + dify_sync_module.KbDifySyncService, + 'create_document_by_text', + lambda self, dataset_id, name, text: {'document': {'id': 'doc_test_001', 'name': name}}, + ) + + sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers) + assert sync_response.status_code == 200, sync_response.get_json() + sync_job_payload = sync_response.get_json() + assert sync_job_payload['job_type'] == 'sync_dify' + assert sync_job_payload['status'] == 'success' + + sync_records_response = client.get(f'/api/kb/documents/{document_id}/sync-records', headers=admin_headers) + assert sync_records_response.status_code == 200 + sync_records_payload = sync_records_response.get_json() + assert len(sync_records_payload) == 1 + assert sync_records_payload[0]['dataset_id'] == 'ds_test_001' + assert sync_records_payload[0]['remote_document_id'] == 'doc_test_001' + + +def test_integration_api_resolves_synced_document(app, client, monkeypatch, tmp_path): + _configure_app(app, tmp_path) + + with app.app_context(): + _ensure_user('admin', 'admin') + + admin_headers = _auth_headers_for(app, 'admin') + integration_headers = {'X-Integration-Key': app.config['INTEGRATION_API_KEY']} + + group_id = _create_group(client, admin_headers, name='集成测试分组') + document_id = _create_document(client, admin_headers, group_id, title='集成文件') + _upload_document( + client, + admin_headers, + document_id, + content='integration file content', + filename='integration-source.txt', + ) + + monkeypatch.setattr( + dify_sync_module.KbDifySyncService, + 'ensure_dataset', + lambda self, group: ('ds_integration_001', 'Integration Dataset'), + ) + monkeypatch.setattr( + dify_sync_module.KbDifySyncService, + 'create_document_by_text', + lambda self, dataset_id, name, text: {'document': {'id': 'doc_integration_001', 'name': name}}, + ) + + sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers) + assert sync_response.status_code == 200, sync_response.get_json() + + dify_file_response = client.get( + '/api/integration/dify-file', + headers=integration_headers, + query_string={ + 'dataset_id': 'ds_integration_001', + 'remote_document_id': 'doc_integration_001', + }, + ) + assert dify_file_response.status_code == 200 + dify_file_payload = dify_file_response.get_json() + assert dify_file_payload['document_id'] == document_id + assert dify_file_payload['source_filename'] == 'integration-source.txt' + assert dify_file_payload['source_download_url'].endswith( + f'/api/integration/files/{document_id}/download?kind=source' + ) + + resolve_response = client.post( + '/api/integration/dify-files/resolve', + headers=integration_headers, + json={'items': [{'dataset_id': 'ds_integration_001', 'remote_document_id': 'doc_integration_001'}]}, + ) + assert resolve_response.status_code == 200 + resolve_payload = resolve_response.get_json()['data'] + assert len(resolve_payload) == 1 + assert resolve_payload[0]['found'] is True + assert resolve_payload[0]['document']['document_id'] == document_id + + download_response = client.get( + f'/api/integration/files/{document_id}/download', + headers=integration_headers, + query_string={'kind': 'source'}, + ) + assert download_response.status_code == 200 + assert download_response.data == b'integration file content' + + with app.app_context(): + document = db.session.get(KbDocument, document_id) + assert document is not None + assert db.session.query(KbDifySyncRecord).filter_by(document_id=document_id).count() == 1 + + +def test_sync_recreates_missing_remote_document_for_same_hash(app, client, monkeypatch, tmp_path): + _configure_app(app, tmp_path) + + with app.app_context(): + _ensure_user('admin', 'admin') + + admin_headers = _auth_headers_for(app, 'admin') + + group_id = _create_group(client, admin_headers, name='同步补偿分组') + document_id = _create_document(client, admin_headers, group_id, title='同步补偿文档') + _upload_document( + client, + admin_headers, + document_id, + content='same content for repeated sync', + filename='sync-recreate.txt', + ) + + monkeypatch.setattr( + dify_sync_module.KbDifySyncService, + 'ensure_dataset', + lambda self, group: ('ds_recreate_001', 'Recreate Dataset'), + ) + monkeypatch.setattr( + dify_sync_module.KbDifySyncService, + 'create_document_by_text', + lambda self, dataset_id, name, text: {'document': {'id': 'doc_old_001', 'name': name}}, + ) + + first_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers) + assert first_sync_response.status_code == 200, first_sync_response.get_json() + + def _missing_remote_document(self, *, dataset_id: str, document_id: str): + raise dify_sync_module.KbDifySyncError( + 'Dify API GET /datasets/ds_recreate_001/documents/doc_old_001 failed: ' + '404 {"code":"not_found","message":"Document not found."}' + ) + + monkeypatch.setattr( + dify_sync_module.KbDifySyncService, + 'get_document', + _missing_remote_document, + ) + monkeypatch.setattr( + dify_sync_module.KbDifySyncService, + 'create_document_by_text', + lambda self, dataset_id, name, text: {'document': {'id': 'doc_new_001', 'name': name}}, + ) + + second_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers) + assert second_sync_response.status_code == 200, second_sync_response.get_json() + + with app.app_context(): + records = ( + db.session.query(KbDifySyncRecord) + .filter_by(document_id=document_id) + .order_by(KbDifySyncRecord.id.asc()) + .all() + ) + assert len(records) == 2 + assert records[0].remote_document_id == 'doc_old_001' + assert records[1].remote_document_id == 'doc_new_001' + assert records[1].status == 'synced' + + +def test_document_markdown_can_be_viewed_and_saved(app, client, tmp_path): + _configure_app(app, tmp_path) + + with app.app_context(): + _ensure_user('admin', 'admin') + + admin_headers = _auth_headers_for(app, 'admin') + group_id = _create_group(client, admin_headers, name='Markdown 编辑分组') + document_id = _create_document(client, admin_headers, group_id, title='Markdown 编辑文档') + + _upload_document( + client, + admin_headers, + document_id, + content='第一行\n第二行\n第三行', + filename='editable.txt', + ) + + read_response = client.get(f'/api/kb/documents/{document_id}/markdown', headers=admin_headers) + assert read_response.status_code == 200, read_response.get_json() + read_payload = read_response.get_json() + assert read_payload['kind'] == 'markdown' + assert '第二行' in read_payload['content'] + + updated_content = '# 手工修订\n\n这是一段修改后的 Markdown。' + save_response = client.patch( + f'/api/kb/documents/{document_id}/markdown', + headers=admin_headers, + json={'content': updated_content}, + ) + assert save_response.status_code == 200, save_response.get_json() + save_payload = save_response.get_json() + assert save_payload['content'] == updated_content + assert save_payload['version']['cleaned_file_path'].endswith('document.md') + + with app.app_context(): + document = db.session.get(KbDocument, document_id) + version = next(item for item in document.versions if item.is_current) + markdown_path = Path(version.cleaned_file_path) + assert markdown_path.exists() + assert markdown_path.read_text(encoding='utf-8') == updated_content + + +def test_document_markdown_save_upgrades_preview_to_markdown(app, client, monkeypatch, tmp_path): + _configure_app(app, tmp_path) + + with app.app_context(): + _ensure_user('admin', 'admin') + + admin_headers = _auth_headers_for(app, 'admin') + group_id = _create_group(client, admin_headers, name='Preview 编辑分组') + document_id = _create_document(client, admin_headers, group_id, title='Preview 编辑文档') + + def _raise_build_clean_result(source_path, target_dir): + raise RuntimeError('forced preview fallback') + + monkeypatch.setattr(kb_tasks_module, 'build_clean_result', _raise_build_clean_result) + + _upload_document( + client, + admin_headers, + document_id, + content='原始文本内容', + filename='preview-source.txt', + ) + + read_response = client.get(f'/api/kb/documents/{document_id}/markdown', headers=admin_headers) + assert read_response.status_code == 200, read_response.get_json() + read_payload = read_response.get_json() + assert read_payload['kind'] == 'preview' + assert 'forced preview fallback' in read_payload['content'] + + updated_content = '# 兜底转正\n\n预览文件已改为正式 Markdown。' + save_response = client.patch( + f'/api/kb/documents/{document_id}/markdown', + headers=admin_headers, + json={'content': updated_content}, + ) + assert save_response.status_code == 200, save_response.get_json() + save_payload = save_response.get_json() + assert save_payload['kind'] == 'markdown' + + with app.app_context(): + document = db.session.get(KbDocument, document_id) + version = next(item for item in document.versions if item.is_current) + assert version.cleaned_file_path is not None + assert version.cleaned_file_path.endswith('document.md') + assert version.cleaned_preview_path == version.cleaned_file_path + markdown_path = Path(version.cleaned_file_path) + assert markdown_path.exists() + assert markdown_path.read_text(encoding='utf-8') == updated_content + + +def test_upload_preserves_excel_extension_for_non_ascii_filename(app, client, monkeypatch, tmp_path): + _configure_app(app, tmp_path) + + with app.app_context(): + _ensure_user('admin', 'admin') + + admin_headers = _auth_headers_for(app, 'admin') + group_id = _create_group(client, admin_headers, name='中文文件名分组') + document_id = _create_document(client, admin_headers, group_id, title='中文 Excel 文档') + captured = {} + + def _fake_build_clean_result(source_path, target_dir): + captured['source_name'] = source_path.name + cleaned_path = target_dir / 'document.md' + cleaned_path.write_text('# ok', encoding='utf-8') + return { + 'mode': 'edkb_system', + 'cleaned_file_path': str(cleaned_path), + 'cleaned_preview_path': str(cleaned_path), + 'word_count': 1, + } + + monkeypatch.setattr(kb_tasks_module, 'build_clean_result', _fake_build_clean_result) + + version_payload = _upload_document( + client, + admin_headers, + document_id, + content='fake excel bytes', + filename='能源管理体系文件清单.xlsx', + ) + + assert version_payload['source_file_name'].endswith('.xlsx') + assert captured['source_name'].endswith('.xlsx') diff --git a/backend/worker_kb.py b/backend/worker_kb.py new file mode 100644 index 00000000..a33d28ff --- /dev/null +++ b/backend/worker_kb.py @@ -0,0 +1,47 @@ +""" +backend/worker_kb.py +文件用途:知识库最小 worker 入口 +""" +from __future__ import annotations + +import os +import time + +from app import create_app +from app.services.knowledge_cleaning.queue_service import process_next_clean_job + + +def _resolve_config_name() -> str: + """Keep the worker aligned with container/runtime environment selection.""" + explicit = os.getenv('APP_CONFIG') + if explicit: + return explicit.strip().lower() + + flask_env = os.getenv('FLASK_ENV', 'production').strip().lower() + mapping = { + 'dev': 'development', + 'development': 'development', + 'test': 'testing', + 'testing': 'testing', + 'prod': 'production', + 'production': 'production', + } + return mapping.get(flask_env, 'production') + + +def main(): + app = create_app(_resolve_config_name()) + poll_seconds = float(app.config.get('KB_WORKER_POLL_SECONDS', 2)) + + with app.app_context(): + print(f'[kb-worker] started, poll_seconds={poll_seconds}') + while True: + processed, message = process_next_clean_job() + if not processed: + time.sleep(poll_seconds) + continue + print(f'[kb-worker] processed job: {message}') + + +if __name__ == '__main__': + main() diff --git a/docker-compose.yml b/docker-compose.yml index 7a6318f8..72db0c7d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,4 +1,19 @@ services: + # ============================================================================== + # kb-redis: 知识库任务/后续异步能力预留的 Redis 服务 + # ============================================================================== + kb-redis: + image: ${KB_REDIS_IMAGE:-redis:7-alpine} + container_name: hxops-kb-redis + restart: always + profiles: + - kb-redis + command: ["redis-server", "--appendonly", "yes"] + volumes: + - hxops_redis_data:/data + networks: + - ai-platform + # ============================================================================== # hxops-backend: Flask 后端服务 (端口: 5000) # ============================================================================== @@ -7,6 +22,10 @@ services: build: context: . dockerfile: backend/Dockerfile + args: + PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim} + PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple} + PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-} container_name: hxops-backend restart: always # 与 scripts/deploy_compose.sh 使用的 .env.<ENV_NAME> 对齐(通过 COMPOSE_ENV_BASENAME) @@ -20,6 +39,11 @@ services: - ORACLE_CLIENT_LIB_DIR=${ORACLE_CLIENT_LIB_DIR:-/app/oracle_client} - ORACLE_HOME=/app/oracle_client/instantclient_19_31 - LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client + - REDIS_URL: ${REDIS_URL:-redis://kb-redis:6379/0} + - KB_STORAGE_ROOT: ${KB_STORAGE_ROOT:-/app/data/kb} + - KB_TASK_EXECUTION_MODE: ${KB_TASK_EXECUTION_MODE:-worker} + - KB_WORKER_POLL_SECONDS: ${KB_WORKER_POLL_SECONDS:-2} + # 允许容器访问宿主机服务 (如数据库) extra_hosts: - "host.docker.internal:host-gateway" @@ -32,7 +56,43 @@ services: # 把它当作目录挂载,因此先确保宿主机上存在该文件再启动。 volumes: - ./backend/.env:/app/.env - - ./oracle_client:/app/oracle_client:ro + - hxops_runtime_data:/app/data + networks: + - ai-platform + + # ============================================================================== + # hxops-kb-worker: 知识库清洗/同步最小 worker + # ============================================================================== + hxops-kb-worker: + image: ${BACKEND_IMAGE:-hxops-backend:local} + build: + context: ./backend + dockerfile: Dockerfile + args: + PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim} + PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple} + PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-} + container_name: hxops-kb-worker + restart: always + command: ["python", "worker_kb.py"] + depends_on: + - hxops-backend + env_file: + - ./backend/.env + environment: + DATABASE_URL: + SECRET_KEY: + FLASK_APP: ${FLASK_APP:-run.py} + FLASK_ENV: ${FLASK_ENV:-production} + REDIS_URL: ${REDIS_URL:-redis://kb-redis:6379/0} + KB_STORAGE_ROOT: ${KB_STORAGE_ROOT:-/app/data/kb} + KB_TASK_EXECUTION_MODE: ${KB_TASK_EXECUTION_MODE:-worker} + KB_WORKER_POLL_SECONDS: ${KB_WORKER_POLL_SECONDS:-2} + extra_hosts: + - "host.docker.internal:host-gateway" + volumes: + - ./backend/.env:/app/.env + - hxops_runtime_data:/app/data networks: - ai-platform @@ -44,6 +104,9 @@ services: build: context: ./frontend dockerfile: Dockerfile + args: + NODE_BASE_IMAGE: ${NODE_BASE_IMAGE:-node:22-alpine} + NGINX_BASE_IMAGE: ${NGINX_BASE_IMAGE:-nginx:alpine} container_name: hxops-frontend restart: always depends_on: @@ -62,3 +125,6 @@ networks: name: ai-platform driver: bridge +volumes: + hxops_runtime_data: + hxops_redis_data: diff --git a/docker-compose.yml.orig b/docker-compose.yml.orig new file mode 100644 index 00000000..72db0c7d --- /dev/null +++ b/docker-compose.yml.orig @@ -0,0 +1,130 @@ +services: + # ============================================================================== + # kb-redis: 知识库任务/后续异步能力预留的 Redis 服务 + # ============================================================================== + kb-redis: + image: ${KB_REDIS_IMAGE:-redis:7-alpine} + container_name: hxops-kb-redis + restart: always + profiles: + - kb-redis + command: ["redis-server", "--appendonly", "yes"] + volumes: + - hxops_redis_data:/data + networks: + - ai-platform + + # ============================================================================== + # hxops-backend: Flask 后端服务 (端口: 5000) + # ============================================================================== + hxops-backend: + image: ${BACKEND_IMAGE:-hxops-backend:local} + build: + context: . + dockerfile: backend/Dockerfile + args: + PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim} + PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple} + PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-} + container_name: hxops-backend + restart: always + # 与 scripts/deploy_compose.sh 使用的 .env.<ENV_NAME> 对齐(通过 COMPOSE_ENV_BASENAME) + env_file: + - ${COMPOSE_ENV_BASENAME:-.env.dev} + environment: + # 数据库连接 (在环境变量中配置) + - DATABASE_URL=${DATABASE_URL} + - FLASK_APP=${FLASK_APP:-run.py} + - FLASK_ENV=${FLASK_ENV:-production} + - ORACLE_CLIENT_LIB_DIR=${ORACLE_CLIENT_LIB_DIR:-/app/oracle_client} + - ORACLE_HOME=/app/oracle_client/instantclient_19_31 + - LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client + - REDIS_URL: ${REDIS_URL:-redis://kb-redis:6379/0} + - KB_STORAGE_ROOT: ${KB_STORAGE_ROOT:-/app/data/kb} + - KB_TASK_EXECUTION_MODE: ${KB_TASK_EXECUTION_MODE:-worker} + - KB_WORKER_POLL_SECONDS: ${KB_WORKER_POLL_SECONDS:-2} + + # 允许容器访问宿主机服务 (如数据库) + extra_hosts: + - "host.docker.internal:host-gateway" + # 如果需要在宿主机调试,可暴露端口;生产环境建议只在网络内暴露 + ports: + - "5052:5052" + # 持久化运行时可写文件: + # - backend/.env 用于保存管理员后台修改的企业微信等配置(与数据库双写, + # 防止容器重建后从镜像基线读取丢失修改)。文件不存在时 docker 会自动 + # 把它当作目录挂载,因此先确保宿主机上存在该文件再启动。 + volumes: + - ./backend/.env:/app/.env + - hxops_runtime_data:/app/data + networks: + - ai-platform + + # ============================================================================== + # hxops-kb-worker: 知识库清洗/同步最小 worker + # ============================================================================== + hxops-kb-worker: + image: ${BACKEND_IMAGE:-hxops-backend:local} + build: + context: ./backend + dockerfile: Dockerfile + args: + PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim} + PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple} + PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-} + container_name: hxops-kb-worker + restart: always + command: ["python", "worker_kb.py"] + depends_on: + - hxops-backend + env_file: + - ./backend/.env + environment: + DATABASE_URL: + SECRET_KEY: + FLASK_APP: ${FLASK_APP:-run.py} + FLASK_ENV: ${FLASK_ENV:-production} + REDIS_URL: ${REDIS_URL:-redis://kb-redis:6379/0} + KB_STORAGE_ROOT: ${KB_STORAGE_ROOT:-/app/data/kb} + KB_TASK_EXECUTION_MODE: ${KB_TASK_EXECUTION_MODE:-worker} + KB_WORKER_POLL_SECONDS: ${KB_WORKER_POLL_SECONDS:-2} + extra_hosts: + - "host.docker.internal:host-gateway" + volumes: + - ./backend/.env:/app/.env + - hxops_runtime_data:/app/data + networks: + - ai-platform + + # ============================================================================== + # hxops-frontend: Vue 前端静态资源 + Nginx 反向代理 (端口: 80) + # ============================================================================== + hxops-frontend: + image: ${FRONTEND_IMAGE:-hxops-frontend:local} + build: + context: ./frontend + dockerfile: Dockerfile + args: + NODE_BASE_IMAGE: ${NODE_BASE_IMAGE:-node:22-alpine} + NGINX_BASE_IMAGE: ${NGINX_BASE_IMAGE:-nginx:alpine} + container_name: hxops-frontend + restart: always + depends_on: + - hxops-backend + # 前端容器暴露 80 端口,映射到宿主机 8890 (或其他端口供 nginx-gateway 访问) + ports: + - "8890:80" + networks: + - ai-platform + +# ============================================================================== +# 网络配置 +# ============================================================================== +networks: + ai-platform: + name: ai-platform + driver: bridge + +volumes: + hxops_runtime_data: + hxops_redis_data: diff --git a/docker-compose_BASE_79870.yml b/docker-compose_BASE_79870.yml new file mode 100644 index 00000000..a3ca05b0 --- /dev/null +++ b/docker-compose_BASE_79870.yml @@ -0,0 +1,56 @@ +services: + # ============================================================================== + # hxops-backend: Flask 后端服务 (端口: 5000) + # ============================================================================== + hxops-backend: + image: ${BACKEND_IMAGE:-hxops-backend:local} + build: + context: ./backend + dockerfile: Dockerfile + container_name: hxops-backend + restart: always + environment: + # 数据库连接 (在环境变量中配置) + - DATABASE_URL=${DATABASE_URL} + - FLASK_APP=${FLASK_APP:-run.py} + - FLASK_ENV=${FLASK_ENV:-production} + # 允许容器访问宿主机服务 (如数据库) + extra_hosts: + - "host.docker.internal:host-gateway" + # 如果需要在宿主机调试,可暴露端口;生产环境建议只在网络内暴露 + ports: + - "5002:5002" + # 持久化运行时可写文件: + # - backend/.env 用于保存管理员后台修改的企业微信等配置(与数据库双写, + # 防止容器重建后从镜像基线读取丢失修改)。文件不存在时 docker 会自动 + # 把它当作目录挂载,因此先确保宿主机上存在该文件再启动。 + volumes: + - ./backend/.env:/app/.env + networks: + - ai-platform + + # ============================================================================== + # hxops-frontend: Vue 前端静态资源 + Nginx 反向代理 (端口: 80) + # ============================================================================== + hxops-frontend: + image: ${FRONTEND_IMAGE:-hxops-frontend:local} + build: + context: ./frontend + dockerfile: Dockerfile + container_name: hxops-frontend + restart: always + depends_on: + - hxops-backend + # 前端容器暴露 80 端口,映射到宿主机 8890 (或其他端口供 nginx-gateway 访问) + ports: + - "8890:80" + networks: + - ai-platform + +# ============================================================================== +# 网络配置 +# ============================================================================== +networks: + ai-platform: + name: ai-platform + driver: bridge diff --git a/docker-compose_LOCAL_79870.yml b/docker-compose_LOCAL_79870.yml new file mode 100644 index 00000000..7a6318f8 --- /dev/null +++ b/docker-compose_LOCAL_79870.yml @@ -0,0 +1,64 @@ +services: + # ============================================================================== + # hxops-backend: Flask 后端服务 (端口: 5000) + # ============================================================================== + hxops-backend: + image: ${BACKEND_IMAGE:-hxops-backend:local} + build: + context: . + dockerfile: backend/Dockerfile + container_name: hxops-backend + restart: always + # 与 scripts/deploy_compose.sh 使用的 .env.<ENV_NAME> 对齐(通过 COMPOSE_ENV_BASENAME) + env_file: + - ${COMPOSE_ENV_BASENAME:-.env.dev} + environment: + # 数据库连接 (在环境变量中配置) + - DATABASE_URL=${DATABASE_URL} + - FLASK_APP=${FLASK_APP:-run.py} + - FLASK_ENV=${FLASK_ENV:-production} + - ORACLE_CLIENT_LIB_DIR=${ORACLE_CLIENT_LIB_DIR:-/app/oracle_client} + - ORACLE_HOME=/app/oracle_client/instantclient_19_31 + - LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client + # 允许容器访问宿主机服务 (如数据库) + extra_hosts: + - "host.docker.internal:host-gateway" + # 如果需要在宿主机调试,可暴露端口;生产环境建议只在网络内暴露 + ports: + - "5052:5052" + # 持久化运行时可写文件: + # - backend/.env 用于保存管理员后台修改的企业微信等配置(与数据库双写, + # 防止容器重建后从镜像基线读取丢失修改)。文件不存在时 docker 会自动 + # 把它当作目录挂载,因此先确保宿主机上存在该文件再启动。 + volumes: + - ./backend/.env:/app/.env + - ./oracle_client:/app/oracle_client:ro + networks: + - ai-platform + + # ============================================================================== + # hxops-frontend: Vue 前端静态资源 + Nginx 反向代理 (端口: 80) + # ============================================================================== + hxops-frontend: + image: ${FRONTEND_IMAGE:-hxops-frontend:local} + build: + context: ./frontend + dockerfile: Dockerfile + container_name: hxops-frontend + restart: always + depends_on: + - hxops-backend + # 前端容器暴露 80 端口,映射到宿主机 8890 (或其他端口供 nginx-gateway 访问) + ports: + - "8890:80" + networks: + - ai-platform + +# ============================================================================== +# 网络配置 +# ============================================================================== +networks: + ai-platform: + name: ai-platform + driver: bridge + diff --git a/docker-compose_REMOTE_79870.yml b/docker-compose_REMOTE_79870.yml new file mode 100644 index 00000000..306b8f66 --- /dev/null +++ b/docker-compose_REMOTE_79870.yml @@ -0,0 +1,126 @@ +services: + # ============================================================================== + # kb-redis: 知识库任务/后续异步能力预留的 Redis 服务 + # ============================================================================== + kb-redis: + image: ${KB_REDIS_IMAGE:-redis:7-alpine} + container_name: hxops-kb-redis + restart: always + profiles: + - kb-redis + command: ["redis-server", "--appendonly", "yes"] + volumes: + - hxops_redis_data:/data + networks: + - ai-platform + + # ============================================================================== + # hxops-backend: Flask 后端服务 (端口: 5000) + # ============================================================================== + hxops-backend: + image: ${BACKEND_IMAGE:-hxops-backend:local} + build: + context: ./backend + dockerfile: Dockerfile + args: + PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim} + PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple} + PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-} + container_name: hxops-backend + restart: always + env_file: + - ./backend/.env + environment: + # backend/.env 提供默认值;如需容器内覆盖数据库地址,可在启动前临时设置 shell 中的 DATABASE_URL。 + DATABASE_URL: + SECRET_KEY: + FLASK_APP: ${FLASK_APP:-run.py} + FLASK_ENV: ${FLASK_ENV:-production} + REDIS_URL: ${REDIS_URL:-redis://kb-redis:6379/0} + KB_STORAGE_ROOT: ${KB_STORAGE_ROOT:-/app/data/kb} + KB_TASK_EXECUTION_MODE: ${KB_TASK_EXECUTION_MODE:-worker} + KB_WORKER_POLL_SECONDS: ${KB_WORKER_POLL_SECONDS:-2} + # 允许容器访问宿主机服务 (如数据库) + extra_hosts: + - "host.docker.internal:host-gateway" + # 如果需要在宿主机调试,可暴露端口;生产环境建议只在网络内暴露 + ports: + - "5002:5000" + # 持久化运行时可写文件: + # - backend/.env 用于保存管理员后台修改的企业微信等配置(与数据库双写, + # 防止容器重建后从镜像基线读取丢失修改)。文件不存在时 docker 会自动 + # 把它当作目录挂载,因此先确保宿主机上存在该文件再启动。 + volumes: + - ./backend/.env:/app/.env + - hxops_runtime_data:/app/data + networks: + - ai-platform + + # ============================================================================== + # hxops-kb-worker: 知识库清洗/同步最小 worker + # ============================================================================== + hxops-kb-worker: + image: ${BACKEND_IMAGE:-hxops-backend:local} + build: + context: ./backend + dockerfile: Dockerfile + args: + PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim} + PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple} + PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-} + container_name: hxops-kb-worker + restart: always + command: ["python", "worker_kb.py"] + depends_on: + - hxops-backend + env_file: + - ./backend/.env + environment: + DATABASE_URL: + SECRET_KEY: + FLASK_APP: ${FLASK_APP:-run.py} + FLASK_ENV: ${FLASK_ENV:-production} + REDIS_URL: ${REDIS_URL:-redis://kb-redis:6379/0} + KB_STORAGE_ROOT: ${KB_STORAGE_ROOT:-/app/data/kb} + KB_TASK_EXECUTION_MODE: ${KB_TASK_EXECUTION_MODE:-worker} + KB_WORKER_POLL_SECONDS: ${KB_WORKER_POLL_SECONDS:-2} + extra_hosts: + - "host.docker.internal:host-gateway" + volumes: + - ./backend/.env:/app/.env + - hxops_runtime_data:/app/data + networks: + - ai-platform + + # ============================================================================== + # hxops-frontend: Vue 前端静态资源 + Nginx 反向代理 (端口: 80) + # ============================================================================== + hxops-frontend: + image: ${FRONTEND_IMAGE:-hxops-frontend:local} + build: + context: ./frontend + dockerfile: Dockerfile + args: + NODE_BASE_IMAGE: ${NODE_BASE_IMAGE:-node:22-alpine} + NGINX_BASE_IMAGE: ${NGINX_BASE_IMAGE:-nginx:alpine} + container_name: hxops-frontend + restart: always + depends_on: + - hxops-backend + # 前端容器暴露 80 端口,映射到宿主机 8890 (或其他端口供 nginx-gateway 访问) + ports: + - "8890:80" + networks: + - ai-platform + +# ============================================================================== +# 网络配置 +# ============================================================================== +networks: + ai-platform: + name: ai-platform + driver: bridge + +volumes: + hxops_runtime_data: + hxops_redis_data: diff --git a/docs/knowledge_base_runtime_deploy.md b/docs/knowledge_base_runtime_deploy.md new file mode 100644 index 00000000..944d77a9 --- /dev/null +++ b/docs/knowledge_base_runtime_deploy.md @@ -0,0 +1,171 @@ +# 主平台知识库运行时部署说明 + +## 目标 + +将知识库上传、清洗、Dify 同步运行时统一收敛到主平台 `hxops&xinxin`,不再依赖 `xinxin2` 独立运行 `api + worker + redis`。 + +当前主平台 `docker-compose.yml` 已接入: + +- `kb-redis` +- `hxops-backend` +- `hxops-kb-worker` +- `hxops-frontend` +- 共享卷 `hxops_runtime_data` + +## 容器职责 + +### `hxops-backend` + +- 提供主平台 API +- 提供知识库 API:`/api/kb/*` +- 提供集成 API:`/api/integration/*` +- 挂载知识库存储根目录到 `/app/data` + +### `hxops-kb-worker` + +- 轮询执行知识库 `clean` 任务 +- 复用后端镜像,避免维护第二套依赖 +- 与后端共享数据库、Redis、知识库存储卷 + +### `kb-redis` + +- 提供知识库异步任务所需 Redis +- 当前主要用于主平台知识库运行时接入与后续队列化扩展 + +## 关键环境变量 + +部署主平台知识库运行时时,至少确认以下变量: + +| 变量名 | 用途 | 建议值/说明 | +| --- | --- | --- | +| `DATABASE_URL` | 主平台数据库连接 | 指向当前主平台生产库 | +| `SECRET_KEY` | Flask/JWT 密钥 | 使用足够长的随机字符串 | +| `REDIS_URL` | 知识库 Redis 连接 | 默认可用 `redis://kb-redis:6379/0` | +| `KB_STORAGE_ROOT` | 知识库文件根目录 | 容器内建议保持 `/app/data/kb` | +| `KB_TASK_EXECUTION_MODE` | 任务执行模式 | 生产建议 `worker` | +| `KB_WORKER_POLL_SECONDS` | worker 轮询间隔 | 默认 `2` 即可 | +| `INTEGRATION_API_MODE` | 聊天侧集成调用模式 | 主平台自承载时建议 `local` | +| `WECOM_PUBLIC_BASE_URL` | 对外可访问主平台地址 | 供聊天/企业微信/文件回链生成绝对地址 | +| `DIFY_API_BASE` | Dify API 地址 | 按现网环境填写 | +| `DIFY_API_KEY` | Dify API Key | 由管理端保存后可持久化到 `.env`/数据库 | +| `KB_REDIS_IMAGE` | Redis 镜像来源 | 默认 `redis:7-alpine`,内网可改为私有仓库地址 | +| `PYTHON_BASE_IMAGE` | 后端基础镜像 | 默认 `python:3.12-slim`,内网可改为私有仓库地址 | +| `NODE_BASE_IMAGE` | 前端构建基础镜像 | 默认 `node:22-alpine` | +| `NGINX_BASE_IMAGE` | 前端运行基础镜像 | 默认 `nginx:alpine` | +| `PIP_INDEX_URL` | 后端 pip 主镜像源 | 可指向国内或内网 PyPI 镜像 | +| `PIP_EXTRA_INDEX_URL` | 后端 pip 额外镜像源 | 用于补充私有或备用源 | + +补充说明: + +- 宿主机应先创建 `backend/.env` 文件,再执行 `docker compose up`,避免 Docker 将目标当作目录挂载。 +- 当前 `docker-compose.yml` 不再从宿主机 shell 强依赖 `DATABASE_URL`,而是由容器内挂载的 `backend/.env` 提供数据库连接与密钥。 +- 若当前环境无法访问 Docker Hub,可在执行前设置 `KB_REDIS_IMAGE`,例如改为企业私有仓库中的 Redis 镜像。 +- 若当前环境无法访问 Docker Hub,也可同时设置 `PYTHON_BASE_IMAGE`、`NODE_BASE_IMAGE`、`NGINX_BASE_IMAGE`,把后端/前端基础镜像切到企业私有仓库。 +- 若后端 `pip install -r requirements.txt` 速度过慢或不稳定,可设置 `PIP_INDEX_URL` / `PIP_EXTRA_INDEX_URL`。 +- 若要沿用旧 `xinxin2` 文件目录,切换前需先把历史知识库文件迁入主平台卷,并保证 `KB_STORAGE_ROOT` 指向迁移后的新路径。 +- 若仍要调用外部 integration API,才需要配置 `INTEGRATION_API_BASE` 与 `INTEGRATION_API_KEY`,此时 `INTEGRATION_API_MODE` 设为 `external`。 +- 当前知识库主链路的 `worker_kb` 轮询数据库即可工作,`kb-redis` 以 profile 方式保留,用于后续异步队列扩展或外接 Redis 场景。 + +## 启动步骤 + +### 1. 构建并启动 + +```bash +docker compose up -d --build +``` + +若使用私有镜像仓库,可先设置: + +```bash +$env:KB_REDIS_IMAGE = "your-registry.example.com/library/redis:7-alpine" +$env:PYTHON_BASE_IMAGE = "your-registry.example.com/library/python:3.12-slim" +$env:NODE_BASE_IMAGE = "your-registry.example.com/library/node:22-alpine" +$env:NGINX_BASE_IMAGE = "your-registry.example.com/library/nginx:alpine" +$env:PIP_INDEX_URL = "https://pypi.tuna.tsinghua.edu.cn/simple" +docker compose up -d --build +``` + +若需要同时启用内置 Redis,再改为: + +```bash +docker compose --profile kb-redis up -d --build +``` + +### 2. 执行数据库迁移 + +```bash +docker compose exec hxops-backend flask db upgrade +``` + +### 3. 检查服务状态 + +```bash +docker compose ps +``` + +预期: + +- `hxops-backend` 为 `Up` +- `hxops-kb-worker` 为 `Up` +- `hxops-frontend` 为 `Up` + +若启用了 `kb-redis` profile,则额外确认: + +- `kb-redis` 为 `Up` + +### 4. 检查 worker 日志 + +```bash +docker compose logs -f hxops-kb-worker +``` + +预期可见: + +```text +[kb-worker] started, poll_seconds=2.0 +``` + +## 端口与卷 + +当前主平台容器端口关系: + +- 宿主机 `5002` -> `hxops-backend:5000` +- 宿主机 `8890` -> `hxops-frontend:80` + +当前关键卷: + +- `hxops_runtime_data`:主平台运行时可写数据,包含知识库存储目录 +- `hxops_redis_data`:Redis 持久化数据 + +## 切换前检查 + +切换 `xinxin2` 运行时前,至少确认: + +1. 主平台已完成数据库迁移 +2. 主平台后台可正常打开知识库管理页 +3. 上传文件后会生成 `upload/clean` 任务 +4. `hxops-kb-worker` 能持续消费待执行任务 +5. Dify 设置已在主平台管理端保存并通过健康检查 +6. 聊天侧 `INTEGRATION_API_MODE=local` +7. `WECOM_PUBLIC_BASE_URL` 对应外部真实可访问域名 + +## 切换后冒烟清单 + +建议按顺序验证: + +1. 登录主平台并进入知识库工作台 +2. 新建一个分组和一个文档条目 +3. 上传一个 `txt` 或 `md` 文件 +4. 确认任务状态从 `pending/running` 进入 `success` +5. 在文档详情里触发一次 Dify 同步 +6. 调用主平台 `/api/integration/dify-file` 或 `/api/integration/dify-files/resolve` 验证映射 +7. 从聊天侧点击源文件链接,确认下载地址仍指向主平台 + +## 常见注意事项 + +- `hxops-backend` 容器内部监听 `5000`,宿主机映射使用 `5002:5000`;若改端口,需同步更新网关/探针配置。 +- `worker_kb.py` 已按 `FLASK_ENV` 或 `APP_CONFIG` 选择配置;生产环境不要再用 `development` 配置启动 worker。 +- `KB_TASK_EXECUTION_MODE=worker` 时,需要确保 `hxops-kb-worker` 运行;若临时排障切到 `sync`,应评估接口耗时影响。 +- `kb-redis` 已改为可选 profile,不执行 `docker compose --profile kb-redis ...` 时不会默认拉起。 +- `backend/.env` 与数据库配置存在持久化联动,重建容器前不要误删该文件。 +- `SECRET_KEY` 过短会导致 JWT/HMAC 安全性不足,生产必须替换为长随机值。 diff --git a/docs/xinxin2_migration_cutover_checklist.md b/docs/xinxin2_migration_cutover_checklist.md new file mode 100644 index 00000000..91a57e94 --- /dev/null +++ b/docs/xinxin2_migration_cutover_checklist.md @@ -0,0 +1,213 @@ +# `xinxin2` 迁移收尾清单(第一版) + +## 目标 + +将 `xinxin2` 从“独立运行的文档清洗平台”收敛为: + +- 代码能力已并入 `hxops&xinxin` +- 登录入口统一使用 `hxops&xinxin` +- 聊天侧与外部系统优先访问 `hxops&xinxin` 的知识库与集成 API +- `xinxin2` 仅在少量未切换的部署职责上临时保留 + +## 当前已完成的迁移能力 + +主平台 `hxops&xinxin` 当前已经具备以下能力: + +- 知识库分组管理 +- 文档条目管理 +- 文件上传 +- 文档版本记录 +- 自动 `clean` 任务执行 +- `edkb_system` 轻量接入 +- Dify 同步第一版 +- Dify 设置与健康检查面板 +- `/api/integration/*` 集成查询接口 +- 聊天侧默认优先指向主平台自身 integration API +- 基础回归测试:分组/文档/上传/同步/集成 API + +## 结论摘要 + +### 可立即下线 + +这些入口已经被主平台完全替代,继续保留只会造成双入口混淆: + +| `xinxin2` 项 | 当前状态 | 处理建议 | +| --- | --- | --- | +| `frontend/src/views/LoginView.vue` | 已由主平台登录替代 | 停用 | +| `frontend/src/lib/auth.ts` | 已由主平台鉴权替代 | 停用 | +| `frontend/src/main.ts` | 不再需要独立前端入口 | 停用 | +| `frontend/src/router/index.ts` | 不再需要独立路由壳 | 停用 | +| `backend/app/api/auth.py` | 不再需要独立登录 API | 停用 | +| `backend/app/main.py` | 不再需要独立 FastAPI 入口 | 停用 | +| `start-local-frontend.ps1` | 不再需要独立前端启动 | 停用 | +| `start-local-dev.ps1` | 不再需要独立双进程启动 | 停用 | + +### 待切换后下线 + +这些职责在主平台里已有对应实现,但部署或调用方还需要完成切换: + +| `xinxin2` 项 | 当前替代物 | 下线前条件 | +| --- | --- | --- | +| `backend/app/api/integration.py` | `hxops&xinxin/backend/app/api/integration.py` | 确认所有调用方都改指向主平台 | +| `frontend/src/views/WorkspaceView.vue` | `hxops&xinxin/frontend/src/views/KbWorkspaceView.vue` | 用户不再访问 `8891` 前端 | +| `frontend/src/views/AdminView.vue` | `hxops&xinxin/frontend/src/views/KbAdminView.vue` | 管理员改从主平台进入 | +| `backend/app/api/groups.py` | `hxops&xinxin/backend/app/api/knowledge_base.py` | 验证分组管理不再依赖旧服务 | +| `backend/app/api/files.py` | 主平台 `knowledge_base.py` 已覆盖核心主链路 | 如需高级下载/批量功能,先补齐后再停 | +| `backend/app/tasks.py` | `hxops&xinxin/backend/app/services/knowledge_cleaning/tasks.py` | 生产环境切到主平台 worker/sync 模式 | +| `backend/worker.py` | `hxops&xinxin/backend/worker_kb.py` | 主平台部署接入 worker 后再停 | + +### 暂时保留 + +这些项暂时还建议保留,不是因为业务没迁,而是因为主平台部署面还没完全接住: + +| `xinxin2` 项 | 暂时保留原因 | 建议 | +| --- | --- | --- | +| `docker-compose.yml` | 主平台已补 `redis` / `worker_kb` / 知识库存储卷,但切换后仍需观察一段时间 | 切换稳定后再停 | +| `backend/Dockerfile` | 主平台镜像未完全吸收文档清洗依赖时,仍是参考来源 | 保留作为迁移参考 | +| `start-local-backend.ps1` | 主平台本地脚本还未完全覆盖知识库依赖检查 | 保留到本地开发文档更新完成 | +| `backend/edkb_system/*` 原仓库副本 | 主平台已轻量接入,但若要完全停旧仓库,需要确认无外部脚本再直接引用旧路径 | 短期保留 | +| `backend/tests/*` | 主平台只补了核心主链路测试,尚未完整迁入所有旧测试 | 保留到测试迁移完成 | + +## 当前最大阻塞 + +### 阻塞 1:主平台生产部署已接住知识库运行时,但仍需完成切换验证 + +当前主平台 `docker-compose.yml` 已新增: + +- `kb-redis` +- `hxops-backend` +- `hxops-kb-worker` +- `hxops-frontend` +- `hxops_runtime_data` +- `hxops_redis_data` + +影响: + +- 现在的重点已从“补部署件”转为“验证切换链路” +- 如果线上有专门的 `8891` 文件存储目录,切换前仍要确认主平台 `KB_STORAGE_ROOT` 已指向迁移后的新位置 +- 若要正式下线旧 worker,需观察主平台 `hxops-kb-worker` 实际消费任务是否稳定 + +### 阻塞 2:调用方地址切换要做最终确认 + +虽然聊天侧已经默认优先用主平台自身 `/api/integration/*`,但仍建议确认: + +- `INTEGRATION_API_MODE=local` +- `WECOM_PUBLIC_BASE_URL` 正确配置 +- 旧的 `INTEGRATION_API_BASE` 不再被外部系统直接依赖 + +### 阻塞 3:部分高级能力仍是“第一版” + +当前主平台已跑通主链路,但以下能力仍属于增强项,不建议在未验证前立刻删除旧仓库参考: + +- 更完整的 `edkb_system` skill 支持 +- 批量下载与更多文件格式处理 +- 完整异步队列化执行策略 +- 更完整的 Dify diff / import 行为 + +## 建议的切换顺序 + +### 第一步:停独立入口 + +先停掉所有“用户可见的独立入口”: + +- `xinxin2` 独立登录页 +- `xinxin2` 独立前端 Vite 本地启动 +- `xinxin2` 独立前端对外访问入口 + +判定标准: + +- 用户和管理员都只从 `hxops&xinxin` 访问知识库模块 + +### 第二步:切集成地址 + +确认聊天链路和外部系统都使用主平台集成接口: + +- `/api/integration/dify-file` +- `/api/integration/dify-files/resolve` +- `/api/integration/files/<id>/download` + +判定标准: + +- 旧 `xinxin2` 集成 API 日志无实际流量 + +### 第三步:切运行时 + +把知识库运行时职责切到主平台: + +- 在主平台 compose 中加入 `redis` +- 在主平台 compose 中加入 `worker_kb` +- 确认 `KB_STORAGE_ROOT` 与卷映射 + +判定标准: + +- 上传、自动 clean、sync_dify 都在主平台运行完成 + +### 第四步:停旧后端服务 + +当以下条件同时满足时,可停 `xinxin2` 的 `api` / `worker`: + +- 主平台知识库 API 正常 +- 主平台 integration API 正常 +- 主平台 worker 正常 +- 旧服务近一段时间无流量或仅剩探测流量 + +## 具体可下线项清单 + +### 现在就可以停 + +- `xinxin2/frontend/src/views/LoginView.vue` +- `xinxin2/frontend/src/lib/auth.ts` +- `xinxin2/frontend/src/main.ts` +- `xinxin2/frontend/src/router/index.ts` +- `xinxin2/backend/app/api/auth.py` +- `xinxin2/backend/app/main.py` +- `xinxin2/start-local-frontend.ps1` +- `xinxin2/start-local-dev.ps1` + +### 完成部署切换后可停 + +- `xinxin2/frontend/Dockerfile` +- `xinxin2/frontend/src/views/WorkspaceView.vue` +- `xinxin2/frontend/src/views/AdminView.vue` +- `xinxin2/backend/app/api/groups.py` +- `xinxin2/backend/app/api/files.py` +- `xinxin2/backend/app/api/integration.py` +- `xinxin2/backend/app/tasks.py` +- `xinxin2/backend/worker.py` +- `xinxin2/docker-compose.yml` + +### 暂时保留参考 + +- `xinxin2/backend/edkb_system/*` +- `xinxin2/backend/tests/*` +- `xinxin2/project-governance/*` +- `xinxin2/README.md` +- `xinxin2/EXTERNAL-INTEGRATION-API.md` + +## 建议新增的主平台收尾工作 + +为了真正完成下线,主平台还建议补这几项: + +- 观察主平台 `worker_kb` 切换后一段时间的稳定性 +- 为知识库模块补部署文档(见 `docs/knowledge_base_runtime_deploy.md`) +- 在主平台 README 或 docs 中补本地运行步骤 +- 继续迁移 `xinxin2` 测试到主平台 `backend/tests/` +- 补一版“切换完成后的 smoke checklist” + +## 切换完成判定 + +满足以下条件,可认为 `xinxin2` 已完成业务下线: + +- 用户只从 `hxops&xinxin` 登录和使用知识库 +- 聊天侧 source 文件映射只访问主平台 integration API +- 文档上传、clean、sync 都由主平台完成 +- 主平台部署已具备所需 worker/存储能力 +- `xinxin2` 的外部访问流量归零 + +## 当前建议 + +下一步优先做: + +1. 按 `docs/knowledge_base_runtime_deploy.md` 完成一轮主平台知识库运行时冒烟验证 +2. 观察主平台 `worker_kb`、`/api/integration/*` 与文件下载链路是否稳定 +3. 再决定是否正式停掉 `xinxin2` 的 `api/worker/frontend` diff --git a/docs/xinxin2_offline_execution_runbook.md b/docs/xinxin2_offline_execution_runbook.md new file mode 100644 index 00000000..b313d32d --- /dev/null +++ b/docs/xinxin2_offline_execution_runbook.md @@ -0,0 +1,238 @@ +# `xinxin2` 正式下线执行文档 + +## 文档目标 + +用于记录 `xinxin2` 向主平台 `hxops&xinxin` 完成迁移后的正式下线执行方案、当前实机执行结果、回滚预案与生产切换注意事项。 + +## 当前结论 + +当前主平台 `hxops&xinxin` 已实机跑通以下完整链路: + +- 知识库分组创建 +- 文档创建 +- 文件上传 +- 自动 `clean` +- 同步到本地 Dify +- `/api/integration/files/*` +- `/api/integration/dify-file` +- 源文件与 Markdown 下载 + +本地环境当前结论: + +- `xinxin2` 已满足下线条件 +- 主平台已具备替代 `xinxin2` 的完整知识库主链路能力 +- 生产环境正式切换前,仅需把本地测试用公开地址替换为真实可访问域名 + +## 本次实机执行结果 + +### 1. 主平台状态 + +当前正在运行: + +- `hxops-backend` +- `hxops-kb-worker` +- `hxops-frontend` +- `hxops-kb-redis` + +当前已验证: + +- 前端访问正常:`http://127.0.0.1:8890/` +- 后端访问正常:`http://127.0.0.1:5002/` +- 知识库上传/清洗/同步/集成接口全部通过 + +### 2. Dify 测试配置 + +当前本地测试使用: + +- `DIFY_API_BASE=http://host.docker.internal/v1` +- `DIFY_API_KEY=dataset-EYE6BMiJcVQ7OJEbob2K4gM1` + +说明: + +- 由于主平台运行在 Docker 容器中,容器内访问宿主机 Dify 不能使用 `localhost` +- 本地测试时应使用 `http://host.docker.internal/v1` + +### 3. Public Base 测试配置 + +当前本地测试使用: + +- `WECOM_PUBLIC_BASE_URL=http://127.0.0.1:5002` + +作用: + +- 让 `/api/integration/*` 返回的下载地址直接指向本机可访问的主平台后端 + +说明: + +- 该值只适用于本地验证 +- 生产环境必须替换为真实公网或内网可访问域名 + +### 4. `xinxin2` 当前运行状态 + +本机实机检查结果: + +- `docker compose ps -a`(在 `xinxin2` 目录执行)为空 +- `http://127.0.0.1:8891/` 当前不可达 + +结论: + +- 当前机器上不存在正在运行的 `xinxin2` Docker 前端/API/worker 实例 +- 因此“停止旧服务”这一步在本机已是完成状态 + +## 正式下线执行顺序 + +### 第一步:统一入口 + +执行项: + +- 停止 `xinxin2` 独立前端入口 +- 用户与管理员统一从 `hxops&xinxin` 登录 +- 不再对外暴露 `8891` 知识库前端入口 + +判定标准: + +- 用户只从主平台访问知识库 +- `8891` 无用户流量 + +### 第二步:统一调用地址 + +执行项: + +- 外部调用方统一切换到主平台 `/api/integration/*` +- 聊天侧继续使用主平台本地 integration API + +判定标准: + +- 旧 `xinxin2` integration API 流量归零 + +### 第三步:统一运行时 + +执行项: + +- 使用主平台 `hxops-backend` +- 使用主平台 `hxops-kb-worker` +- 使用主平台知识库存储卷 +- 使用主平台知识库 Dify 配置 + +判定标准: + +- 上传、`clean`、`sync_dify` 都在主平台成功完成 + +### 第四步:停止旧后端 + +执行项: + +- 停止 `xinxin2` worker +- 停止 `xinxin2` API +- 停止 `xinxin2` 旧 compose 服务 + +判定标准: + +- 主平台 API、worker、integration API 持续正常 +- 旧服务无有效访问流量 + +## 当前机器的执行状态 + +### 已完成 + +- 主平台知识库功能迁移 +- 主平台 Docker 运行时接入 +- 主平台 Dify 测试配置接入 +- 主平台 integration API 验证 +- `xinxin2` 旧前端入口不可达 +- `xinxin2` compose 无运行实例 + +### 当前无需再执行的停机动作 + +在这台机器上,以下动作已无需再做: + +- `docker compose stop` `xinxin2` 前端 +- `docker compose stop` `xinxin2` API +- `docker compose stop` `xinxin2` worker + +原因: + +- 当前本机 `xinxin2` 本就未运行 + +## 回滚预案 + +若主平台切换后出现异常,可按以下顺序回滚: + +1. 恢复 `xinxin2` 前端入口 +2. 恢复 `xinxin2` API +3. 恢复 `xinxin2` worker +4. 将调用方 integration 地址切回旧服务 +5. 验证旧链路恢复后,再排查主平台问题 + +## 回滚时禁止直接删除 + +- `xinxin2` 数据库 +- `xinxin2` 历史文件目录 +- `xinxin2/docker-compose.yml` +- `xinxin2/backend/tests/*` +- `xinxin2/backend/edkb_system/*` + +## 生产环境切换前必改项 + +### 1. `WECOM_PUBLIC_BASE_URL` + +本地测试值: + +- `http://127.0.0.1:5002` + +生产要求: + +- 替换为真实公网或内网可访问域名 + +### 2. `DIFY_API_BASE` + +本地测试值: + +- `http://host.docker.internal/v1` + +生产要求: + +- 替换为生产环境 Dify 可访问地址 + +### 3. `DIFY_API_KEY` + +本地测试值: + +- `dataset-EYE6BMiJcVQ7OJEbob2K4gM1` + +生产要求: + +- 替换为生产可用的 Dify Key + +### 4. 其他关键生产变量 + +切换前同时确认: + +- `DATABASE_URL` +- `SECRET_KEY` +- `KB_STORAGE_ROOT` +- `INTEGRATION_API_MODE=local` + +## 生产切换后最小冒烟清单 + +建议逐项验证: + +1. 登录主平台知识库工作台 +2. 新建分组 +3. 新建文档 +4. 上传 `txt` 或 `md` +5. 确认 `clean` 成功 +6. 触发同步到 Dify +7. 调用 `/api/integration/dify-file` +8. 点击下载源文件与 Markdown + +## 最终结论 + +在当前本地环境中: + +- `xinxin2` 已可正式进入下线状态 +- 主平台 `hxops&xinxin` 已完成替代 + +在生产环境中: + +- 只要把本地测试配置替换为真实生产配置,即可按本执行文档推进正式切换 diff --git a/docs/新人环境搭建与配置文档.md b/docs/新人环境搭建与配置文档.md index 179b3d6a..18f565eb 100644 --- a/docs/新人环境搭建与配置文档.md +++ b/docs/新人环境搭建与配置文档.md @@ -154,6 +154,12 @@ docker compose up -d --build - 后端:`5052:5052` 注意:当前项目中后端端口存在 `5000` 与 `5052` 并存配置,若容器联调异常,优先统一端口配置。 +- 后端:`5002:5000` + +补充: + +- 容器内后端监听 `5000`,宿主机对外暴露 `5002` +- 知识库运行时部署说明见 `docs/knowledge_base_runtime_deploy.md` ## 6. 项目登录环境与账号配置 @@ -221,13 +227,22 @@ docker compose up -d --build | `SECRET_KEY` | Flask 密钥 | 随机长字符串 | | `DATABASE_URL` | 数据库连接 | `postgresql://user:pwd@host:5432/db` | | `REDIS_URL` | Redis 连接 | `redis://:pwd@host:6379/0` | +| `KB_STORAGE_ROOT` | 知识库存储根目录 | `/app/data/kb` | +| `KB_TASK_EXECUTION_MODE` | 知识库任务执行模式 | `worker` / `sync` / `manual` | +| `KB_WORKER_POLL_SECONDS` | worker 轮询间隔 | `2` | +| `KB_REDIS_IMAGE` | Redis 镜像来源 | `redis:7-alpine` 或私有仓库镜像 | +| `PYTHON_BASE_IMAGE` | 后端基础镜像 | `python:3.12-slim` 或私有仓库镜像 | +| `NODE_BASE_IMAGE` | 前端构建基础镜像 | `node:22-alpine` 或私有仓库镜像 | +| `NGINX_BASE_IMAGE` | 前端运行基础镜像 | `nginx:alpine` 或私有仓库镜像 | | `DIFY_API_BASE` | Dify 地址 | `https://api.dify.ai/v1` | | `DIFY_API_KEY` | Dify 密钥 | `sk-...` | | `HR_WORKFLOW_IFRAME_URL` | HR 页面链接 | `https://...` | | `HR_WORKFLOW_API_BASE` | HR API 地址 | `https://...` | | `HR_WORKFLOW_API_KEY` | HR API 密钥 | `<待补>` | +| `INTEGRATION_API_MODE` | 集成 API 模式 | `local` / `external` | | `INTEGRATION_API_BASE` | 集成 API 地址 | `https://...` | | `INTEGRATION_API_KEY` | 集成 API 密钥 | `<待补>` | +| `WECOM_PUBLIC_BASE_URL` | 主平台公网基地址 | `https://<your-domain>` | | `WECOM_*` | 企业微信配置 | 见第 6.4 节 | | `CASDOOR_BASE_URL` | Casdoor 地址 | `http://192.168.100.230:8870` | | `CASDOOR_REDIRECT_URI` | OAuth 兜底回调 | 见 §6.2.1;须与 Casdoor 登记一致 | diff --git a/frontend/Dockerfile b/frontend/Dockerfile index 1dbcd8f1..56a625b6 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -1,4 +1,6 @@ -FROM node:22-alpine AS builder +ARG NODE_BASE_IMAGE=node:22-alpine +ARG NGINX_BASE_IMAGE=nginx:alpine +FROM ${NODE_BASE_IMAGE} AS builder WORKDIR /app COPY package*.json ./ @@ -6,10 +8,10 @@ RUN npm ci COPY . . RUN npm run build -FROM nginx:alpine +FROM ${NGINX_BASE_IMAGE} COPY nginx.conf /etc/nginx/conf.d/default.conf COPY --from=builder /app/dist /usr/share/nginx/html EXPOSE 80 -CMD ["nginx", "-g", "daemon off;"] \ No newline at end of file +CMD ["nginx", "-g", "daemon off;"] diff --git a/frontend/dist/index.html b/frontend/dist/index.html index 986a0937..a7199826 100644 --- a/frontend/dist/index.html +++ b/frontend/dist/index.html @@ -10,8 +10,13 @@ <meta name="apple-mobile-web-app-title" content="AI工作台" /> <link rel="manifest" href="/manifest.webmanifest" /> <title>AI工作台 +<<<<<<< HEAD +======= + + +>>>>>>> runny&xinxin
diff --git a/frontend/nginx.conf b/frontend/nginx.conf index a2844bc9..04e607cd 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -1,6 +1,9 @@ server { listen 80; server_name localhost; + client_max_body_size 100m; + resolver 127.0.0.11 valid=30s ipv6=off; + resolver_timeout 5s; # 静态资源服务 location / { @@ -11,9 +14,11 @@ server { # API 代理到后端 location /api/ { - # 注意: 这里使用 Docker Compose 服务名 - # 使用 /api/ 后缀确保传递完整路径 - proxy_pass http://hxops-backend:5000/api/; + # 通过 Docker 内置 DNS 动态解析后端服务,避免后端容器重建后 + # Nginx 继续使用启动时缓存的旧 IP 而出现 502。 + set $backend_upstream hxops-backend:5000; + # 变量形式下不要附带 URI,保留原始 /api/... 路径透传给后端。 + proxy_pass http://$backend_upstream; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; diff --git a/frontend/public/sw.js b/frontend/public/sw.js index 0191d8c4..56e416ea 100644 --- a/frontend/public/sw.js +++ b/frontend/public/sw.js @@ -1,53 +1,17 @@ -const CACHE_NAME = 'hxops-shell-v2'; -const OFFLINE_ASSETS = ['/', '/workspace', '/manifest.webmanifest', '/vite.svg']; - self.addEventListener('install', (event) => { event.waitUntil( - caches.open(CACHE_NAME).then((cache) => cache.addAll(OFFLINE_ASSETS)).catch(() => null) + self.skipWaiting() ); - self.skipWaiting(); }); self.addEventListener('activate', (event) => { event.waitUntil( - caches.keys().then((keys) => - Promise.all( - keys - .filter((key) => key !== CACHE_NAME) - .map((key) => caches.delete(key)) - ) - ) - ); - self.clients.claim(); -}); - -self.addEventListener('fetch', (event) => { - const request = event.request; - if (request.method !== 'GET') return; - - const url = new URL(request.url); - if (url.origin !== self.location.origin) return; - if (url.pathname.startsWith('/api/')) return; - if (url.pathname.startsWith('/@vite/')) return; - if (url.pathname.includes('/__vite_ping')) return; - - if (request.mode === 'navigate') { - event.respondWith( - fetch(request).catch(() => caches.match('/workspace').then((res) => res || caches.match('/'))) - ); - return; - } - - event.respondWith( - caches.match(request).then((cached) => { - if (cached) return cached; - return fetch(request) - .then((response) => { - const copy = response.clone(); - caches.open(CACHE_NAME).then((cache) => cache.put(request, copy)).catch(() => null); - return response; - }) - .catch(() => caches.match('/vite.svg')); - }) + (async () => { + const keys = await caches.keys(); + await Promise.all(keys.map((key) => caches.delete(key))); + await self.clients.claim(); + const registrations = await self.registration.unregister(); + return registrations; + })() ); }); diff --git a/frontend/src/api/kb.ts b/frontend/src/api/kb.ts new file mode 100644 index 00000000..eeb3ee25 --- /dev/null +++ b/frontend/src/api/kb.ts @@ -0,0 +1,557 @@ +import { getAuthHeaders } from '../utils/auth'; + +export interface KbGroup { + id: number; + name: string; + description?: string | null; + department_id?: number | null; + document_count?: number; + created_at?: string | null; + updated_at?: string | null; +} + +export interface KbDocumentItem { + id: number; + group_id?: number; + title: string; + description?: string | null; + status?: string; + source_type?: string | null; + created_at?: string | null; + updated_at?: string; + version_count?: number; + latest_version?: KbDocumentVersionItem | null; +} + +export interface KbDocumentVersionItem { + id: number; + document_id: number; + version_no: number; + status: string; + is_current: boolean; + source_file_name: string; + source_file_ext?: string | null; + source_file_size?: number | null; + sha256?: string | null; + cleaned_file_path?: string | null; + cleaned_preview_path?: string | null; + error_message?: string | null; + created_at?: string | null; +} + +export interface KbSyncRecordItem { + id: number; + group_id?: number | null; + document_id?: number | null; + document_version_id: number; + dataset_id: string; + dataset_name?: string | null; + remote_document_id: string; + remote_document_name?: string | null; + status: string; + sync_hash?: string | null; + error_message?: string | null; + synced_at?: string | null; + updated_at?: string | null; +} + +export interface KbDocumentMarkdown { + document_id: number; + title: string; + version: KbDocumentVersionItem | null; + content: string; + kind: 'markdown' | 'preview'; +} + +export interface KbJob { + id: number | string; + job_type: string; + status: string; + group_id?: number | null; + document_id?: number | null; + document_version_id?: number | null; + progress?: number; + message?: string | null; + error_message?: string | null; + payload_json?: Record | null; + result_json?: Record | null; + created_at?: string; + started_at?: string | null; + finished_at?: string | null; +} + +export interface KbDifySettings { + DIFY_API_BASE: string; + DIFY_API_KEY: string; + KB_DIFY_PERMISSION: string; + KB_DIFY_INDEXING_TECHNIQUE: string; + KB_DIFY_SEARCH_METHOD: string; + KB_DIFY_DOC_FORM: string; + dify_api_configured?: boolean; +} + +export interface KbDifyHealth { + dify_base_url: string; + dify_api_configured: boolean; + api: { + configured: boolean; + reachable: boolean; + dataset_count?: number | null; + error?: string | null; + }; + local_sync_health: { + dataset_bound_groups: number; + sync_records: number; + syncing_versions: number; + synced_versions: number; + failed_sync_records: number; + pending_sync_jobs: number; + }; +} + +export interface KbListResponse { + ok: boolean; + data: T; + error?: string; + status?: number; +} + +const getJson = async (path: string, fallback: T): Promise => { + try { + const res = await fetch(path, { headers: getAuthHeaders() }); + if (!res.ok) return fallback; + return (await res.json()) as T; + } catch { + return fallback; + } +}; + +const getJsonWithStatus = async (path: string, fallback: T): Promise> => { + try { + const res = await fetch(path, { headers: getAuthHeaders() }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { + ok: false, + data: fallback, + error: data?.error || '知识库接口请求失败', + status: res.status, + }; + } + return { ok: true, data: (await res.json()) as T, status: res.status }; + } catch { + return { ok: false, data: fallback, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const getKbGroups = async (): Promise => { + return getJson('/api/kb/groups', []); +}; + +export const getKbGroupFiles = async (groupId: number): Promise => { + return getJson(`/api/kb/groups/${groupId}/files`, []); +}; + +export const getKbGroupsSafe = async (): Promise> => { + return getJsonWithStatus('/api/kb/groups', []); +}; + +export const getKbGroupFilesSafe = async (groupId: number): Promise> => { + return getJsonWithStatus(`/api/kb/groups/${groupId}/files`, []); +}; + +export const createKbGroup = async (payload: { + name: string; + description?: string; +}): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => { + try { + const res = await fetch('/api/kb/groups', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...getAuthHeaders(), + }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '创建知识库分组失败' }; + } + return { ok: true, group: (await res.json()) as KbGroup }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const getKbJobs = async (): Promise => { + return getJson('/api/kb/jobs', []); +}; + +export const getKbJobsSafe = async (): Promise> => { + return getJsonWithStatus('/api/kb/jobs', []); +}; + +export const getKbDifySettings = async (): Promise => { + return getJson('/api/kb/dify/settings', null); +}; + +export const updateKbDifySettings = async ( + payload: Partial +): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => { + try { + const res = await fetch('/api/kb/dify/settings', { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + ...getAuthHeaders(), + }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '保存 Dify 设置失败' }; + } + return { ok: true, settings: (await res.json()) as KbDifySettings }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const getKbDifyHealth = async (): Promise => { + return getJson('/api/kb/dify/health', null); +}; + +export const runKbJob = async ( + jobId: number | string +): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => { + try { + const res = await fetch(`/api/kb/jobs/${jobId}/run`, { + method: 'POST', + headers: getAuthHeaders(), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '执行任务失败' }; + } + const job = (await res.json()) as KbJob & { run_result?: string }; + return { ok: true, job, run_result: job.run_result }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const createKbDocument = async ( + groupId: number, + payload: { title: string; description?: string } +): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => { + try { + const res = await fetch(`/api/kb/groups/${groupId}/files`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...getAuthHeaders(), + }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '创建文档失败' }; + } + return { ok: true, document: (await res.json()) as KbDocumentItem }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const updateKbDocument = async ( + documentId: number, + payload: { title: string; description?: string; status?: string } +): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => { + try { + const res = await fetch(`/api/kb/documents/${documentId}`, { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + ...getAuthHeaders(), + }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '更新文档失败' }; + } + return { ok: true, document: (await res.json()) as KbDocumentItem }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const deleteKbDocument = async ( + documentId: number +): Promise<{ ok: boolean; error?: string }> => { + try { + const res = await fetch(`/api/kb/documents/${documentId}`, { + method: 'DELETE', + headers: getAuthHeaders(), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '删除文档失败' }; + } + return { ok: true }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const getKbDocumentVersions = async ( + documentId: number +): Promise => { + return getJson(`/api/kb/documents/${documentId}/versions`, []); +}; + +export const getKbDocumentVersionSourceFile = async ( + versionId: number +): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => { + try { + const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, { + headers: getAuthHeaders(), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '读取原始文件失败' }; + } + const disposition = res.headers.get('content-disposition') || ''; + const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i); + const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || ''); + return { + ok: true, + blob: await res.blob(), + filename: filename || undefined, + contentType: res.headers.get('content-type') || undefined, + }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const getKbDocumentSyncRecords = async ( + documentId: number +): Promise => { + return getJson(`/api/kb/documents/${documentId}/sync-records`, []); +}; + +export const getKbDocumentMarkdown = async ( + documentId: number +): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => { + try { + const res = await fetch(`/api/kb/documents/${documentId}/markdown`, { + headers: getAuthHeaders(), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '读取清洗后的 Markdown 失败' }; + } + return { ok: true, data: (await res.json()) as KbDocumentMarkdown }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const updateKbDocumentMarkdown = async ( + documentId: number, + payload: { content: string } +): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => { + try { + const res = await fetch(`/api/kb/documents/${documentId}/markdown`, { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + ...getAuthHeaders(), + }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '保存 Markdown 失败' }; + } + return { ok: true, data: (await res.json()) as KbDocumentMarkdown }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const uploadKbDocumentVersion = async ( + documentId: number, + file: File +): Promise<{ ok: boolean; error?: string; version?: KbDocumentVersionItem; status?: number }> => { + try { + const formData = new FormData(); + formData.append('file', file); + + const res = await fetch(`/api/kb/documents/${documentId}/upload`, { + method: 'POST', + headers: getAuthHeaders(), + body: formData, + }); + if (!res.ok) { + if (res.status === 413) { + return { ok: false, error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试', status: res.status }; + } + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '上传文档版本失败', status: res.status }; + } + return { ok: true, version: (await res.json()) as KbDocumentVersionItem, status: res.status }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const createKbPathUploadJob = async ( + groupId: number, + payload: { total_files: number; selected_paths: string[] } +): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => { + try { + const res = await fetch(`/api/kb/groups/${groupId}/path-upload-jobs`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...getAuthHeaders(), + }, + body: JSON.stringify(payload), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + return { ok: false, error: data?.error || '创建路径上传任务失败', status: res.status }; + } + return { ok: true, job: data as KbJob, status: res.status }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const uploadKbPathJobFile = async ( + jobId: number | string, + file: File, + relativePath: string, +): Promise<{ ok: boolean; error?: string; job?: KbJob }> => { + try { + const formData = new FormData(); + formData.append('file', file); + formData.append('relative_path', relativePath); + + const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/files`, { + method: 'POST', + headers: getAuthHeaders(), + body: formData, + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + return { ok: false, error: data?.error || '上传路径文件失败' }; + } + return { ok: true, job: data as KbJob }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const finalizeKbPathUploadJob = async ( + jobId: number | string, +): Promise<{ ok: boolean; error?: string; job?: KbJob }> => { + try { + const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/finalize`, { + method: 'POST', + headers: getAuthHeaders(), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + return { ok: false, error: data?.error || '提交路径上传任务失败' }; + } + return { ok: true, job: data as KbJob }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const retryFailedKbPathUploadJob = async ( + jobId: number | string, + payload?: { relative_paths?: string[] }, +): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => { + try { + const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...getAuthHeaders(), + }, + body: JSON.stringify(payload || {}), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + return { ok: false, error: data?.error || '重试失败文件失败', status: res.status }; + } + return { ok: true, job: data as KbJob, status: res.status }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const syncKbDocumentToDify = async ( + documentId: number +): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => { + try { + const res = await fetch(`/api/kb/documents/${documentId}/sync`, { + method: 'POST', + headers: getAuthHeaders(), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || data?.error_message || data?.run_result || '同步到 Dify 失败' }; + } + const job = (await res.json()) as KbJob & { run_result?: string }; + return { ok: true, job, run_result: job.run_result }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const updateKbGroup = async ( + groupId: number, + payload: { name: string; description?: string } +): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => { + try { + const res = await fetch(`/api/kb/groups/${groupId}`, { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + ...getAuthHeaders(), + }, + body: JSON.stringify(payload), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '更新知识库分组失败' }; + } + return { ok: true, group: (await res.json()) as KbGroup }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; + +export const deleteKbGroup = async ( + groupId: number +): Promise<{ ok: boolean; error?: string }> => { + try { + const res = await fetch(`/api/kb/groups/${groupId}`, { + method: 'DELETE', + headers: getAuthHeaders(), + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + return { ok: false, error: data?.error || '删除知识库分组失败' }; + } + return { ok: true }; + } catch { + return { ok: false, error: '知识库接口暂未就绪,请稍后再试' }; + } +}; diff --git a/frontend/src/components/kb/DifyHealthDialog.vue b/frontend/src/components/kb/DifyHealthDialog.vue new file mode 100644 index 00000000..ff0030b9 --- /dev/null +++ b/frontend/src/components/kb/DifyHealthDialog.vue @@ -0,0 +1,115 @@ + + + diff --git a/frontend/src/components/kb/DifySettingsDialog.vue b/frontend/src/components/kb/DifySettingsDialog.vue new file mode 100644 index 00000000..e5b4e8fc --- /dev/null +++ b/frontend/src/components/kb/DifySettingsDialog.vue @@ -0,0 +1,134 @@ + + + diff --git a/frontend/src/main.ts b/frontend/src/main.ts index ef28d191..48db241c 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -1,4 +1,4 @@ -import { createApp } from 'vue' +import { createApp } from 'vue' import './style.css' import App from './App.vue' import router from './router' @@ -52,10 +52,17 @@ createApp(App) .use(i18n) .mount('#app') -if (import.meta.env.PROD && 'serviceWorker' in navigator) { - window.addEventListener('load', () => { - navigator.serviceWorker.register('/sw.js').catch((err) => { - console.error('Service worker registration failed:', err); - }); +if ('serviceWorker' in navigator) { + window.addEventListener('load', async () => { + try { + const registrations = await navigator.serviceWorker.getRegistrations(); + await Promise.all(registrations.map((registration) => registration.unregister())); + if ('caches' in window) { + const cacheKeys = await window.caches.keys(); + await Promise.all(cacheKeys.map((key) => window.caches.delete(key))); + } + } catch (err) { + console.error('Service worker cleanup failed:', err); + } }); } diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 8aa49a6c..2613e8f1 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -6,6 +6,8 @@ import ChatView from '../views/ChatView.vue'; import AdminView from '../views/AdminView.vue'; import ProfileView from '../views/ProfileView.vue'; import ResetPasswordView from '../views/ResetPasswordView.vue'; +import KbWorkspaceView from '../views/KbWorkspaceView.vue'; +import KbAdminView from '../views/KbAdminView.vue'; import { config } from '../config'; import { getStoredAuthUser } from '../utils/auth'; @@ -45,6 +47,18 @@ const routes = [ name: 'Admin', component: AdminView }, + { + path: '/kb/workspace', + name: 'KbWorkspace', + component: KbWorkspaceView, + meta: { title: '知识库工作台' } + }, + { + path: '/kb/admin', + name: 'KbAdmin', + component: KbAdminView, + meta: { title: '知识库管理台' } + }, ]; diff --git a/frontend/src/views/AdminView.vue b/frontend/src/views/AdminView.vue index e41cbdc4..edeeedc3 100644 --- a/frontend/src/views/AdminView.vue +++ b/frontend/src/views/AdminView.vue @@ -2544,6 +2544,13 @@ const handlePermissionImport = async (event: Event) => {
+
diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 9b3e8f28..0a6e2f58 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -628,26 +628,10 @@ const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\ const isStrongLeaveIntent = (content: string) => { const normalized = getLeaveIntentNormalized(content); - return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|我要走请假流程)/.test(normalized); -}; - -const startLocalLeaveFlow = (content: string) => { - const formId = newLocalMessageId('leave-form'); - const payload: LeaveFormPayload = { - formId, - form: createLeaveFormData(), - submitting: false, - confirmationGenerated: false, - }; - messages.value.push({ role: 'user', content, type: 'text' }); - messages.value.push({ - role: 'assistant', - type: 'leave-form', - content: '已为你生成请假申请表,请直接在下方填写并提交。或登录OA系统直接申请', - payload, - local_id: formId, - local_only: true, - }); + // 弱意图(咨询流程/步骤)应走正常问答,不触发表单分流。 + const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定)/; + if (weakConsultationIntent.test(normalized)) return false; + return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|帮我请假|代我请假|提交请假)/.test(normalized); }; const getLeaveFormPayload = (msg: any): LeaveFormPayload | null => ( diff --git a/frontend/src/views/KbAdminView.vue b/frontend/src/views/KbAdminView.vue new file mode 100644 index 00000000..b1403123 --- /dev/null +++ b/frontend/src/views/KbAdminView.vue @@ -0,0 +1,360 @@ + + +