Merge branch 'runny&xinxin' into dev
This commit is contained in:
commit
8d73343bd8
77 files changed
+17955
-274
No files matched your search
+36
-8
@@ -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/ .
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<<<<<<< HEAD
|
||||
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
|
||||
=======
|
||||
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"
|
||||
>>>>>>> runny&xinxin
|
||||
|
||||
# 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"]
|
||||
|
||||
@@ -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"]
|
||||
@@ -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"]
|
||||
|
||||
@@ -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"]
|
||||
@@ -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
|
||||
|
||||
+37
-16
@@ -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])
|
||||
|
||||
|
||||
+61
-8
@@ -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
|
||||
|
||||
@@ -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/<conversation_id>', 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
|
||||
@@ -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/<int:file_id>', 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/<int:knowledge_base_id>/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/<int:file_id>/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)
|
||||
File diff suppressed because it is too large.
Load diff
+157
-98
@@ -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/<int:agent_id>', 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():
|
||||
|
||||
+56
-29
@@ -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]:
|
||||
|
||||
@@ -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',
|
||||
)
|
||||
|
||||
|
||||
|
||||
+186
-1
@@ -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):
|
||||
"""
|
||||
企业微信回调审计表
|
||||
|
||||
@@ -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}',
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
"""
|
||||
知识库清洗服务包
|
||||
"""
|
||||
@@ -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}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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 / <parent_dir_name> / <filename>.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()),
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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'
|
||||
@@ -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<host>[^:/]+)(?::(?P<port>\d+))?/(?P<service>.+)$", 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):
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
integration smoke text
|
||||
@@ -37,5 +37,6 @@ daemon = False
|
||||
# 进程名称
|
||||
proc_name = "hxops_backend"
|
||||
|
||||
# 预加载应用 (加快启动速度)
|
||||
preload_app = True
|
||||
# 应用启动时会访问数据库加载持久化配置;预加载会让主进程先建立连接再 fork,
|
||||
# 导致 worker 继承损坏的数据库连接。
|
||||
preload_app = False
|
||||
@@ -0,0 +1 @@
|
||||
"""Enterprise KB Skill System orchestrator package."""
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
@@ -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]
|
||||
@@ -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 != "<empty>":
|
||||
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
|
||||
@@ -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))
|
||||
@@ -0,0 +1 @@
|
||||
"""Atomic skills for enterprise KB pipeline."""
|
||||
@@ -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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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"")
|
||||
else:
|
||||
lines.append(f"")
|
||||
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)
|
||||
@@ -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}
|
||||
@@ -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""
|
||||
|
||||
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""
|
||||
|
||||
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)}
|
||||
@@ -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}
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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))
|
||||
@@ -26,3 +26,7 @@ keepalive = 5
|
||||
accesslog = "-"
|
||||
errorlog = "-"
|
||||
loglevel = "info"
|
||||
|
||||
# 应用启动时会访问数据库加载持久化配置;预加载会让主进程先建立连接再 fork,
|
||||
# 导致 worker 继承损坏的数据库连接。
|
||||
preload_app = False
|
||||
@@ -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')
|
||||
@@ -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
|
||||
@@ -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'
|
||||
@@ -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')
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user