kbzhishiku

This commit is contained in:
runny committed 2026-05-12 08:16:42 +08:00
1 parent 7f542f54a5
commit 08a19ebe96
68 files changed
+16602 -229

No files matched your search

+37 -2
View File
@@ -1,10 +1,45 @@
FROM python:3.12-slim
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 pip install --no-cache-dir -r 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 . .
+6
View File
@@ -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
View File
@@ -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])
+3 -3
View File
@@ -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):
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 = ''
+349
View File
@@ -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
View File
@@ -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
@@ -1704,64 +1734,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):
@@ -1872,41 +1914,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
@@ -2039,17 +2085,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
View File
@@ -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
@@ -138,43 +139,69 @@ def _decode_jwt(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]:
+5 -3
View File
@@ -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')
@@ -96,9 +100,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
View File
@@ -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):
"""
企业微信回调审计表
+34 -8
View File
@@ -5,7 +5,7 @@ from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
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 +13,32 @@ from app.config import Config
class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@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":
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 +86,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 +108,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 +147,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 +162,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 +213,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'
@@ -0,0 +1 @@
integration smoke text
+3 -2
View File
@@ -37,5 +37,6 @@ daemon = False
# 进程名称
proc_name = "hxops_backend"
# 预加载应用 (加快启动速度)
preload_app = True
# 应用启动时会访问数据库加载持久化配置;预加载会让主进程先建立连接再 fork,
# 导致 worker 继承损坏的数据库连接。
preload_app = False
+1
View File
@@ -0,0 +1 @@
"""Enterprise KB Skill System orchestrator package."""
+167
View File
@@ -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()
+53
View File
@@ -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)
+54
View File
@@ -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]
+893
View File
@@ -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
+22
View File
@@ -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))
+1
View File
@@ -0,0 +1 @@
"""Atomic skills for enterprise KB pipeline."""
+90
View File
@@ -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
+244
View File
@@ -0,0 +1,244 @@
from __future__ import annotations
import hashlib
import json
import re
from dataclasses import asdict
from pathlib import Path
from typing import Any
from edkb_system.contracts import Block
def hash_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def hash_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def _page_image_structured_lines(payload: str) -> list[str]:
tokens = [x.strip() for x in payload.split(";") if x.strip()]
if not tokens:
return []
cert_context_hits = 0
cert_context_pat = re.compile(
r"證明書|证明书|CERTIFICATE|材质|材質|TEST CERTIFICATE|ROHS|MSDS|"
r"检测报告|測試報告|材质证明|物性表",
re.IGNORECASE,
)
for tok in tokens:
if cert_context_pat.search(tok):
cert_context_hits += 1
if cert_context_hits < 2:
return []
def _find(pattern: str) -> str:
rx = re.compile(pattern, re.IGNORECASE)
for tok in tokens:
if rx.search(tok):
return tok
return ""
def _find_match(pattern: str) -> str:
rx = re.compile(pattern, re.IGNORECASE)
for tok in tokens:
m = rx.search(tok)
if m:
return m.group(0)
return ""
def _find_after(anchor_pat: str, value_pat: str = r".+") -> str:
anchor_rx = re.compile(anchor_pat, re.IGNORECASE)
value_rx = re.compile(value_pat, re.IGNORECASE)
for idx, tok in enumerate(tokens):
if not anchor_rx.search(tok):
continue
for cand in tokens[idx + 1 : idx + 8]:
if value_rx.search(cand) and not anchor_rx.search(cand):
return cand
return ""
def _uniq(values: list[tuple[str, str]]) -> list[tuple[str, str]]:
out: list[tuple[str, str]] = []
seen: set[str] = set()
for key, value in values:
v = value.strip()
if not v:
continue
marker = f"{key}:{v.lower()}"
if marker in seen:
continue
seen.add(marker)
out.append((key, v))
return out
certificate_no = ""
cert_anchor = re.compile(
r"證明書编号|證明書編號|CERTIFICATE\s*(?:NO|NUMBER)?", re.IGNORECASE
)
cert_value = re.compile(r"(?=.*\d)[A-Z0-9][A-Z0-9/-]{5,}", re.IGNORECASE)
for idx, tok in enumerate(tokens):
if not cert_anchor.search(tok):
continue
for cand in tokens[idx + 1 : idx + 8]:
if re.search(r"fax|tel|date", cand, re.IGNORECASE):
continue
if cert_value.fullmatch(cand):
certificate_no = cand
break
if certificate_no:
break
if not certificate_no:
certificate_no = _find_match(
r"\b(?=[A-Z0-9-]*\d)[A-Z0-9]{4,}-[A-Z0-9-]+\b"
) or _find_match(r"\b\d{6,}[A-Z0-9/-]*\b")
issue_date = _find(
r"(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[A-Z.]*\s*\d{1,2},?\s*\d{4}"
)
spec = _find(r"JIS\s*G\d+|SGCC|EN\s*\d+")
product = _find_after(r"PRODUCT", r"[A-Z]{2,}[-A-Z0-9 ]{3,}|COIL") or _find(
r"HDG[-A-Z0-9 ]*COIL"
)
customer = _find(r"CORPORATION|COMPANY|STEEL")
order_no = _find_after(r"ORDER|訂單|订单", r"[A-Z0-9/-]{5,}") or _find(
r"[A-Z]{0,3}\d{3,}[A-Z0-9/-]*"
)
weight = ""
for idx, tok in enumerate(tokens):
if tok.lower() == "kg" and idx > 0:
m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?", tokens[idx - 1])
weight = (m.group(0) if m else tokens[idx - 1]) + " kg"
break
m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?\s*kg", tok, re.IGNORECASE)
if m:
weight = m.group(0)
break
tensile: list[tuple[str, str]] = []
for idx, tok in enumerate(tokens):
if tok in {"降伏", "抗拉", "硬度"}:
for cand in tokens[idx + 1 : idx + 4]:
if re.fullmatch(r"\d+(?:\.\d+)?", cand):
tensile.append((tok, cand))
break
fields = _uniq(
[
("证书编号", certificate_no),
("日期", issue_date),
("客户", customer),
("产品", product),
("规格", spec),
("订单/追踪号", order_no),
("重量", weight),
]
)
if not fields and not tensile:
return []
lines = ["## 识别整理版", ""]
for key, value in fields:
lines.append(f"- {key}:{value}")
if tensile:
if fields:
lines.append("")
lines.append("### 关键数值")
lines.append("")
lines.append("| 项目 | 数值 |")
lines.append("| --- | --- |")
for key, value in _uniq(tensile):
lines.append(f"| {key} | {value} |")
lines.extend(["", "## 原始识别结果", ""])
return lines
def blocks_to_plain_markdown(blocks: list[Block]) -> str:
def _ocr_payload(txt: str) -> str:
payload = txt
if payload.startswith("OCR_TEXT:"):
payload = payload[len("OCR_TEXT:") :].strip()
if not payload or payload == "<empty>":
return ""
payload = re.sub(r"(?m)^\s*-\s*", "", payload)
payload = ";".join(x.strip() for x in payload.splitlines() if x.strip())
return payload
ocr_by_image: dict[str, str] = {}
for b in blocks:
if b.type != "ocr_text" or not b.id.startswith("ocr-"):
continue
payload = _ocr_payload((b.text or "").strip())
if payload:
ocr_by_image[b.id[len("ocr-") :]] = payload
page_text_chars: dict[int, int] = {}
page_body_chars: dict[int, int] = {}
for b in blocks:
if b.type in {"ocr_text", "image"}:
continue
txt = (b.text or "").strip()
if not txt:
continue
page_text_chars[b.page] = page_text_chars.get(b.page, 0) + len(txt)
if b.type != "heading":
page_body_chars[b.page] = page_body_chars.get(b.page, 0) + len(txt)
lines: list[str] = []
image_idx = 0
for b in sorted(
[x for x in blocks if x.type != "ocr_text"],
key=lambda x: (x.page, x.cy(), x.cx()),
):
txt = (b.text or "").strip()
if not txt and b.type != "image":
continue
if b.type == "heading":
lines.append(f"## {txt}")
elif b.type == "image":
data_uri = b.meta.get("data_uri") if b.meta else None
if data_uri:
image_idx += 1
if b.meta and b.meta.get("page_image"):
lines.append(f"![page-image-{b.page}]({data_uri})")
else:
lines.append(f"![image-{image_idx}]({data_uri})")
ocr_text = ocr_by_image.get(b.id)
if ocr_text:
suppress_pptx_ocr = bool(
b.meta and b.meta.get("page_image_source") == "pptx"
) and (
page_body_chars.get(b.page, 0) >= 15
or page_text_chars.get(b.page, 0) >= 40
)
if (
b.meta
and b.meta.get("page_image")
and b.meta.get("page_image_source") != "pptx"
):
lines.extend(_page_image_structured_lines(ocr_text))
if not suppress_pptx_ocr:
lines.append(f"图中文字:{ocr_text}")
else:
lines.append("![image]")
else:
lines.append(txt)
return "\n\n".join(lines).strip() + "\n"
def dump_json(path: Path, data: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
def block_to_dict(block: Block) -> dict[str, Any]:
return asdict(block)
+83
View File
@@ -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}
+567
View File
@@ -0,0 +1,567 @@
from __future__ import annotations
import base64
import hashlib
import io
import json
import os
import re
import shutil
from dataclasses import asdict, replace
from pathlib import Path
from urllib.parse import quote, urlparse
from edkb_system.contracts import Block, Chunk, Context
def _write(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
_EMBEDDED_IMG_RE = re.compile(
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/(?P<fmt>[a-zA-Z0-9.+-]+);base64,(?P<b64>[^)]+))\)",
re.IGNORECASE | re.DOTALL,
)
_EMBEDDED_IMG_LOOSE_RE = re.compile(
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/[^)]*)\)",
re.IGNORECASE | re.DOTALL,
)
_EMBEDDED_IMG_ANY_RE = re.compile(
r"!\[[^\]]*\]\(data:image/.*?\)",
re.IGNORECASE | re.DOTALL,
)
_KEEP_IMAGE = "__KEEP_EMBEDDED_IMAGE__"
_DROP_IMAGE = "__DROP_EMBEDDED_IMAGE__"
def _bool_env(name: str, default: bool) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "on"}
def _sanitize_segment(raw: str) -> str:
s = (raw or "").strip()
if not s:
return "untitled"
s = re.sub(r"\s+", "_", s)
s = s.replace("/", "_").replace("\\", "_")
s = re.sub(r"[:*?\"<>|]", "_", s)
s = re.sub(r"_+", "_", s).strip("._")
return s or "untitled"
def _build_object_prefix(
source_category: str, source_rel_path: str, source_file: str
) -> str:
rel = (source_rel_path or source_file or "document").replace("\\", "/").strip("/")
parts = [p for p in rel.split("/") if p and p not in {".", ".."}]
category = _sanitize_segment(source_category)
if not category:
if len(parts) >= 2:
category = _sanitize_segment(parts[0])
else:
category = "uncategorized"
if parts and _sanitize_segment(parts[0]) == category:
parts = parts[1:]
if parts:
doc_parts = parts[:-1] + [Path(parts[-1]).stem or "document"]
else:
doc_parts = [Path(source_file or "document").stem or "document"]
normalized = [category] + [_sanitize_segment(p) for p in doc_parts]
normalized = [p for p in normalized if p]
return "/".join(normalized)
def _normalize_endpoint(raw_endpoint: str) -> tuple[str, bool]:
endpoint = (raw_endpoint or "").strip()
secure_default = False
if "://" in endpoint:
parsed = urlparse(endpoint)
secure_default = parsed.scheme.lower() == "https"
endpoint = parsed.netloc or parsed.path
endpoint = endpoint.strip().rstrip("/")
return endpoint, secure_default
def _normalize_public_base(raw_base: str, endpoint: str, secure: bool) -> str:
base = (raw_base or "").strip().rstrip("/")
if not base:
scheme = "https" if secure else "http"
return f"{scheme}://{endpoint}".rstrip("/")
if "://" not in base:
scheme = "https" if secure else "http"
return f"{scheme}://{base}".rstrip("/")
return base.rstrip("/")
def _quote_object_name(object_name: str) -> str:
return "/".join(quote(seg, safe="") for seg in object_name.split("/"))
def _ext_from_blob(blob: bytes) -> str | None:
if blob.startswith(b"\x89PNG\r\n\x1a\n"):
return "png"
if blob.startswith(b"\xff\xd8\xff"):
return "jpg"
if blob.startswith((b"GIF87a", b"GIF89a")):
return "gif"
if blob.startswith(b"BM"):
return "bmp"
if len(blob) >= 12 and blob[:4] == b"RIFF" and blob[8:12] == b"WEBP":
return "webp"
return None
def _normalize_ext(fmt: str, blob: bytes) -> str:
f = (fmt or "").lower().strip()
if f in {"jpeg", "jpg"}:
return "jpg"
if f in {"png", "gif", "bmp", "webp"}:
return f
guessed = _ext_from_blob(blob)
return guessed or "png"
def _content_type_for_ext(ext: str) -> str:
if ext == "jpg":
return "image/jpeg"
if ext == "png":
return "image/png"
if ext == "gif":
return "image/gif"
if ext == "bmp":
return "image/bmp"
if ext == "webp":
return "image/webp"
return "application/octet-stream"
def _is_valid_image_blob(blob: bytes) -> bool:
if len(blob) < 8:
return False
if _ext_from_blob(blob):
return True
# Unknown format fallback: keep only if not tiny garbage.
return len(blob) >= 64
class _MinioStorage:
def __init__(
self,
*,
endpoint: str,
bucket_name: str,
access_key: str,
secret_key: str,
secure: bool,
public_base: str,
) -> None:
import importlib
minio_mod = importlib.import_module("minio")
minio_ctor = getattr(minio_mod, "Minio")
self.bucket_name = bucket_name
self.public_base = public_base.rstrip("/")
self.client = minio_ctor(
endpoint,
access_key=access_key,
secret_key=secret_key,
secure=secure,
)
if not self.client.bucket_exists(bucket_name):
self.client.make_bucket(bucket_name)
def put_bytes(self, object_name: str, blob: bytes, content_type: str) -> None:
stream = io.BytesIO(blob)
self.client.put_object(
self.bucket_name,
object_name,
stream,
len(blob),
content_type=content_type,
)
def list_prefix(self, prefix: str) -> list[str]:
return [
obj.object_name
for obj in self.client.list_objects(
self.bucket_name,
prefix=prefix,
recursive=True,
)
]
def remove_object(self, object_name: str) -> None:
self.client.remove_object(self.bucket_name, object_name)
def build_url(self, object_name: str) -> str:
return (
f"{self.public_base}/{self.bucket_name}/{_quote_object_name(object_name)}"
)
class _RemoteImageRewriter:
def __init__(
self,
*,
context: Context,
source_file: str,
source_rel_path: str,
source_category: str,
) -> None:
self.context = context
self.source_file = source_file
self.source_rel_path = source_rel_path
self.source_category = source_category
self.object_prefix = _build_object_prefix(
source_category, source_rel_path, source_file
)
self.allow_embed_fallback = _bool_env("MINIO_ALLOW_EMBED_FALLBACK", False)
self.storage: _MinioStorage | None = None
self._storage_initialized = False
self.uri_cache: dict[str, str] = {}
self.sha_cache: dict[str, tuple[str, str]] = {}
self.referenced_objects: set[str] = set()
self.uploaded_count = 0
self.reused_count = 0
self.invalid_removed_count = 0
self.kept_embedded_count = 0
self.stale_removed_count = 0
self._upload_error_warn_count = 0
self._saw_embedded_image = False
self._next_image_index = 1
def _build_storage(self) -> _MinioStorage | None:
if not _bool_env("MINIO_UPLOAD_ENABLED", True):
if self.allow_embed_fallback:
self.context.warnings.append(
"image-hosting disabled by MINIO_UPLOAD_ENABLED"
)
return None
raise RuntimeError("image-hosting disabled by MINIO_UPLOAD_ENABLED")
endpoint_raw = os.getenv("MINIO_ENDPOINT", "127.0.0.1:9000")
endpoint, secure_default = _normalize_endpoint(endpoint_raw)
secure = _bool_env("MINIO_SECURE", secure_default)
if not endpoint:
if self.allow_embed_fallback:
self.context.warnings.append(
"image-hosting disabled: MINIO_ENDPOINT is empty"
)
return None
raise RuntimeError("image-hosting disabled: MINIO_ENDPOINT is empty")
bucket_name = os.getenv("MINIO_BUCKET", "image-hosting-service")
access_key = os.getenv("MINIO_ACCESS_KEY", "admin")
secret_key = os.getenv("MINIO_SECRET_KEY", "difyai123456")
public_base = _normalize_public_base(
os.getenv("MINIO_PUBLIC_BASE_URL", ""), endpoint, secure
)
try:
return _MinioStorage(
endpoint=endpoint,
bucket_name=bucket_name,
access_key=access_key,
secret_key=secret_key,
secure=secure,
public_base=public_base,
)
except Exception as exc:
if self.allow_embed_fallback:
self.context.warnings.append(
f"image-hosting unavailable, keep embedded image: {exc}"
)
return None
raise RuntimeError(f"image-hosting unavailable: {exc}")
def _warn_upload_error(self, msg: str) -> None:
if self._upload_error_warn_count < 5:
self.context.warnings.append(msg)
self._upload_error_warn_count += 1
def _ensure_storage(self) -> None:
if self._storage_initialized:
return
self.storage = self._build_storage()
self._storage_initialized = True
def _process_embedded_uri(self, uri: str, fmt: str, b64_raw: str) -> str:
cached = self.uri_cache.get(uri)
if cached is not None:
return cached
fmt = (fmt or "png").lower()
b64_clean = re.sub(r"\s+", "", b64_raw)
try:
blob = base64.b64decode(b64_clean, validate=False)
except Exception:
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
if not _is_valid_image_blob(blob):
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
self._ensure_storage()
if self.storage is None:
if not self.allow_embed_fallback:
raise RuntimeError(
"image-hosting unavailable: embedded fallback is disabled"
)
self.kept_embedded_count += 1
self.uri_cache[uri] = _KEEP_IMAGE
return _KEEP_IMAGE
sha = hashlib.sha256(blob).hexdigest()
cached_sha = self.sha_cache.get(sha)
if cached_sha is not None:
url, object_name = cached_sha
self.referenced_objects.add(object_name)
self.reused_count += 1
self.uri_cache[uri] = url
return url
ext = _normalize_ext(fmt, blob)
content_type = _content_type_for_ext(ext)
file_name = f"img_{self._next_image_index:03d}_{sha[:8]}.{ext}"
self._next_image_index += 1
object_name = (
f"{self.object_prefix}/{file_name}" if self.object_prefix else file_name
)
try:
self.storage.put_bytes(object_name, blob, content_type)
url = self.storage.build_url(object_name)
self.sha_cache[sha] = (url, object_name)
self.referenced_objects.add(object_name)
self.uploaded_count += 1
self.uri_cache[uri] = url
return url
except Exception as exc:
if not self.allow_embed_fallback:
raise RuntimeError(
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
) from exc
self.kept_embedded_count += 1
self.uri_cache[uri] = _KEEP_IMAGE
self._warn_upload_error(
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
)
return _KEEP_IMAGE
def _process_match(self, m: re.Match[str]) -> str:
return self._process_embedded_uri(
m.group("uri"),
m.group("fmt") or "png",
m.group("b64") or "",
)
def _process_loose_uri(self, uri: str) -> str:
cached = self.uri_cache.get(uri)
if cached is not None:
return cached
head, sep, b64_raw = uri.partition(",")
if not sep:
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
fmt = "png"
m = re.match(r"^data:image/(?P<fmt>[a-zA-Z0-9.+-]+)", head, re.IGNORECASE)
if m:
fmt = (m.group("fmt") or "png").lower()
return self._process_embedded_uri(uri, fmt, b64_raw)
def replace_text(self, text: str) -> str:
if not text or "data:image/" not in text:
return text
self._saw_embedded_image = True
def repl(m: re.Match[str]) -> str:
alt = m.group("alt") or "image"
decision = self._process_match(m)
if decision == _DROP_IMAGE:
return ""
if decision == _KEEP_IMAGE:
return m.group(0)
return f"![{alt}]({decision})"
out = _EMBEDDED_IMG_RE.sub(repl, text)
if "data:image/" in out:
def loose_repl(m: re.Match[str]) -> str:
alt = m.group("alt") or "image"
decision = self._process_loose_uri(m.group("uri") or "")
if decision == _DROP_IMAGE:
return ""
if decision == _KEEP_IMAGE:
return m.group(0)
return f"![{alt}]({decision})"
out = _EMBEDDED_IMG_LOOSE_RE.sub(loose_repl, out)
if not self.allow_embed_fallback and "data:image/" in out:
dropped_before = self.invalid_removed_count
out = _EMBEDDED_IMG_LOOSE_RE.sub("", out)
out = _EMBEDDED_IMG_ANY_RE.sub("", out)
removed = self.invalid_removed_count - dropped_before
if "data:image/" in out:
self.context.warnings.append(
"image-hosting left non-markdown data:image content; kept as-is"
)
else:
self.context.warnings.append(
"image-hosting removed unsupported embedded images"
+ (f": {removed}" if removed > 0 else "")
)
out = re.sub(r"(?:\s*<br>\s*){2,}", " <br> ", out)
return out
def finalize(self) -> None:
if self._saw_embedded_image and _bool_env("MINIO_CLEANUP_STALE", True):
self._ensure_storage()
if self.storage is not None and _bool_env("MINIO_CLEANUP_STALE", True):
prefix = f"{self.object_prefix}/"
try:
for object_name in self.storage.list_prefix(prefix):
if object_name in self.referenced_objects:
continue
self.storage.remove_object(object_name)
self.stale_removed_count += 1
except Exception as exc:
self.context.warnings.append(
f"image-hosting cleanup failed ({self.source_file}): {exc}"
)
if self.invalid_removed_count > 0:
self.context.warnings.append(
f"image-hosting removed invalid images: {self.invalid_removed_count}"
)
if self.kept_embedded_count > 0 and self.storage is None:
self.context.warnings.append(
"image-hosting unavailable: keep legacy data:image embeds"
)
if (
self.uploaded_count > 0
or self.reused_count > 0
or self.stale_removed_count > 0
):
self.context.warnings.append(
"image-hosting synced "
f"(uploaded={self.uploaded_count}, reused={self.reused_count}, "
f"stale_removed={self.stale_removed_count}, prefix={self.object_prefix})"
)
def run(input_data: dict, context: Context) -> dict:
out_dir = Path(input_data["out_dir"])
out_dir.mkdir(parents=True, exist_ok=True)
source_file = input_data.get("source_file", "")
source_rel_path = input_data.get("source_rel_path", source_file)
source_category = input_data.get("source_category", "")
source_stem = Path(source_file).stem if source_file else out_dir.name
flat_clean_path = Path(
input_data.get("flat_md_path", out_dir.parent / f"{source_stem}.md")
)
view_clean_path = out_dir / "03_clean_view.md"
view_images_dir = out_dir / "images_view"
for p in [
out_dir / "01_raw_layout.json",
out_dir / "02_flow_procedure.md",
out_dir / "03_clean.md",
out_dir / "04_chunks.jsonl",
out_dir / "report.md",
view_clean_path,
flat_clean_path,
]:
if p.exists():
p.unlink()
chunks_dir = out_dir / "chunks"
if chunks_dir.exists():
shutil.rmtree(chunks_dir)
if view_images_dir.exists():
shutil.rmtree(view_images_dir)
clean_md: str = input_data.get("clean_md", "")
chunks: list[Chunk] = input_data.get("chunks", [])
blocks: list[Block] = input_data.get("blocks", [])
flow_markdowns: list[str] = input_data.get("flow_markdowns", [])
rewriter = _RemoteImageRewriter(
context=context,
source_file=source_file,
source_rel_path=source_rel_path,
source_category=source_category,
)
clean_md = rewriter.replace_text(clean_md)
exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks]
rewriter.finalize()
_write(out_dir / "03_clean.md", clean_md)
_write(flat_clean_path, clean_md)
lines = [json.dumps(asdict(c), ensure_ascii=False) for c in exported_chunks]
_write(out_dir / "04_chunks.jsonl", "\n".join(lines) + ("\n" if lines else ""))
chunks_dir.mkdir(parents=True, exist_ok=True)
for c in exported_chunks:
_write(chunks_dir / f"chunk_{c.index:04d}.md", c.text + "\n")
if flow_markdowns:
_write(out_dir / "02_flow_procedure.md", "\n\n".join(flow_markdowns) + "\n")
_write(
out_dir / "01_raw_layout.json",
json.dumps([asdict(b) for b in blocks], ensure_ascii=False, indent=2) + "\n",
)
report_lines = [
f"# Report: {input_data.get('source_file', '')}",
"",
f"- pages: {context.pages}",
f"- images: {context.images}",
f"- ocr_characters: {context.ocr_characters}",
f"- flows_detected: {context.flows_detected}",
f"- confidence: {context.confidence:.2f}",
"",
"## warnings",
]
if context.warnings:
report_lines.extend([f"- {w}" for w in context.warnings])
else:
report_lines.append("- none")
report_lines.extend(
[
"",
"## recommended_dify_settings",
"- Index: High Quality",
"- Retrieval: Hybrid",
"- Chunking: General",
"",
]
)
_write(out_dir / "report.md", "\n".join(report_lines))
return {"out_dir": str(out_dir)}
@@ -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}
+419
View File
@@ -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,
)
+39
View File
@@ -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
+250
View File
@@ -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
+478
View File
@@ -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
+97
View File
@@ -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
+192
View File
@@ -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"
+249
View File
@@ -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))
+4
View File
@@ -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')
+14
View File
@@ -17,3 +17,17 @@ PyJWT
cryptography
oracledb
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
+44
View File
@@ -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'
+400
View File
@@ -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')
+47
View File
@@ -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()
+75 -5
View File
@@ -1,4 +1,19 @@
services:
# ==============================================================================
# kb-redis: 知识库任务/后续异步能力预留的 Redis 服务
# ==============================================================================
kb-redis:
image: ${KB_REDIS_IMAGE:-redis:7-alpine}
container_name: hxops-kb-redis
restart: always
profiles:
- kb-redis
command: ["redis-server", "--appendonly", "yes"]
volumes:
- hxops_redis_data:/data
networks:
- ai-platform
# ==============================================================================
# hxops-backend: Flask 后端服务 (端口: 5000)
# ==============================================================================
@@ -7,25 +22,73 @@ services:
build:
context: ./backend
dockerfile: Dockerfile
args:
PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim}
PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple}
PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-}
container_name: hxops-backend
restart: always
env_file:
- ./backend/.env
environment:
# 数据库连接 (在环境变量中配置)
- DATABASE_URL=${DATABASE_URL}
- FLASK_APP=${FLASK_APP:-run.py}
- FLASK_ENV=${FLASK_ENV:-production}
# backend/.env 提供默认值;如需容器内覆盖数据库地址,可在启动前临时设置 shell 中的 DATABASE_URL。
DATABASE_URL:
SECRET_KEY:
FLASK_APP: ${FLASK_APP:-run.py}
FLASK_ENV: ${FLASK_ENV:-production}
REDIS_URL: ${REDIS_URL:-redis://kb-redis:6379/0}
KB_STORAGE_ROOT: ${KB_STORAGE_ROOT:-/app/data/kb}
KB_TASK_EXECUTION_MODE: ${KB_TASK_EXECUTION_MODE:-worker}
KB_WORKER_POLL_SECONDS: ${KB_WORKER_POLL_SECONDS:-2}
# 允许容器访问宿主机服务 (如数据库)
extra_hosts:
- "host.docker.internal:host-gateway"
# 如果需要在宿主机调试,可暴露端口;生产环境建议只在网络内暴露
ports:
- "5002:5002"
- "5002:5000"
# 持久化运行时可写文件:
# - backend/.env 用于保存管理员后台修改的企业微信等配置(与数据库双写,
# 防止容器重建后从镜像基线读取丢失修改)。文件不存在时 docker 会自动
# 把它当作目录挂载,因此先确保宿主机上存在该文件再启动。
volumes:
- ./backend/.env:/app/.env
- hxops_runtime_data:/app/data
networks:
- ai-platform
# ==============================================================================
# hxops-kb-worker: 知识库清洗/同步最小 worker
# ==============================================================================
hxops-kb-worker:
image: ${BACKEND_IMAGE:-hxops-backend:local}
build:
context: ./backend
dockerfile: Dockerfile
args:
PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim}
PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple}
PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-}
container_name: hxops-kb-worker
restart: always
command: ["python", "worker_kb.py"]
depends_on:
- hxops-backend
env_file:
- ./backend/.env
environment:
DATABASE_URL:
SECRET_KEY:
FLASK_APP: ${FLASK_APP:-run.py}
FLASK_ENV: ${FLASK_ENV:-production}
REDIS_URL: ${REDIS_URL:-redis://kb-redis:6379/0}
KB_STORAGE_ROOT: ${KB_STORAGE_ROOT:-/app/data/kb}
KB_TASK_EXECUTION_MODE: ${KB_TASK_EXECUTION_MODE:-worker}
KB_WORKER_POLL_SECONDS: ${KB_WORKER_POLL_SECONDS:-2}
extra_hosts:
- "host.docker.internal:host-gateway"
volumes:
- ./backend/.env:/app/.env
- hxops_runtime_data:/app/data
networks:
- ai-platform
@@ -37,6 +100,9 @@ services:
build:
context: ./frontend
dockerfile: Dockerfile
args:
NODE_BASE_IMAGE: ${NODE_BASE_IMAGE:-node:22-alpine}
NGINX_BASE_IMAGE: ${NGINX_BASE_IMAGE:-nginx:alpine}
container_name: hxops-frontend
restart: always
depends_on:
@@ -54,3 +120,7 @@ networks:
ai-platform:
name: ai-platform
driver: bridge
volumes:
hxops_runtime_data:
hxops_redis_data:
+171
View File
@@ -0,0 +1,171 @@
# 主平台知识库运行时部署说明
## 目标
将知识库上传、清洗、Dify 同步运行时统一收敛到主平台 `hxops&xinxin`,不再依赖 `xinxin2` 独立运行 `api + worker + redis`。
当前主平台 `docker-compose.yml` 已接入:
- `kb-redis`
- `hxops-backend`
- `hxops-kb-worker`
- `hxops-frontend`
- 共享卷 `hxops_runtime_data`
## 容器职责
### `hxops-backend`
- 提供主平台 API
- 提供知识库 API:`/api/kb/*`
- 提供集成 API:`/api/integration/*`
- 挂载知识库存储根目录到 `/app/data`
### `hxops-kb-worker`
- 轮询执行知识库 `clean` 任务
- 复用后端镜像,避免维护第二套依赖
- 与后端共享数据库、Redis、知识库存储卷
### `kb-redis`
- 提供知识库异步任务所需 Redis
- 当前主要用于主平台知识库运行时接入与后续队列化扩展
## 关键环境变量
部署主平台知识库运行时时,至少确认以下变量:
| 变量名 | 用途 | 建议值/说明 |
| --- | --- | --- |
| `DATABASE_URL` | 主平台数据库连接 | 指向当前主平台生产库 |
| `SECRET_KEY` | Flask/JWT 密钥 | 使用足够长的随机字符串 |
| `REDIS_URL` | 知识库 Redis 连接 | 默认可用 `redis://kb-redis:6379/0` |
| `KB_STORAGE_ROOT` | 知识库文件根目录 | 容器内建议保持 `/app/data/kb` |
| `KB_TASK_EXECUTION_MODE` | 任务执行模式 | 生产建议 `worker` |
| `KB_WORKER_POLL_SECONDS` | worker 轮询间隔 | 默认 `2` 即可 |
| `INTEGRATION_API_MODE` | 聊天侧集成调用模式 | 主平台自承载时建议 `local` |
| `WECOM_PUBLIC_BASE_URL` | 对外可访问主平台地址 | 供聊天/企业微信/文件回链生成绝对地址 |
| `DIFY_API_BASE` | Dify API 地址 | 按现网环境填写 |
| `DIFY_API_KEY` | Dify API Key | 由管理端保存后可持久化到 `.env`/数据库 |
| `KB_REDIS_IMAGE` | Redis 镜像来源 | 默认 `redis:7-alpine`,内网可改为私有仓库地址 |
| `PYTHON_BASE_IMAGE` | 后端基础镜像 | 默认 `python:3.12-slim`,内网可改为私有仓库地址 |
| `NODE_BASE_IMAGE` | 前端构建基础镜像 | 默认 `node:22-alpine` |
| `NGINX_BASE_IMAGE` | 前端运行基础镜像 | 默认 `nginx:alpine` |
| `PIP_INDEX_URL` | 后端 pip 主镜像源 | 可指向国内或内网 PyPI 镜像 |
| `PIP_EXTRA_INDEX_URL` | 后端 pip 额外镜像源 | 用于补充私有或备用源 |
补充说明:
- 宿主机应先创建 `backend/.env` 文件,再执行 `docker compose up`,避免 Docker 将目标当作目录挂载。
- 当前 `docker-compose.yml` 不再从宿主机 shell 强依赖 `DATABASE_URL`,而是由容器内挂载的 `backend/.env` 提供数据库连接与密钥。
- 若当前环境无法访问 Docker Hub,可在执行前设置 `KB_REDIS_IMAGE`,例如改为企业私有仓库中的 Redis 镜像。
- 若当前环境无法访问 Docker Hub,也可同时设置 `PYTHON_BASE_IMAGE`、`NODE_BASE_IMAGE`、`NGINX_BASE_IMAGE`,把后端/前端基础镜像切到企业私有仓库。
- 若后端 `pip install -r requirements.txt` 速度过慢或不稳定,可设置 `PIP_INDEX_URL` / `PIP_EXTRA_INDEX_URL`。
- 若要沿用旧 `xinxin2` 文件目录,切换前需先把历史知识库文件迁入主平台卷,并保证 `KB_STORAGE_ROOT` 指向迁移后的新路径。
- 若仍要调用外部 integration API,才需要配置 `INTEGRATION_API_BASE` 与 `INTEGRATION_API_KEY`,此时 `INTEGRATION_API_MODE` 设为 `external`。
- 当前知识库主链路的 `worker_kb` 轮询数据库即可工作,`kb-redis` 以 profile 方式保留,用于后续异步队列扩展或外接 Redis 场景。
## 启动步骤
### 1. 构建并启动
```bash
docker compose up -d --build
```
若使用私有镜像仓库,可先设置:
```bash
$env:KB_REDIS_IMAGE = "your-registry.example.com/library/redis:7-alpine"
$env:PYTHON_BASE_IMAGE = "your-registry.example.com/library/python:3.12-slim"
$env:NODE_BASE_IMAGE = "your-registry.example.com/library/node:22-alpine"
$env:NGINX_BASE_IMAGE = "your-registry.example.com/library/nginx:alpine"
$env:PIP_INDEX_URL = "https://pypi.tuna.tsinghua.edu.cn/simple"
docker compose up -d --build
```
若需要同时启用内置 Redis,再改为:
```bash
docker compose --profile kb-redis up -d --build
```
### 2. 执行数据库迁移
```bash
docker compose exec hxops-backend flask db upgrade
```
### 3. 检查服务状态
```bash
docker compose ps
```
预期:
- `hxops-backend` 为 `Up`
- `hxops-kb-worker` 为 `Up`
- `hxops-frontend` 为 `Up`
若启用了 `kb-redis` profile,则额外确认:
- `kb-redis` 为 `Up`
### 4. 检查 worker 日志
```bash
docker compose logs -f hxops-kb-worker
```
预期可见:
```text
[kb-worker] started, poll_seconds=2.0
```
## 端口与卷
当前主平台容器端口关系:
- 宿主机 `5002` -> `hxops-backend:5000`
- 宿主机 `8890` -> `hxops-frontend:80`
当前关键卷:
- `hxops_runtime_data`:主平台运行时可写数据,包含知识库存储目录
- `hxops_redis_data`:Redis 持久化数据
## 切换前检查
切换 `xinxin2` 运行时前,至少确认:
1. 主平台已完成数据库迁移
2. 主平台后台可正常打开知识库管理页
3. 上传文件后会生成 `upload/clean` 任务
4. `hxops-kb-worker` 能持续消费待执行任务
5. Dify 设置已在主平台管理端保存并通过健康检查
6. 聊天侧 `INTEGRATION_API_MODE=local`
7. `WECOM_PUBLIC_BASE_URL` 对应外部真实可访问域名
## 切换后冒烟清单
建议按顺序验证:
1. 登录主平台并进入知识库工作台
2. 新建一个分组和一个文档条目
3. 上传一个 `txt` 或 `md` 文件
4. 确认任务状态从 `pending/running` 进入 `success`
5. 在文档详情里触发一次 Dify 同步
6. 调用主平台 `/api/integration/dify-file` 或 `/api/integration/dify-files/resolve` 验证映射
7. 从聊天侧点击源文件链接,确认下载地址仍指向主平台
## 常见注意事项
- `hxops-backend` 容器内部监听 `5000`,宿主机映射使用 `5002:5000`;若改端口,需同步更新网关/探针配置。
- `worker_kb.py` 已按 `FLASK_ENV` 或 `APP_CONFIG` 选择配置;生产环境不要再用 `development` 配置启动 worker。
- `KB_TASK_EXECUTION_MODE=worker` 时,需要确保 `hxops-kb-worker` 运行;若临时排障切到 `sync`,应评估接口耗时影响。
- `kb-redis` 已改为可选 profile,不执行 `docker compose --profile kb-redis ...` 时不会默认拉起。
- `backend/.env` 与数据库配置存在持久化联动,重建容器前不要误删该文件。
- `SECRET_KEY` 过短会导致 JWT/HMAC 安全性不足,生产必须替换为长随机值。
+213
View File
@@ -0,0 +1,213 @@
# `xinxin2` 迁移收尾清单(第一版)
## 目标
将 `xinxin2` 从“独立运行的文档清洗平台”收敛为:
- 代码能力已并入 `hxops&xinxin`
- 登录入口统一使用 `hxops&xinxin`
- 聊天侧与外部系统优先访问 `hxops&xinxin` 的知识库与集成 API
- `xinxin2` 仅在少量未切换的部署职责上临时保留
## 当前已完成的迁移能力
主平台 `hxops&xinxin` 当前已经具备以下能力:
- 知识库分组管理
- 文档条目管理
- 文件上传
- 文档版本记录
- 自动 `clean` 任务执行
- `edkb_system` 轻量接入
- Dify 同步第一版
- Dify 设置与健康检查面板
- `/api/integration/*` 集成查询接口
- 聊天侧默认优先指向主平台自身 integration API
- 基础回归测试:分组/文档/上传/同步/集成 API
## 结论摘要
### 可立即下线
这些入口已经被主平台完全替代,继续保留只会造成双入口混淆:
| `xinxin2` 项 | 当前状态 | 处理建议 |
| --- | --- | --- |
| `frontend/src/views/LoginView.vue` | 已由主平台登录替代 | 停用 |
| `frontend/src/lib/auth.ts` | 已由主平台鉴权替代 | 停用 |
| `frontend/src/main.ts` | 不再需要独立前端入口 | 停用 |
| `frontend/src/router/index.ts` | 不再需要独立路由壳 | 停用 |
| `backend/app/api/auth.py` | 不再需要独立登录 API | 停用 |
| `backend/app/main.py` | 不再需要独立 FastAPI 入口 | 停用 |
| `start-local-frontend.ps1` | 不再需要独立前端启动 | 停用 |
| `start-local-dev.ps1` | 不再需要独立双进程启动 | 停用 |
### 待切换后下线
这些职责在主平台里已有对应实现,但部署或调用方还需要完成切换:
| `xinxin2` 项 | 当前替代物 | 下线前条件 |
| --- | --- | --- |
| `backend/app/api/integration.py` | `hxops&xinxin/backend/app/api/integration.py` | 确认所有调用方都改指向主平台 |
| `frontend/src/views/WorkspaceView.vue` | `hxops&xinxin/frontend/src/views/KbWorkspaceView.vue` | 用户不再访问 `8891` 前端 |
| `frontend/src/views/AdminView.vue` | `hxops&xinxin/frontend/src/views/KbAdminView.vue` | 管理员改从主平台进入 |
| `backend/app/api/groups.py` | `hxops&xinxin/backend/app/api/knowledge_base.py` | 验证分组管理不再依赖旧服务 |
| `backend/app/api/files.py` | 主平台 `knowledge_base.py` 已覆盖核心主链路 | 如需高级下载/批量功能,先补齐后再停 |
| `backend/app/tasks.py` | `hxops&xinxin/backend/app/services/knowledge_cleaning/tasks.py` | 生产环境切到主平台 worker/sync 模式 |
| `backend/worker.py` | `hxops&xinxin/backend/worker_kb.py` | 主平台部署接入 worker 后再停 |
### 暂时保留
这些项暂时还建议保留,不是因为业务没迁,而是因为主平台部署面还没完全接住:
| `xinxin2` 项 | 暂时保留原因 | 建议 |
| --- | --- | --- |
| `docker-compose.yml` | 主平台已补 `redis` / `worker_kb` / 知识库存储卷,但切换后仍需观察一段时间 | 切换稳定后再停 |
| `backend/Dockerfile` | 主平台镜像未完全吸收文档清洗依赖时,仍是参考来源 | 保留作为迁移参考 |
| `start-local-backend.ps1` | 主平台本地脚本还未完全覆盖知识库依赖检查 | 保留到本地开发文档更新完成 |
| `backend/edkb_system/*` 原仓库副本 | 主平台已轻量接入,但若要完全停旧仓库,需要确认无外部脚本再直接引用旧路径 | 短期保留 |
| `backend/tests/*` | 主平台只补了核心主链路测试,尚未完整迁入所有旧测试 | 保留到测试迁移完成 |
## 当前最大阻塞
### 阻塞 1:主平台生产部署已接住知识库运行时,但仍需完成切换验证
当前主平台 `docker-compose.yml` 已新增:
- `kb-redis`
- `hxops-backend`
- `hxops-kb-worker`
- `hxops-frontend`
- `hxops_runtime_data`
- `hxops_redis_data`
影响:
- 现在的重点已从“补部署件”转为“验证切换链路”
- 如果线上有专门的 `8891` 文件存储目录,切换前仍要确认主平台 `KB_STORAGE_ROOT` 已指向迁移后的新位置
- 若要正式下线旧 worker,需观察主平台 `hxops-kb-worker` 实际消费任务是否稳定
### 阻塞 2:调用方地址切换要做最终确认
虽然聊天侧已经默认优先用主平台自身 `/api/integration/*`,但仍建议确认:
- `INTEGRATION_API_MODE=local`
- `WECOM_PUBLIC_BASE_URL` 正确配置
- 旧的 `INTEGRATION_API_BASE` 不再被外部系统直接依赖
### 阻塞 3:部分高级能力仍是“第一版”
当前主平台已跑通主链路,但以下能力仍属于增强项,不建议在未验证前立刻删除旧仓库参考:
- 更完整的 `edkb_system` skill 支持
- 批量下载与更多文件格式处理
- 完整异步队列化执行策略
- 更完整的 Dify diff / import 行为
## 建议的切换顺序
### 第一步:停独立入口
先停掉所有“用户可见的独立入口”:
- `xinxin2` 独立登录页
- `xinxin2` 独立前端 Vite 本地启动
- `xinxin2` 独立前端对外访问入口
判定标准:
- 用户和管理员都只从 `hxops&xinxin` 访问知识库模块
### 第二步:切集成地址
确认聊天链路和外部系统都使用主平台集成接口:
- `/api/integration/dify-file`
- `/api/integration/dify-files/resolve`
- `/api/integration/files/<id>/download`
判定标准:
- 旧 `xinxin2` 集成 API 日志无实际流量
### 第三步:切运行时
把知识库运行时职责切到主平台:
- 在主平台 compose 中加入 `redis`
- 在主平台 compose 中加入 `worker_kb`
- 确认 `KB_STORAGE_ROOT` 与卷映射
判定标准:
- 上传、自动 clean、sync_dify 都在主平台运行完成
### 第四步:停旧后端服务
当以下条件同时满足时,可停 `xinxin2` 的 `api` / `worker`:
- 主平台知识库 API 正常
- 主平台 integration API 正常
- 主平台 worker 正常
- 旧服务近一段时间无流量或仅剩探测流量
## 具体可下线项清单
### 现在就可以停
- `xinxin2/frontend/src/views/LoginView.vue`
- `xinxin2/frontend/src/lib/auth.ts`
- `xinxin2/frontend/src/main.ts`
- `xinxin2/frontend/src/router/index.ts`
- `xinxin2/backend/app/api/auth.py`
- `xinxin2/backend/app/main.py`
- `xinxin2/start-local-frontend.ps1`
- `xinxin2/start-local-dev.ps1`
### 完成部署切换后可停
- `xinxin2/frontend/Dockerfile`
- `xinxin2/frontend/src/views/WorkspaceView.vue`
- `xinxin2/frontend/src/views/AdminView.vue`
- `xinxin2/backend/app/api/groups.py`
- `xinxin2/backend/app/api/files.py`
- `xinxin2/backend/app/api/integration.py`
- `xinxin2/backend/app/tasks.py`
- `xinxin2/backend/worker.py`
- `xinxin2/docker-compose.yml`
### 暂时保留参考
- `xinxin2/backend/edkb_system/*`
- `xinxin2/backend/tests/*`
- `xinxin2/project-governance/*`
- `xinxin2/README.md`
- `xinxin2/EXTERNAL-INTEGRATION-API.md`
## 建议新增的主平台收尾工作
为了真正完成下线,主平台还建议补这几项:
- 观察主平台 `worker_kb` 切换后一段时间的稳定性
- 为知识库模块补部署文档(见 `docs/knowledge_base_runtime_deploy.md`)
- 在主平台 README 或 docs 中补本地运行步骤
- 继续迁移 `xinxin2` 测试到主平台 `backend/tests/`
- 补一版“切换完成后的 smoke checklist”
## 切换完成判定
满足以下条件,可认为 `xinxin2` 已完成业务下线:
- 用户只从 `hxops&xinxin` 登录和使用知识库
- 聊天侧 source 文件映射只访问主平台 integration API
- 文档上传、clean、sync 都由主平台完成
- 主平台部署已具备所需 worker/存储能力
- `xinxin2` 的外部访问流量归零
## 当前建议
下一步优先做:
1. 按 `docs/knowledge_base_runtime_deploy.md` 完成一轮主平台知识库运行时冒烟验证
2. 观察主平台 `worker_kb`、`/api/integration/*` 与文件下载链路是否稳定
3. 再决定是否正式停掉 `xinxin2` 的 `api/worker/frontend`
+238
View File
@@ -0,0 +1,238 @@
# `xinxin2` 正式下线执行文档
## 文档目标
用于记录 `xinxin2` 向主平台 `hxops&xinxin` 完成迁移后的正式下线执行方案、当前实机执行结果、回滚预案与生产切换注意事项。
## 当前结论
当前主平台 `hxops&xinxin` 已实机跑通以下完整链路:
- 知识库分组创建
- 文档创建
- 文件上传
- 自动 `clean`
- 同步到本地 Dify
- `/api/integration/files/*`
- `/api/integration/dify-file`
- 源文件与 Markdown 下载
本地环境当前结论:
- `xinxin2` 已满足下线条件
- 主平台已具备替代 `xinxin2` 的完整知识库主链路能力
- 生产环境正式切换前,仅需把本地测试用公开地址替换为真实可访问域名
## 本次实机执行结果
### 1. 主平台状态
当前正在运行:
- `hxops-backend`
- `hxops-kb-worker`
- `hxops-frontend`
- `hxops-kb-redis`
当前已验证:
- 前端访问正常:`http://127.0.0.1:8890/`
- 后端访问正常:`http://127.0.0.1:5002/`
- 知识库上传/清洗/同步/集成接口全部通过
### 2. Dify 测试配置
当前本地测试使用:
- `DIFY_API_BASE=http://host.docker.internal/v1`
- `DIFY_API_KEY=dataset-EYE6BMiJcVQ7OJEbob2K4gM1`
说明:
- 由于主平台运行在 Docker 容器中,容器内访问宿主机 Dify 不能使用 `localhost`
- 本地测试时应使用 `http://host.docker.internal/v1`
### 3. Public Base 测试配置
当前本地测试使用:
- `WECOM_PUBLIC_BASE_URL=http://127.0.0.1:5002`
作用:
- 让 `/api/integration/*` 返回的下载地址直接指向本机可访问的主平台后端
说明:
- 该值只适用于本地验证
- 生产环境必须替换为真实公网或内网可访问域名
### 4. `xinxin2` 当前运行状态
本机实机检查结果:
- `docker compose ps -a`(在 `xinxin2` 目录执行)为空
- `http://127.0.0.1:8891/` 当前不可达
结论:
- 当前机器上不存在正在运行的 `xinxin2` Docker 前端/API/worker 实例
- 因此“停止旧服务”这一步在本机已是完成状态
## 正式下线执行顺序
### 第一步:统一入口
执行项:
- 停止 `xinxin2` 独立前端入口
- 用户与管理员统一从 `hxops&xinxin` 登录
- 不再对外暴露 `8891` 知识库前端入口
判定标准:
- 用户只从主平台访问知识库
- `8891` 无用户流量
### 第二步:统一调用地址
执行项:
- 外部调用方统一切换到主平台 `/api/integration/*`
- 聊天侧继续使用主平台本地 integration API
判定标准:
- 旧 `xinxin2` integration API 流量归零
### 第三步:统一运行时
执行项:
- 使用主平台 `hxops-backend`
- 使用主平台 `hxops-kb-worker`
- 使用主平台知识库存储卷
- 使用主平台知识库 Dify 配置
判定标准:
- 上传、`clean`、`sync_dify` 都在主平台成功完成
### 第四步:停止旧后端
执行项:
- 停止 `xinxin2` worker
- 停止 `xinxin2` API
- 停止 `xinxin2` 旧 compose 服务
判定标准:
- 主平台 API、worker、integration API 持续正常
- 旧服务无有效访问流量
## 当前机器的执行状态
### 已完成
- 主平台知识库功能迁移
- 主平台 Docker 运行时接入
- 主平台 Dify 测试配置接入
- 主平台 integration API 验证
- `xinxin2` 旧前端入口不可达
- `xinxin2` compose 无运行实例
### 当前无需再执行的停机动作
在这台机器上,以下动作已无需再做:
- `docker compose stop` `xinxin2` 前端
- `docker compose stop` `xinxin2` API
- `docker compose stop` `xinxin2` worker
原因:
- 当前本机 `xinxin2` 本就未运行
## 回滚预案
若主平台切换后出现异常,可按以下顺序回滚:
1. 恢复 `xinxin2` 前端入口
2. 恢复 `xinxin2` API
3. 恢复 `xinxin2` worker
4. 将调用方 integration 地址切回旧服务
5. 验证旧链路恢复后,再排查主平台问题
## 回滚时禁止直接删除
- `xinxin2` 数据库
- `xinxin2` 历史文件目录
- `xinxin2/docker-compose.yml`
- `xinxin2/backend/tests/*`
- `xinxin2/backend/edkb_system/*`
## 生产环境切换前必改项
### 1. `WECOM_PUBLIC_BASE_URL`
本地测试值:
- `http://127.0.0.1:5002`
生产要求:
- 替换为真实公网或内网可访问域名
### 2. `DIFY_API_BASE`
本地测试值:
- `http://host.docker.internal/v1`
生产要求:
- 替换为生产环境 Dify 可访问地址
### 3. `DIFY_API_KEY`
本地测试值:
- `dataset-EYE6BMiJcVQ7OJEbob2K4gM1`
生产要求:
- 替换为生产可用的 Dify Key
### 4. 其他关键生产变量
切换前同时确认:
- `DATABASE_URL`
- `SECRET_KEY`
- `KB_STORAGE_ROOT`
- `INTEGRATION_API_MODE=local`
## 生产切换后最小冒烟清单
建议逐项验证:
1. 登录主平台知识库工作台
2. 新建分组
3. 新建文档
4. 上传 `txt` 或 `md`
5. 确认 `clean` 成功
6. 触发同步到 Dify
7. 调用 `/api/integration/dify-file`
8. 点击下载源文件与 Markdown
## 最终结论
在当前本地环境中:
- `xinxin2` 已可正式进入下线状态
- 主平台 `hxops&xinxin` 已完成替代
在生产环境中:
- 只要把本地测试配置替换为真实生产配置,即可按本执行文档推进正式切换
+14 -2
View File
@@ -151,9 +151,12 @@ docker compose up -d --build
当前对外端口映射(`docker-compose.yml`):
- 前端:`8890:80`
- 后端:`5002:5002`
- 后端:`5002:5000`
注意:当前项目中后端端口存在 `5000` 与 `5002` 并存配置,若容器联调异常,优先统一端口配置。
补充:
- 容器内后端监听 `5000`,宿主机对外暴露 `5002`
- 知识库运行时部署说明见 `docs/knowledge_base_runtime_deploy.md`
## 6. 项目登录环境与账号配置
@@ -212,13 +215,22 @@ docker compose up -d --build
| `SECRET_KEY` | Flask 密钥 | 随机长字符串 |
| `DATABASE_URL` | 数据库连接 | `postgresql://user:pwd@host:5432/db` |
| `REDIS_URL` | Redis 连接 | `redis://:pwd@host:6379/0` |
| `KB_STORAGE_ROOT` | 知识库存储根目录 | `/app/data/kb` |
| `KB_TASK_EXECUTION_MODE` | 知识库任务执行模式 | `worker` / `sync` / `manual` |
| `KB_WORKER_POLL_SECONDS` | worker 轮询间隔 | `2` |
| `KB_REDIS_IMAGE` | Redis 镜像来源 | `redis:7-alpine` 或私有仓库镜像 |
| `PYTHON_BASE_IMAGE` | 后端基础镜像 | `python:3.12-slim` 或私有仓库镜像 |
| `NODE_BASE_IMAGE` | 前端构建基础镜像 | `node:22-alpine` 或私有仓库镜像 |
| `NGINX_BASE_IMAGE` | 前端运行基础镜像 | `nginx:alpine` 或私有仓库镜像 |
| `DIFY_API_BASE` | Dify 地址 | `https://api.dify.ai/v1` |
| `DIFY_API_KEY` | Dify 密钥 | `sk-...` |
| `HR_WORKFLOW_IFRAME_URL` | HR 页面链接 | `https://...` |
| `HR_WORKFLOW_API_BASE` | HR API 地址 | `https://...` |
| `HR_WORKFLOW_API_KEY` | HR API 密钥 | `<待补>` |
| `INTEGRATION_API_MODE` | 集成 API 模式 | `local` / `external` |
| `INTEGRATION_API_BASE` | 集成 API 地址 | `https://...` |
| `INTEGRATION_API_KEY` | 集成 API 密钥 | `<待补>` |
| `WECOM_PUBLIC_BASE_URL` | 主平台公网基地址 | `https://<your-domain>` |
| `WECOM_*` | 企业微信配置 | 见第 6.4 节 |
## 8. Codex 配置方案
+5 -3
View File
@@ -1,4 +1,6 @@
FROM node:22-alpine AS builder
ARG NODE_BASE_IMAGE=node:22-alpine
ARG NGINX_BASE_IMAGE=nginx:alpine
FROM ${NODE_BASE_IMAGE} AS builder
WORKDIR /app
COPY package*.json ./
@@ -6,10 +8,10 @@ RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
FROM ${NGINX_BASE_IMAGE}
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
CMD ["nginx", "-g", "daemon off;"]
+2 -2
View File
@@ -10,8 +10,8 @@
<meta name="apple-mobile-web-app-title" content="AI工作台" />
<link rel="manifest" href="/manifest.webmanifest" />
<title>AI工作台</title>
<script type="module" crossorigin src="/assets/index-uH1T_5lG.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-CeYjUdzN.css">
<script type="module" crossorigin src="/assets/index-NHaeLCnB.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-OMOYmKxf.css">
</head>
<body>
<div id="app"></div>␍
+8 -3
View File
@@ -1,6 +1,9 @@
server {
listen 80;
server_name localhost;
client_max_body_size 100m;
resolver 127.0.0.11 valid=30s ipv6=off;
resolver_timeout 5s;
# 静态资源服务
location / {
@@ -11,9 +14,11 @@ server {
# API 代理到后端
location /api/ {
# 注意: 这里使用 Docker Compose 服务名
# 使用 /api/ 后缀确保传递完整路径
proxy_pass http://hxops-backend:5000/api/;
# 通过 Docker 内置 DNS 动态解析后端服务,避免后端容器重建后
# Nginx 继续使用启动时缓存的旧 IP 而出现 502。
set $backend_upstream hxops-backend:5000;
# 变量形式下不要附带 URI,保留原始 /api/... 路径透传给后端。
proxy_pass http://$backend_upstream;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+8 -44
View File
@@ -1,53 +1,17 @@
const CACHE_NAME = 'hxops-shell-v2';
const OFFLINE_ASSETS = ['/', '/workspace', '/manifest.webmanifest', '/vite.svg'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(OFFLINE_ASSETS)).catch(() => null)
self.skipWaiting()
);
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key))
)
)
);
self.clients.claim();
});
self.addEventListener('fetch', (event) => {
const request = event.request;
if (request.method !== 'GET') return;
const url = new URL(request.url);
if (url.origin !== self.location.origin) return;
if (url.pathname.startsWith('/api/')) return;
if (url.pathname.startsWith('/@vite/')) return;
if (url.pathname.includes('/__vite_ping')) return;
if (request.mode === 'navigate') {
event.respondWith(
fetch(request).catch(() => caches.match('/workspace').then((res) => res || caches.match('/')))
);
return;
}
event.respondWith(
caches.match(request).then((cached) => {
if (cached) return cached;
return fetch(request)
.then((response) => {
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy)).catch(() => null);
return response;
})
.catch(() => caches.match('/vite.svg'));
})
(async () => {
const keys = await caches.keys();
await Promise.all(keys.map((key) => caches.delete(key)));
await self.clients.claim();
const registrations = await self.registration.unregister();
return registrations;
})()
);
});
+557
View File
@@ -0,0 +1,557 @@
import { getAuthHeaders } from '../utils/auth';
export interface KbGroup {
id: number;
name: string;
description?: string | null;
department_id?: number | null;
document_count?: number;
created_at?: string | null;
updated_at?: string | null;
}
export interface KbDocumentItem {
id: number;
group_id?: number;
title: string;
description?: string | null;
status?: string;
source_type?: string | null;
created_at?: string | null;
updated_at?: string;
version_count?: number;
latest_version?: KbDocumentVersionItem | null;
}
export interface KbDocumentVersionItem {
id: number;
document_id: number;
version_no: number;
status: string;
is_current: boolean;
source_file_name: string;
source_file_ext?: string | null;
source_file_size?: number | null;
sha256?: string | null;
cleaned_file_path?: string | null;
cleaned_preview_path?: string | null;
error_message?: string | null;
created_at?: string | null;
}
export interface KbSyncRecordItem {
id: number;
group_id?: number | null;
document_id?: number | null;
document_version_id: number;
dataset_id: string;
dataset_name?: string | null;
remote_document_id: string;
remote_document_name?: string | null;
status: string;
sync_hash?: string | null;
error_message?: string | null;
synced_at?: string | null;
updated_at?: string | null;
}
export interface KbDocumentMarkdown {
document_id: number;
title: string;
version: KbDocumentVersionItem | null;
content: string;
kind: 'markdown' | 'preview';
}
export interface KbJob {
id: number | string;
job_type: string;
status: string;
group_id?: number | null;
document_id?: number | null;
document_version_id?: number | null;
progress?: number;
message?: string | null;
error_message?: string | null;
payload_json?: Record<string, any> | null;
result_json?: Record<string, any> | null;
created_at?: string;
started_at?: string | null;
finished_at?: string | null;
}
export interface KbDifySettings {
DIFY_API_BASE: string;
DIFY_API_KEY: string;
KB_DIFY_PERMISSION: string;
KB_DIFY_INDEXING_TECHNIQUE: string;
KB_DIFY_SEARCH_METHOD: string;
KB_DIFY_DOC_FORM: string;
dify_api_configured?: boolean;
}
export interface KbDifyHealth {
dify_base_url: string;
dify_api_configured: boolean;
api: {
configured: boolean;
reachable: boolean;
dataset_count?: number | null;
error?: string | null;
};
local_sync_health: {
dataset_bound_groups: number;
sync_records: number;
syncing_versions: number;
synced_versions: number;
failed_sync_records: number;
pending_sync_jobs: number;
};
}
export interface KbListResponse<T> {
ok: boolean;
data: T;
error?: string;
status?: number;
}
const getJson = async <T>(path: string, fallback: T): Promise<T> => {
try {
const res = await fetch(path, { headers: getAuthHeaders() });
if (!res.ok) return fallback;
return (await res.json()) as T;
} catch {
return fallback;
}
};
const getJsonWithStatus = async <T>(path: string, fallback: T): Promise<KbListResponse<T>> => {
try {
const res = await fetch(path, { headers: getAuthHeaders() });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return {
ok: false,
data: fallback,
error: data?.error || '知识库接口请求失败',
status: res.status,
};
}
return { ok: true, data: (await res.json()) as T, status: res.status };
} catch {
return { ok: false, data: fallback, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const getKbGroups = async (): Promise<KbGroup[]> => {
return getJson<KbGroup[]>('/api/kb/groups', []);
};
export const getKbGroupFiles = async (groupId: number): Promise<KbDocumentItem[]> => {
return getJson<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
};
export const getKbGroupsSafe = async (): Promise<KbListResponse<KbGroup[]>> => {
return getJsonWithStatus<KbGroup[]>('/api/kb/groups', []);
};
export const getKbGroupFilesSafe = async (groupId: number): Promise<KbListResponse<KbDocumentItem[]>> => {
return getJsonWithStatus<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
};
export const createKbGroup = async (payload: {
name: string;
description?: string;
}): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
try {
const res = await fetch('/api/kb/groups', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '创建知识库分组失败' };
}
return { ok: true, group: (await res.json()) as KbGroup };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const getKbJobs = async (): Promise<KbJob[]> => {
return getJson<KbJob[]>('/api/kb/jobs', []);
};
export const getKbJobsSafe = async (): Promise<KbListResponse<KbJob[]>> => {
return getJsonWithStatus<KbJob[]>('/api/kb/jobs', []);
};
export const getKbDifySettings = async (): Promise<KbDifySettings | null> => {
return getJson<KbDifySettings | null>('/api/kb/dify/settings', null);
};
export const updateKbDifySettings = async (
payload: Partial<KbDifySettings>
): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => {
try {
const res = await fetch('/api/kb/dify/settings', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '保存 Dify 设置失败' };
}
return { ok: true, settings: (await res.json()) as KbDifySettings };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const getKbDifyHealth = async (): Promise<KbDifyHealth | null> => {
return getJson<KbDifyHealth | null>('/api/kb/dify/health', null);
};
export const runKbJob = async (
jobId: number | string
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
try {
const res = await fetch(`/api/kb/jobs/${jobId}/run`, {
method: 'POST',
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '执行任务失败' };
}
const job = (await res.json()) as KbJob & { run_result?: string };
return { ok: true, job, run_result: job.run_result };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const createKbDocument = async (
groupId: number,
payload: { title: string; description?: string }
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
try {
const res = await fetch(`/api/kb/groups/${groupId}/files`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '创建文档失败' };
}
return { ok: true, document: (await res.json()) as KbDocumentItem };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const updateKbDocument = async (
documentId: number,
payload: { title: string; description?: string; status?: string }
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '更新文档失败' };
}
return { ok: true, document: (await res.json()) as KbDocumentItem };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const deleteKbDocument = async (
documentId: number
): Promise<{ ok: boolean; error?: string }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '删除文档失败' };
}
return { ok: true };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const getKbDocumentVersions = async (
documentId: number
): Promise<KbDocumentVersionItem[]> => {
return getJson<KbDocumentVersionItem[]>(`/api/kb/documents/${documentId}/versions`, []);
};
export const getKbDocumentVersionSourceFile = async (
versionId: number
): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => {
try {
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, {
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '读取原始文件失败' };
}
const disposition = res.headers.get('content-disposition') || '';
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || '');
return {
ok: true,
blob: await res.blob(),
filename: filename || undefined,
contentType: res.headers.get('content-type') || undefined,
};
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const getKbDocumentSyncRecords = async (
documentId: number
): Promise<KbSyncRecordItem[]> => {
return getJson<KbSyncRecordItem[]>(`/api/kb/documents/${documentId}/sync-records`, []);
};
export const getKbDocumentMarkdown = async (
documentId: number
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}/markdown`, {
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '读取清洗后的 Markdown 失败' };
}
return { ok: true, data: (await res.json()) as KbDocumentMarkdown };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const updateKbDocumentMarkdown = async (
documentId: number,
payload: { content: string }
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}/markdown`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '保存 Markdown 失败' };
}
return { ok: true, data: (await res.json()) as KbDocumentMarkdown };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const uploadKbDocumentVersion = async (
documentId: number,
file: File
): Promise<{ ok: boolean; error?: string; version?: KbDocumentVersionItem; status?: number }> => {
try {
const formData = new FormData();
formData.append('file', file);
const res = await fetch(`/api/kb/documents/${documentId}/upload`, {
method: 'POST',
headers: getAuthHeaders(),
body: formData,
});
if (!res.ok) {
if (res.status === 413) {
return { ok: false, error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试', status: res.status };
}
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '上传文档版本失败', status: res.status };
}
return { ok: true, version: (await res.json()) as KbDocumentVersionItem, status: res.status };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const createKbPathUploadJob = async (
groupId: number,
payload: { total_files: number; selected_paths: string[] }
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
try {
const res = await fetch(`/api/kb/groups/${groupId}/path-upload-jobs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
return { ok: false, error: data?.error || '创建路径上传任务失败', status: res.status };
}
return { ok: true, job: data as KbJob, status: res.status };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const uploadKbPathJobFile = async (
jobId: number | string,
file: File,
relativePath: string,
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
try {
const formData = new FormData();
formData.append('file', file);
formData.append('relative_path', relativePath);
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/files`, {
method: 'POST',
headers: getAuthHeaders(),
body: formData,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
return { ok: false, error: data?.error || '上传路径文件失败' };
}
return { ok: true, job: data as KbJob };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const finalizeKbPathUploadJob = async (
jobId: number | string,
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
try {
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/finalize`, {
method: 'POST',
headers: getAuthHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
return { ok: false, error: data?.error || '提交路径上传任务失败' };
}
return { ok: true, job: data as KbJob };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const retryFailedKbPathUploadJob = async (
jobId: number | string,
payload?: { relative_paths?: string[] },
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
try {
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload || {}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
return { ok: false, error: data?.error || '重试失败文件失败', status: res.status };
}
return { ok: true, job: data as KbJob, status: res.status };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const syncKbDocumentToDify = async (
documentId: number
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
try {
const res = await fetch(`/api/kb/documents/${documentId}/sync`, {
method: 'POST',
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || data?.error_message || data?.run_result || '同步到 Dify 失败' };
}
const job = (await res.json()) as KbJob & { run_result?: string };
return { ok: true, job, run_result: job.run_result };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const updateKbGroup = async (
groupId: number,
payload: { name: string; description?: string }
): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
try {
const res = await fetch(`/api/kb/groups/${groupId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify(payload),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '更新知识库分组失败' };
}
return { ok: true, group: (await res.json()) as KbGroup };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
export const deleteKbGroup = async (
groupId: number
): Promise<{ ok: boolean; error?: string }> => {
try {
const res = await fetch(`/api/kb/groups/${groupId}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
return { ok: false, error: data?.error || '删除知识库分组失败' };
}
return { ok: true };
} catch {
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
}
};
@@ -0,0 +1,115 @@
<script setup lang="ts">
import { ref, watch } from 'vue';
import { getKbDifyHealth, type KbDifyHealth } from '../../api/kb';
const props = defineProps<{
open: boolean;
}>();
const emit = defineEmits<{
close: [];
error: [message: string];
}>();
const loading = ref(false);
const payload = ref<KbDifyHealth | null>(null);
const close = () => emit('close');
const loadHealth = async () => {
loading.value = true;
payload.value = await getKbDifyHealth();
loading.value = false;
if (!payload.value) {
emit('error', '加载 Dify 健康状态失败');
}
};
watch(
() => props.open,
(open) => {
if (open) {
void loadHealth();
}
}
);
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
@click="close"
>
<div class="w-full max-w-4xl rounded-3xl border border-slate-200 bg-white p-6 shadow-xl dark:border-slate-700 dark:bg-slate-900" @click.stop>
<div class="flex items-center justify-between gap-4">
<div>
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">Dify 健康检查</h3>
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
查看知识库模块当前的 Dify 连接情况和本地同步概况。
</p>
</div>
<div class="flex items-center gap-3">
<button class="rounded-2xl border border-slate-200 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800" @click="loadHealth">
刷新
</button>
<button class="rounded-2xl border border-slate-200 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800" @click="close">
关闭
</button>
</div>
</div>
<div v-if="loading" class="py-16 text-center text-sm text-slate-400">正在检测...</div>
<div v-else-if="payload" class="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Dify API</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.api.reachable ? '可访问' : '不可访问' }}
</div>
<div class="mt-2 break-all text-xs text-slate-500 dark:text-slate-400">
{{ payload.dify_base_url || '未配置' }}
</div>
</div>
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Dataset 数量</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.api.dataset_count ?? '--' }}
</div>
<div class="mt-2 text-xs text-slate-500 dark:text-slate-400">
配置完成:{{ payload.dify_api_configured ? '是' : '否' }}
</div>
</div>
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">已绑定分组</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.local_sync_health.dataset_bound_groups }}
</div>
<div class="mt-2 text-xs text-slate-500 dark:text-slate-400">
本地同步记录:{{ payload.local_sync_health.sync_records }}
</div>
</div>
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">同步中版本</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.local_sync_health.syncing_versions }}
</div>
</div>
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">已同步版本</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.local_sync_health.synced_versions }}
</div>
</div>
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">待同步任务</div>
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
{{ payload.local_sync_health.pending_sync_jobs }}
</div>
<div class="mt-2 text-xs text-rose-500" v-if="payload.api.error">
{{ payload.api.error }}
</div>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,134 @@
<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import { getKbDifySettings, updateKbDifySettings } from '../../api/kb';
const props = defineProps<{
open: boolean;
}>();
const emit = defineEmits<{
close: [];
saved: [message: string];
error: [message: string];
}>();
const loading = ref(false);
const saving = ref(false);
const form = reactive({
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',
});
const close = () => emit('close');
const loadSettings = async () => {
loading.value = true;
const settings = await getKbDifySettings();
loading.value = false;
if (!settings) {
emit('error', '加载 Dify 设置失败');
return;
}
Object.assign(form, settings);
};
const save = async () => {
saving.value = true;
const result = await updateKbDifySettings(form);
saving.value = false;
if (!result.ok) {
emit('error', result.error || '保存 Dify 设置失败');
return;
}
emit('saved', 'Dify 设置已保存');
emit('close');
};
watch(
() => props.open,
(open) => {
if (open) {
void loadSettings();
}
}
);
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
@click="close"
>
<div class="w-full max-w-3xl rounded-3xl border border-slate-200 bg-white p-6 shadow-xl dark:border-slate-700 dark:bg-slate-900" @click.stop>
<div class="flex items-center justify-between gap-4">
<div>
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">Dify 设置</h3>
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
管理知识库模块使用的 Dify 连接和默认同步参数。
</p>
</div>
<button class="rounded-2xl border border-slate-200 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800" @click="close">
关闭
</button>
</div>
<div v-if="loading" class="py-16 text-center text-sm text-slate-400">正在加载设置...</div>
<div v-else class="mt-6 grid gap-4 md:grid-cols-2">
<label class="space-y-2 md:col-span-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Dify Base URL</span>
<input v-model="form.DIFY_API_BASE" class="input-field" placeholder="https://api.dify.ai/v1" />
</label>
<label class="space-y-2 md:col-span-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Dify API Key</span>
<input v-model="form.DIFY_API_KEY" class="input-field" placeholder="app-..." />
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Permission</span>
<select v-model="form.KB_DIFY_PERMISSION" class="input-field">
<option value="only_me">only_me</option>
<option value="all_team_members">all_team_members</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Indexing Technique</span>
<select v-model="form.KB_DIFY_INDEXING_TECHNIQUE" class="input-field">
<option value="high_quality">high_quality</option>
<option value="economy">economy</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Search Method</span>
<select v-model="form.KB_DIFY_SEARCH_METHOD" class="input-field">
<option value="semantic_search">semantic_search</option>
<option value="hybrid_search">hybrid_search</option>
<option value="full_text_search">full_text_search</option>
</select>
</label>
<label class="space-y-2">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Doc Form</span>
<select v-model="form.KB_DIFY_DOC_FORM" class="input-field">
<option value="text_model">text_model</option>
</select>
</label>
</div>
<div class="mt-6 flex justify-end gap-3">
<button class="rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800" @click="close">
取消
</button>
<button
class="rounded-2xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="saving"
@click="save"
>
{{ saving ? '保存中...' : '保存设置' }}
</button>
</div>
</div>
</div>
</template>
+13 -6
View File
@@ -1,4 +1,4 @@
import { createApp } from 'vue'
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
@@ -48,10 +48,17 @@ createApp(App)
.use(i18n)
.mount('#app')
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js').catch((err) => {
console.error('Service worker registration failed:', err);
});
if ('serviceWorker' in navigator) {
window.addEventListener('load', async () => {
try {
const registrations = await navigator.serviceWorker.getRegistrations();
await Promise.all(registrations.map((registration) => registration.unregister()));
if ('caches' in window) {
const cacheKeys = await window.caches.keys();
await Promise.all(cacheKeys.map((key) => window.caches.delete(key)));
}
} catch (err) {
console.error('Service worker cleanup failed:', err);
}
});
}
+14
View File
@@ -6,6 +6,8 @@ import ChatView from '../views/ChatView.vue';
import AdminView from '../views/AdminView.vue';
import ProfileView from '../views/ProfileView.vue';
import ResetPasswordView from '../views/ResetPasswordView.vue';
import KbWorkspaceView from '../views/KbWorkspaceView.vue';
import KbAdminView from '../views/KbAdminView.vue';
import { config } from '../config';
const routes = [
@@ -44,6 +46,18 @@ const routes = [
name: 'Admin',
component: AdminView
},
{
path: '/kb/workspace',
name: 'KbWorkspace',
component: KbWorkspaceView,
meta: { title: '知识库工作台' }
},
{
path: '/kb/admin',
name: 'KbAdmin',
component: KbAdminView,
meta: { title: '知识库管理台' }
},
];
+7
View File
@@ -2544,6 +2544,13 @@ const handlePermissionImport = async (event: Event) => {
</div>
</div>
<div class="flex items-center gap-4">
<button
@click="router.push('/kb/admin')"
class="hidden md:inline-flex items-center gap-2 rounded-xl border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-50 hover:text-slate-900 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-slate-100"
>
<Settings2 class="w-4 h-4" />
<span>知识库管理</span>
</button>
<ThemeToggleButton />
<!-- Language Selector -->
<div class="flex items-center gap-2">
+360
View File
@@ -0,0 +1,360 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ArrowLeft, FolderPlus, Pencil, Play, RefreshCw, Settings, Trash2, Wrench, X } from 'lucide-vue-next';
import DifyHealthDialog from '../components/kb/DifyHealthDialog.vue';
import DifySettingsDialog from '../components/kb/DifySettingsDialog.vue';
import {
createKbGroup,
deleteKbGroup,
getKbGroupsSafe,
getKbJobsSafe,
runKbJob,
updateKbGroup,
type KbGroup,
type KbJob,
} from '../api/kb';
const router = useRouter();
const groups = ref<KbGroup[]>([]);
const jobs = ref<KbJob[]>([]);
const isSubmitting = ref(false);
const isRefreshing = ref(false);
const editingGroupId = ref<number | null>(null);
const form = ref({
name: '',
description: '',
});
const feedback = ref('');
const feedbackType = ref<'success' | 'error' | ''>('');
const runningJobId = ref<number | string | null>(null);
const settingsDialogOpen = ref(false);
const healthDialogOpen = ref(false);
const formTitle = computed(() => editingGroupId.value ? '编辑知识库分组' : '新建知识库分组');
const formDescription = computed(() => editingGroupId.value
? '修改知识库分组名称和描述,保存后会立即刷新列表。'
: '用于验证主平台里的知识库管理入口和基础接口壳。');
const submitText = computed(() => {
if (isSubmitting.value) return editingGroupId.value ? '保存中...' : '提交中...';
return editingGroupId.value ? '保存修改' : '创建分组';
});
const loadData = async () => {
isRefreshing.value = true;
const [groupsResult, jobsResult] = await Promise.all([getKbGroupsSafe(), getKbJobsSafe()]);
if (groupsResult.ok) {
groups.value = groupsResult.data;
} else {
feedback.value = groupsResult.error || '加载知识库分组失败';
feedbackType.value = 'error';
}
if (jobsResult.ok) {
jobs.value = jobsResult.data;
} else {
feedback.value = jobsResult.error || '加载任务列表失败';
feedbackType.value = 'error';
}
isRefreshing.value = false;
};
const resetForm = () => {
editingGroupId.value = null;
form.value = { name: '', description: '' };
};
const handleCreateGroup = async () => {
if (!form.value.name.trim()) {
feedback.value = '请输入知识库分组名称';
feedbackType.value = 'error';
return;
}
isSubmitting.value = true;
const payload = {
name: form.value.name.trim(),
description: form.value.description.trim(),
};
const result = editingGroupId.value
? await updateKbGroup(editingGroupId.value, payload)
: await createKbGroup(payload);
isSubmitting.value = false;
if (!result.ok) {
feedback.value = result.error || '创建失败';
feedbackType.value = 'error';
return;
}
feedback.value = editingGroupId.value ? '知识库分组已更新' : '知识库分组创建成功';
feedbackType.value = 'success';
resetForm();
await loadData();
};
const handleEditGroup = (group: KbGroup) => {
editingGroupId.value = group.id;
form.value = {
name: group.name,
description: group.description || '',
};
feedback.value = '';
feedbackType.value = '';
};
const handleDeleteGroup = async (group: KbGroup) => {
const confirmed = window.confirm(`确认删除知识库分组「${group.name}」吗?`);
if (!confirmed) return;
const result = await deleteKbGroup(group.id);
if (!result.ok) {
feedback.value = result.error || '删除失败';
feedbackType.value = 'error';
return;
}
if (editingGroupId.value === group.id) {
resetForm();
}
feedback.value = '知识库分组已删除';
feedbackType.value = 'success';
await loadData();
};
const handleRunJob = async (job: KbJob) => {
runningJobId.value = job.id;
const result = await runKbJob(job.id);
runningJobId.value = null;
if (!result.ok) {
feedback.value = result.error || '任务执行失败';
feedbackType.value = 'error';
return;
}
feedback.value = result.run_result || '任务已执行';
feedbackType.value = 'success';
await loadData();
};
onMounted(async () => {
await loadData();
});
</script>
<template>
<div class="min-h-screen bg-gray-50 dark:bg-slate-950 text-slate-800 dark:text-slate-200">
<div class="mx-auto max-w-7xl px-4 py-6 md:px-6 lg:px-8">
<div class="mb-6 flex flex-col gap-4 rounded-3xl border border-slate-200 bg-white p-6 shadow-sm md:flex-row md:items-center md:justify-between dark:border-slate-700 dark:bg-slate-900">
<div class="flex items-start gap-4">
<button
@click="router.push('/admin')"
class="rounded-2xl border border-slate-200 p-3 text-slate-500 transition-colors hover:bg-slate-50 hover:text-slate-900 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-white"
title="返回管理后台"
>
<ArrowLeft class="h-5 w-5" />
</button>
<div class="flex items-center gap-3">
<div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-brand-50 text-brand-600 dark:bg-brand-500/10">
<Settings class="h-6 w-6" />
</div>
<div>
<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100">知识库管理台</h1>
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
第一阶段先承接分组、任务和 Dify 管理入口,后续再接入清洗链路。
</p>
</div>
</div>
</div>
<div class="flex items-center gap-3">
<button
@click="loadData"
class="inline-flex items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
>
<RefreshCw class="h-4 w-4" />
刷新数据
</button>
<button
@click="settingsDialogOpen = true"
class="inline-flex items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
>
<Settings class="h-4 w-4" />
Dify 设置
</button>
<button
@click="healthDialogOpen = true"
class="inline-flex items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
>
<RefreshCw class="h-4 w-4" />
健康检查
</button>
<button
@click="router.push('/kb/workspace')"
class="inline-flex items-center gap-2 rounded-2xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-brand-700"
>
<Wrench class="h-4 w-4" />
前往工作台
</button>
</div>
</div>
<div class="grid grid-cols-1 gap-6 xl:grid-cols-[420px_minmax(0,1fr)]">
<section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="mb-5 flex items-center gap-3">
<div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-brand-50 text-brand-600 dark:bg-brand-500/10">
<FolderPlus class="h-5 w-5" />
</div>
<div>
<h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100">{{ formTitle }}</h2>
<p class="text-sm text-slate-500 dark:text-slate-400">{{ formDescription }}</p>
</div>
</div>
<div class="space-y-4">
<div>
<label class="mb-2 block text-sm font-medium text-slate-600 dark:text-slate-300">分组名称</label>
<input v-model="form.name" class="input-field" placeholder="例如:财务制度库" />
</div>
<div>
<label class="mb-2 block text-sm font-medium text-slate-600 dark:text-slate-300">分组描述</label>
<textarea
v-model="form.description"
rows="4"
class="input-field"
placeholder="描述该知识库分组的业务范围或清洗目标"
/>
</div>
<button
@click="handleCreateGroup"
:disabled="isSubmitting"
class="inline-flex w-full items-center justify-center gap-2 rounded-2xl bg-brand-600 px-4 py-3 text-sm font-medium text-white transition-colors hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
>
<FolderPlus class="h-4 w-4" />
{{ submitText }}
</button>
<button
v-if="editingGroupId"
@click="resetForm"
type="button"
class="inline-flex w-full items-center justify-center gap-2 rounded-2xl border border-slate-200 px-4 py-3 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
>
<X class="h-4 w-4" />
取消编辑
</button>
<p
v-if="feedback"
class="text-sm"
:class="feedbackType === 'error' ? 'text-rose-500' : 'text-emerald-600 dark:text-emerald-400'"
>
{{ feedback }}
</p>
</div>
</section>
<div class="space-y-6">
<section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="mb-4 flex items-center justify-between">
<h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100">知识库分组概览</h2>
<span class="text-xs text-slate-400">{{ isRefreshing ? '加载中...' : '`/api/kb/groups`' }}</span>
</div>
<div v-if="groups.length === 0" class="rounded-2xl border border-dashed border-slate-200 px-4 py-10 text-center text-sm text-slate-400 dark:border-slate-700">
当前暂无分组,或知识库接口尚未联调完成。
</div>
<div v-else class="grid grid-cols-1 gap-3 md:grid-cols-2">
<div
v-for="group in groups"
:key="group.id"
class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="font-semibold text-slate-900 dark:text-slate-100">{{ group.name }}</div>
<div class="mt-1 text-sm text-slate-500 dark:text-slate-400">{{ group.description || '暂无描述' }}</div>
</div>
<div class="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-600 dark:bg-slate-800 dark:text-slate-300">
{{ group.document_count ?? 0 }} 文档
</div>
</div>
<div class="mt-4 flex flex-wrap items-center justify-between gap-3">
<div class="text-xs text-slate-400">
更新时间:{{ group.updated_at || '--' }}
</div>
<div class="flex items-center gap-2">
<button
@click="handleEditGroup(group)"
class="inline-flex items-center gap-1 rounded-xl border border-slate-200 px-3 py-2 text-xs font-medium text-slate-600 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
>
<Pencil class="h-3.5 w-3.5" />
编辑
</button>
<button
@click="handleDeleteGroup(group)"
class="inline-flex items-center gap-1 rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 dark:border-rose-500/30 dark:text-rose-400 dark:hover:bg-rose-500/10"
>
<Trash2 class="h-3.5 w-3.5" />
删除
</button>
</div>
</div>
</div>
</div>
</section>
<section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="mb-4 flex items-center justify-between">
<h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100">任务队列占位</h2>
<span class="text-xs text-slate-400">`/api/kb/jobs`</span>
</div>
<div v-if="jobs.length === 0" class="rounded-2xl border border-dashed border-slate-200 px-4 py-10 text-center text-sm text-slate-400 dark:border-slate-700">
暂无任务。第二阶段会在这里接入清洗、同步和重试任务。
</div>
<div v-else class="space-y-3">
<div
v-for="job in jobs"
:key="job.id"
class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="font-semibold text-slate-900 dark:text-slate-100">{{ job.job_type }}</div>
<div class="mt-1 text-sm text-slate-500 dark:text-slate-400">{{ job.created_at || '--' }}</div>
<div class="mt-2 text-sm text-slate-500 dark:text-slate-400">
{{ job.message || '暂无任务说明' }}
</div>
<div class="mt-2 text-xs text-slate-400">
文档:{{ job.document_id ?? '--' }} · 版本:{{ job.document_version_id ?? '--' }} · 进度:{{ job.progress ?? 0 }}%
</div>
</div>
<span class="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-600 dark:bg-slate-800 dark:text-slate-300">
{{ job.status }}
</span>
</div>
<div class="mt-3 flex justify-end" v-if="['clean', 'sync_dify'].includes(job.job_type) && job.status !== 'success'">
<button
@click="handleRunJob(job)"
:disabled="runningJobId === job.id"
class="inline-flex items-center gap-1 rounded-xl border border-brand-200 px-3 py-2 text-xs font-medium text-brand-700 transition-colors hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 dark:border-brand-500/30 dark:text-brand-300 dark:hover:bg-brand-500/10"
>
<Play class="h-3.5 w-3.5" />
{{ runningJobId === job.id ? '执行中...' : '执行任务' }}
</button>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
<DifySettingsDialog
:open="settingsDialogOpen"
@close="settingsDialogOpen = false"
@saved="(message) => { feedback = message; feedbackType = 'success'; void loadData(); }"
@error="(message) => { feedback = message; feedbackType = 'error'; }"
/>
<DifyHealthDialog
:open="healthDialogOpen"
@close="healthDialogOpen = false"
@error="(message) => { feedback = message; feedbackType = 'error'; }"
/>
</template>
File diff suppressed because it is too large. Load diff
+22 -2
View File
@@ -33,6 +33,7 @@ import {
Edit,
ExternalLink,
Bot,
FileText,
Lock,
User,
Mail,
@@ -48,6 +49,8 @@ import {
ChevronUp
} from 'lucide-vue-next';
import KbWorkspaceView from './KbWorkspaceView.vue';
const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const router = useRouter();
@@ -718,7 +721,7 @@ const handleRegister = async () => {
}
};
const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates'>('applications');
const activeSidebarItem = ref<'profile' | 'applications' | 'feedback' | 'updates' | 'knowledge_base'>('applications');
const isProfileLoading = ref(false);
const isProfileSaving = ref(false);
const isProfileEditing = ref(false);
@@ -934,12 +937,17 @@ const navigateToApplications = () => openWorkspaceSection('favorites', 'applicat
const navigateToUpdates = () => openWorkspaceSection('announcements', 'updates');
const navigateToKnowledgeBase = () => {
activeSidebarItem.value = 'knowledge_base';
};
const navigateToGeneralChat = () => {
router.push(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
};
const openAdminPanel = () => {
window.location.assign('http://localhost:8881/admin');
// Use SPA route instead of a hard-coded local port.
router.push('/admin');
};
const navigateToChat = (id: number) => {
@@ -1340,6 +1348,14 @@ onMounted(async () => {
<LayoutGrid class="h-4 w-4" />
<span>应用管理</span>
</button>
<button
@click="navigateToKnowledgeBase"
class="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-[15px] font-medium transition-all"
:class="activeSidebarItem === 'knowledge_base' ? 'bg-brand-50 text-brand-700 shadow-sm' : 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'"
>
<FileText class="h-4 w-4" />
<span>知识库管理</span>
</button>
<button
@click="openGeneralFeedback"
class="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-[15px] font-medium transition-all"
@@ -1554,6 +1570,10 @@ onMounted(async () => {
</div>
</template>
<template v-else-if="activeSidebarItem === 'knowledge_base'">
<KbWorkspaceView :embedded="true" />
</template>
<template v-else>
<div v-if="wecomEntryHint" class="rounded-2xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700">
{{ wecomEntryHint }}