Merge branch 'dev' into hugo

# Conflicts:
#	.env.dev
#	.env.shared
#	backend/app/api/chat.py
This commit is contained in:
hugo committed 2026-06-08 16:11:42 +08:00
commit ee90b66ff7
63 files changed
+4786 -1422

No files matched your search

+31 -9
View File
@@ -25,6 +25,13 @@ from app.models import Agent, ChatLog, ChatSession, Feedback
from app import db
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
chat_bp = Blueprint('chat', __name__)
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
def _can_use_leave_feature(agent_proxy) -> bool:
agent_name = str(getattr(agent_proxy, 'name', None) or '').strip()
return agent_name in LEAVE_FEATURE_AGENT_NAMES
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
def _session_title_from_text(text: str) -> str:
@@ -1079,20 +1086,24 @@ def chat_completions():
if normalized_files and PLMOracleService.supports(query, agent_proxy):
raise ValidationError('This route does not support attachments')
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
leave_supported = HRLeaveSQLServerService.supports(query)
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
if PLMOracleService.supports(query, agent_proxy):
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
elif leave_supported and leave_feature_enabled:
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
elif leave_supported:
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
elif kb_type == 'ERP知识库':
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
from app.services.text2sql import Text2SQLService
if HRLeaveSQLServerService.supports(query):
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
<<<<<<< HEAD
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
if HRLeaveSQLServerService.supports(query):
if normalized_files:
@@ -1113,6 +1124,9 @@ def chat_completions():
files=normalized_files,
inputs=dify_inputs,
)
=======
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
>>>>>>> dev
def relay_stream():
created_event = {
@@ -1705,6 +1719,10 @@ def preview_file_raw():
content = _convert_office_to_pdf(content, ext)
ext = 'pdf'
content_type = 'application/pdf'
if name and '.' in name:
name = f"{name.rsplit('.', 1)[0]}.pdf"
elif name:
name = f"{name}.pdf"
except Exception as e:
current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e)
placeholder_text = _extract_placeholder_text(content)
@@ -1712,6 +1730,10 @@ def preview_file_raw():
content = placeholder_text.encode('utf-8')
ext = 'txt'
content_type = 'text/plain; charset=utf-8'
if name and '.' in name:
name = f"{name.rsplit('.', 1)[0]}.txt"
elif name:
name = f"{name}.txt"
current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url)
else:
raise AppError(
+489 -39
View File
@@ -3,6 +3,7 @@ backend/app/api/knowledge_base.py
文件用途:知识库/数据清洗模块第一阶段 API
"""
import hashlib
import shutil
from datetime import datetime
from pathlib import Path
from posixpath import normpath
@@ -18,7 +19,6 @@ from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup,
from app.services.knowledge_cleaning.dify_sync_service import delete_document_from_dify
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job, enqueue_kb_job
from app.services.knowledge_cleaning.settings_service import get_kb_dify_health_payload, get_kb_dify_settings, save_kb_dify_settings
from app.services.knowledge_cleaning.tasks import run_clean_job, run_sync_job
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
knowledge_base_bp = Blueprint('knowledge_base', __name__)
@@ -73,6 +73,18 @@ def _current_version(document: KbDocument | None) -> KbDocumentVersion | None:
return None
return next((item for item in versions if item.is_current), versions[0])
def _latest_job_for_version(version_id: int, job_type: str) -> KbJob | None:
return (
db.session.query(KbJob)
.filter(
KbJob.document_version_id == version_id,
KbJob.job_type == job_type,
)
.order_by(KbJob.created_at.desc(), KbJob.id.desc())
.first()
)
def _resolve_storage_path(path_value: str | None) -> Path | None:
if not path_value:
return None
@@ -84,14 +96,46 @@ def _resolve_storage_path(path_value: str | None) -> Path | None:
return None
return candidate
def _resolve_markdown_read_path(version: KbDocumentVersion) -> tuple[Path | None, str]:
def _ensure_preview_markdown(version: KbDocumentVersion) -> tuple[Path | None, str]:
primary = _resolve_storage_path(version.cleaned_file_path)
if primary and primary.exists():
return (primary, 'markdown')
preview = _resolve_storage_path(version.cleaned_preview_path)
if preview and preview.exists():
return (preview, 'preview')
return (None, 'markdown')
preview_exists = bool(preview and preview.exists())
primary_exists = bool(primary and primary.exists())
if preview_exists:
preview_content = preview.read_text(encoding='utf-8', errors='ignore')
# Some legacy versions incorrectly store cleaned_preview_path as document.md.
if preview != primary and 'data:image/' not in preview_content:
return (preview, 'preview')
source = primary if primary_exists else preview if preview_exists else None
if not source:
return (None, 'markdown')
content = source.read_text(encoding='utf-8', errors='ignore')
if 'data:image/' not in content:
if source == preview:
return (preview, 'preview')
if not version.cleaned_preview_path:
version.cleaned_preview_path = str(primary)
db.session.commit()
return (primary, 'markdown')
from edkb_system.skills.export import _LocalPreviewImageRewriter
preview = primary.parent / 'document_preview.md'
images_dir = primary.parent / 'images_view'
if images_dir.exists():
shutil.rmtree(images_dir, ignore_errors=True)
rewriter = _LocalPreviewImageRewriter(images_dir=images_dir)
preview.write_text(rewriter.replace_text(content), encoding='utf-8')
version.cleaned_preview_path = str(preview)
db.session.commit()
return (preview, 'preview')
def _resolve_markdown_read_path(version: KbDocumentVersion) -> tuple[Path | None, str]:
return _ensure_preview_markdown(version)
def _resolve_markdown_write_path(version: KbDocumentVersion) -> Path | None:
primary = _resolve_storage_path(version.cleaned_file_path)
@@ -108,6 +152,20 @@ def _resolve_markdown_write_path(version: KbDocumentVersion) -> Path | None:
def _serialize_markdown_payload(document: KbDocument, version: KbDocumentVersion, content: str, kind: str):
return {'document_id': document.id, 'title': document.title, 'version': _serialize_version(version), 'content': content, 'kind': kind}
def _markdown_unavailable_message(version: KbDocumentVersion) -> str:
status = str(getattr(version, 'status', '') or '').strip().lower()
error_message = str(getattr(version, 'error_message', '') or '').strip()
if status == 'failed':
if error_message:
return f'当前文档清洗失败,尚未生成 Markdown。失败原因:{error_message}'
return '当前文档清洗失败,尚未生成 Markdown,请重新清洗后重试'
if status == 'processing':
return '当前文档正在清洗中,暂未生成 Markdown,请稍后再试'
if status == 'uploaded':
return '当前文档待清洗,暂未生成 Markdown,请先发起清洗'
return '当前文档尚未生成可编辑 Markdown'
@knowledge_base_bp.route('/dify/settings', methods=['GET'])
@require_admin
def get_dify_settings():
@@ -165,6 +223,26 @@ def _save_upload(file_storage, target_path: Path):
def _get_active_path_upload_job(group_id: int) -> KbJob | None:
return db.session.query(KbJob).filter(KbJob.group_id == group_id, KbJob.job_type == 'path_upload', KbJob.status.in_(('draft', 'staging', 'queued', 'running'))).order_by(KbJob.created_at.desc(), KbJob.id.desc()).first()
def _upsert_path_upload_job_files(job: KbJob, requested_files: list[dict]) -> None:
payload = dict(job.payload_json or {})
files = list(payload.get('files') or [])
for requested_item in requested_files:
relative_path = str(requested_item.get('relative_path') or '').strip()
if not relative_path:
continue
existing_item = _find_path_upload_file_item(files, relative_path)
if existing_item is None:
files.append(requested_item)
continue
if not str(existing_item.get('original_name') or '').strip():
existing_item['original_name'] = requested_item.get('original_name')
_sync_path_upload_job_payload(job, files)
if job.status in ('draft', 'staging', 'queued', 'running'):
_refresh_path_upload_job_state(job)
def _sanitize_relative_path(relative_path: str | None, fallback_name: str) -> str:
raw = str(relative_path or '').replace('\\', '/').strip().lstrip('/')
normalized = normpath(raw) if raw else fallback_name
@@ -182,6 +260,130 @@ def _sanitize_relative_path(relative_path: str | None, fallback_name: str) -> st
safe_leaf = _safe_upload_filename(parts[-1] or fallback_name)
return '/'.join([*safe_parts, safe_leaf]).strip('/') or _safe_upload_filename(fallback_name)
def _build_path_upload_file_item(relative_path: str | None, original_name: str | None, **extra):
fallback_name = Path(str(original_name or relative_path or '')).name or 'uploaded_file'
normalized_path = _sanitize_relative_path(relative_path, fallback_name)
payload = {
'relative_path': normalized_path,
'original_name': Path(fallback_name).name or fallback_name,
'staged_path': None,
'size': None,
'sha256': None,
'status': 'queued',
'error': None,
'document_id': None,
'version_id': None,
}
payload.update(extra)
return payload
def _find_path_upload_file_item(files: list[dict], relative_path: str):
for item in files:
current = str(item.get('relative_path') or item.get('original_name') or '').strip()
if current == relative_path:
return item
return None
def _sync_path_upload_job_payload(job: KbJob, files: list[dict]):
payload = dict(job.payload_json or {})
result = dict(job.result_json or {})
selected_paths = []
for item in files:
relative_path = str(item.get('relative_path') or item.get('original_name') or '').strip()
if not relative_path:
continue
root = relative_path.split('/')[0]
if root and root not in selected_paths:
selected_paths.append(root)
payload['files'] = files
payload['total_files'] = len(files)
payload['staged_count'] = sum(1 for item in files if str(item.get('staged_path') or '').strip())
payload['selected_paths'] = selected_paths
result['total'] = len(files)
result['success'] = sum(1 for item in files if str(item.get('status') or '').lower() == 'success')
result['failed'] = sum(1 for item in files if str(item.get('status') or '').lower() == 'failed')
result['staged'] = payload['staged_count']
result['processed'] = result['success'] + result['failed']
job.payload_json = payload
job.result_json = result
return (payload, result)
def _refresh_path_upload_job_state(job: KbJob) -> None:
payload = dict(job.payload_json or {})
result = dict(job.result_json or {})
total = max(int(result.get('total') or payload.get('total_files') or 0), 0)
success = int(result.get('success') or 0)
failed = int(result.get('failed') or 0)
processed = int(result.get('processed') or (success + failed) or 0)
files = list(payload.get('files') or [])
has_pending = any(
str(item.get('status') or '').lower() in ('queued', 'uploading')
for item in files
)
payload['current_file'] = ''
job.payload_json = payload
job.progress = min(int(processed * 100 / total), 100) if total else 100
if total == 0:
job.status = 'cancelled'
job.finished_at = datetime.utcnow()
job.progress = 100
job.message = '路径上传记录为空'
job.error_message = None
return
if has_pending or processed < total:
job.status = 'staging'
job.finished_at = None
job.message = f'已上传并提交清洗 {processed}/{total} 个文件'
job.error_message = None
return
job.finished_at = datetime.utcnow()
job.progress = 100
if failed > 0:
job.status = 'failed'
job.message = f'路径上传完成,成功 {success} 条,失败 {failed} 条'
job.error_message = f'部分文件上传失败:{failed} 条'
return
job.status = 'success'
job.message = f'路径上传完成,成功 {success} 条'
job.error_message = None
def _remove_path_upload_staged_file(staged_path: str | None):
candidate = _resolve_storage_path(staged_path)
if not candidate or not candidate.exists():
return
try:
candidate.unlink()
except FileNotFoundError:
return
stop_dir = _kb_storage_root() / 'path_upload_jobs'
parent = candidate.parent
while parent.exists() and parent != stop_dir and stop_dir in parent.parents:
try:
parent.rmdir()
except OSError:
break
parent = parent.parent
def _soft_delete_document(document_id: int | None, user_id: int | None):
if not document_id:
return False
document = db.session.get(KbDocument, document_id)
if not document or document.is_deleted:
return False
try:
delete_document_from_dify(document.id)
except Exception:
pass
document.is_deleted = True
document.updated_by_id = user_id
return True
@knowledge_base_bp.route('/groups', methods=['GET'])
def list_groups():
user = _require_user()
@@ -297,13 +499,47 @@ def create_path_upload_job(group_id: int):
raise NotFoundError('Knowledge base group not found')
existing_job = _get_active_path_upload_job(group_id)
if existing_job:
raise ConflictError('有文件正在上传请稍等再试~', details={'job': _serialize_job(existing_job)})
data = request.get_json(silent=True) or {}
raw_files = data.get('files') or []
files = []
if isinstance(raw_files, list):
for item in raw_files:
if not isinstance(item, dict):
continue
try:
files.append(_build_path_upload_file_item(item.get('relative_path'), item.get('original_name')))
except ValueError:
continue
if files:
_upsert_path_upload_job_files(existing_job, files)
db.session.commit()
payload = _serialize_job(existing_job)
payload['reused_existing'] = True
payload['message'] = payload.get('message') or '检测到未完成的路径上传任务,已自动续传'
return jsonify(payload)
data = request.get_json(silent=True) or {}
total_files = max(int(data.get('total_files') or 0), 0)
selected_paths = data.get('selected_paths') or []
if not isinstance(selected_paths, list):
selected_paths = []
job = KbJob(job_type='path_upload', status='draft', group_id=group_id, progress=0, message='等待上传路径文件到后台暂存区', payload_json={'total_files': total_files, 'selected_paths': selected_paths, 'staged_count': 0, 'files': []}, result_json={'total': total_files, 'success': 0, 'failed': 0, 'staged': 0}, created_by_id=getattr(current_user, 'id', None))
raw_files = data.get('files') or []
files = []
if isinstance(raw_files, list):
for item in raw_files:
if not isinstance(item, dict):
continue
try:
files.append(_build_path_upload_file_item(item.get('relative_path'), item.get('original_name')))
except ValueError:
continue
if files:
total_files = len(files)
selected_paths = []
for item in files:
root = str(item.get('relative_path') or '').split('/')[0]
if root and root not in selected_paths:
selected_paths.append(root)
job = KbJob(job_type='path_upload', status='draft', group_id=group_id, progress=0, message='等待上传路径文件到后台暂存区', payload_json={'total_files': total_files, 'selected_paths': selected_paths, 'staged_count': 0, 'files': files}, result_json={'total': total_files, 'success': 0, 'failed': 0, 'staged': 0, 'processed': 0}, created_by_id=getattr(current_user, 'id', None))
db.session.add(job)
db.session.commit()
return (jsonify(_serialize_job(job)), 201)
@@ -329,41 +565,152 @@ def upload_path_job_file(job_id: int):
sha256, file_size = _save_upload(uploaded, target_path)
payload = dict(job.payload_json or {})
files = list(payload.get('files') or [])
files.append({'relative_path': relative_path, 'original_name': fallback_name, 'staged_path': str(target_path), 'size': file_size, 'sha256': sha256, 'status': 'queued', 'error': None, 'document_id': None, 'version_id': None})
payload['files'] = files
payload['staged_count'] = len(files)
job.payload_json = payload
entry = _find_path_upload_file_item(files, relative_path)
if entry is not None and str(entry.get('status') or '').lower() == 'success' and entry.get('document_id') and entry.get('version_id'):
_sync_path_upload_job_payload(job, files)
_refresh_path_upload_job_state(job)
db.session.commit()
return jsonify(_serialize_job(job))
if entry is None:
entry = _build_path_upload_file_item(relative_path, fallback_name)
files.append(entry)
entry['original_name'] = fallback_name
entry['staged_path'] = str(target_path)
entry['size'] = file_size
entry['sha256'] = sha256
entry['status'] = 'uploading'
entry['error'] = None
entry['document_id'] = None
entry['version_id'] = None
payload['current_file'] = relative_path
job.status = 'staging'
job.message = f"已暂存 {len(files)}/{payload.get('total_files') or len(files)} 个文件"
result = dict(job.result_json or {})
result['total'] = payload.get('total_files') or len(files)
result['staged'] = len(files)
job.result_json = result
job.started_at = job.started_at or datetime.utcnow()
payload, _result = _sync_path_upload_job_payload(job, files)
job.payload_json = payload
job.message = f'正在上传并提交清洗:{relative_path}'
try:
from app.services.knowledge_cleaning.tasks import _register_document_version_from_staged_file
document, version, _clean_job = _register_document_version_from_staged_file(
group_id=job.group_id,
relative_path=relative_path,
staged_path=target_path,
original_name=fallback_name,
user_id=getattr(current_user, 'id', None),
)
entry['status'] = 'success'
entry['document_id'] = document.id
entry['version_id'] = version.id
entry['error'] = None
except Exception as exc:
entry['status'] = 'failed'
entry['error'] = str(exc)
_sync_path_upload_job_payload(job, files)
_refresh_path_upload_job_state(job)
db.session.commit()
return (jsonify(_serialize_job(job)), 201)
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files/fail', methods=['POST'])
def mark_path_job_file_failed(job_id: int):
current_user = _require_user()
job = db.session.get(KbJob, job_id)
if not job or job.job_type != 'path_upload':
raise NotFoundError('路径上传任务不存在')
data = request.get_json(silent=True) or {}
original_name = str(data.get('original_name') or '').strip() or None
relative_path_raw = str(data.get('relative_path') or '').strip()
try:
relative_path = _sanitize_relative_path(relative_path_raw, Path(original_name or relative_path_raw or 'uploaded_file').name or 'uploaded_file')
except ValueError as exc:
raise ValidationError(str(exc))
error_message = str(data.get('error') or '路径文件上传失败').strip() or '路径文件上传失败'
payload = dict(job.payload_json or {})
files = list(payload.get('files') or [])
entry = _find_path_upload_file_item(files, relative_path)
if entry is None:
entry = _build_path_upload_file_item(relative_path, original_name)
files.append(entry)
if str(entry.get('staged_path') or '').strip() and str(entry.get('status') or '').lower() in ('queued', 'success', 'uploading'):
return jsonify(_serialize_job(job))
entry['status'] = 'failed'
entry['error'] = error_message
entry['original_name'] = entry.get('original_name') or original_name or Path(relative_path).name
_sync_path_upload_job_payload(job, files)
_refresh_path_upload_job_state(job)
db.session.commit()
return jsonify(_serialize_job(job))
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/finalize', methods=['POST'])
def finalize_path_upload_job(job_id: int):
current_user = _require_user()
job = db.session.get(KbJob, job_id)
if not job or job.job_type != 'path_upload':
raise NotFoundError('路径上传任务不存在')
if job.status in ('success', 'failed', 'cancelled'):
return jsonify(_serialize_job(job))
if job.status not in ('draft', 'staging'):
raise ConflictError('当前任务不允许提交执行')
payload = dict(job.payload_json or {})
files = list(payload.get('files') or [])
if not files:
raise ValidationError('当前没有可上传的文件')
job.status = 'queued'
job.progress = 0
job.message = '等待后台批量导入文档'
staged_files = [item for item in files if str(item.get('staged_path') or '').strip()]
if not staged_files:
_sync_path_upload_job_payload(job, files)
_refresh_path_upload_job_state(job)
if job.status != 'failed':
job.status = 'failed'
job.message = '当前批次没有成功暂存的文件'
job.error_message = '当前批次没有成功暂存的文件'
db.session.commit()
return jsonify(_serialize_job(job))
payload['finalized_at'] = datetime.utcnow().isoformat()
job.payload_json = payload
job.created_by_id = getattr(current_user, 'id', None)
_sync_path_upload_job_payload(job, files)
_refresh_path_upload_job_state(job)
db.session.commit()
enqueue_kb_job(job.id)
refreshed = db.session.get(KbJob, job.id)
return jsonify(_serialize_job(refreshed))
response_payload = _serialize_job(refreshed)
response_payload['queue_result'] = 'inline_per_file'
response_payload['accepted'] = True
return (jsonify(response_payload), 202)
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['DELETE'])
def delete_path_job_file(job_id: int):
current_user = _require_user()
job = db.session.get(KbJob, job_id)
if not job or job.job_type != 'path_upload':
raise NotFoundError('路径上传任务不存在')
relative_path_raw = str(request.args.get('relative_path') or '').strip()
if not relative_path_raw:
raise ValidationError('relative_path is required')
try:
relative_path = _sanitize_relative_path(relative_path_raw, Path(relative_path_raw).name or 'uploaded_file')
except ValueError as exc:
raise ValidationError(str(exc))
payload = dict(job.payload_json or {})
files = list(payload.get('files') or [])
entry = _find_path_upload_file_item(files, relative_path)
if entry is None:
raise NotFoundError('路径文件记录不存在')
_remove_path_upload_staged_file(entry.get('staged_path'))
document_deleted = _soft_delete_document(entry.get('document_id'), getattr(current_user, 'id', None))
files = [item for item in files if item is not entry]
_sync_path_upload_job_payload(job, files)
if not files:
job.status = 'cancelled'
job.progress = 100
job.finished_at = job.finished_at or datetime.utcnow()
job.message = '路径上传记录已清空'
job.error_message = None
staging_dir = _kb_storage_root() / 'path_upload_jobs' / f'job_{job.id:06d}'
if staging_dir.exists():
shutil.rmtree(staging_dir, ignore_errors=True)
db.session.commit()
return jsonify({'ok': True, 'job': _serialize_job(job), 'document_deleted': document_deleted, 'relative_path': relative_path})
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/retry-failed', methods=['POST'])
def retry_failed_path_upload_job(job_id: int):
@@ -451,7 +798,7 @@ def get_document_markdown(document_id: int):
raise NotFoundError('当前文档暂无版本记录')
markdown_path, kind = _resolve_markdown_read_path(version)
if not markdown_path:
raise ConflictError('当前文档尚未生成可编辑 Markdown')
raise ConflictError(_markdown_unavailable_message(version))
content = markdown_path.read_text(encoding='utf-8', errors='ignore')
return jsonify(_serialize_markdown_payload(document, version, content, kind))
@@ -470,7 +817,7 @@ def update_document_markdown(document_id: int):
raise ValidationError('content is required')
markdown_path = _resolve_markdown_write_path(version)
if not markdown_path:
raise ConflictError('当前文档尚未生成可编辑 Markdown')
raise ConflictError(_markdown_unavailable_message(version))
markdown_path.parent.mkdir(parents=True, exist_ok=True)
markdown_path.write_text(content, encoding='utf-8')
version.cleaned_file_path = str(markdown_path)
@@ -512,10 +859,75 @@ def upload_document_version(document_id: int):
db.session.add(upload_job)
db.session.add(clean_job)
db.session.commit()
enqueue_clean_job(clean_job.id)
_enqueued, queue_result = enqueue_clean_job(clean_job.id)
db.session.expire_all()
version = db.session.get(KbDocumentVersion, version.id)
return (jsonify(_serialize_version(version)), 201)
clean_job = db.session.get(KbJob, clean_job.id)
return (jsonify({
'accepted': True,
'message': '文件上传成功,清洗已排队',
'queue_result': queue_result,
'version': _serialize_version(version),
'clean_job': _serialize_job(clean_job) if clean_job else None,
}), 201)
@knowledge_base_bp.route('/documents/<int:document_id>/clean', methods=['POST'])
@require_admin
def submit_document_clean(document_id: int):
current_user = get_current_user()
document = (
db.session.query(KbDocument)
.options(joinedload(KbDocument.versions))
.filter(KbDocument.id == document_id, KbDocument.is_deleted.is_(False))
.first()
)
if not document:
raise NotFoundError('Knowledge base document not found')
version = _current_version(document)
if not version:
raise ValidationError('当前文档暂无可清洗版本')
latest_clean_job = _latest_job_for_version(version.id, 'clean')
if latest_clean_job and latest_clean_job.status in ('queued', 'running'):
payload = _serialize_job(latest_clean_job)
payload['accepted'] = True
payload['queue_result'] = 'already_queued'
payload['message'] = latest_clean_job.message or '清洗任务已在处理中'
return jsonify(payload), 202
version.status = 'uploaded'
version.error_message = None
if document.status == 'failed':
document.status = 'uploaded'
document.updated_by_id = getattr(current_user, 'id', None)
clean_job = KbJob(
job_type='clean',
status='queued',
group_id=document.group_id,
document_id=document.id,
document_version_id=version.id,
progress=0,
message='等待清洗任务执行',
payload_json={
'document_version_id': version.id,
'document_id': document.id,
'source_file_name': version.source_file_name,
'retry_mode': 'manual',
},
created_by_id=getattr(current_user, 'id', None),
)
db.session.add(clean_job)
db.session.commit()
_enqueued, queue_result = enqueue_clean_job(clean_job.id)
refreshed = db.session.get(KbJob, clean_job.id)
payload = _serialize_job(refreshed) if refreshed else {'id': clean_job.id}
payload['accepted'] = True
payload['queue_result'] = queue_result
payload['message'] = refreshed.message if refreshed else '清洗任务已提交,等待后台处理'
return jsonify(payload), 202
@knowledge_base_bp.route('/documents/<int:document_id>/sync', methods=['POST'])
@require_admin
@@ -530,13 +942,13 @@ def sync_document(document_id: int):
sync_job = KbJob(job_type='sync_dify', status='queued', group_id=document.group_id, document_id=document.id, document_version_id=version.id, progress=0, message='等待同步到 Dify', payload_json={'document_version_id': version.id, 'document_id': document.id}, created_by_id=getattr(current_user, 'id', None))
db.session.add(sync_job)
db.session.commit()
success, message = run_sync_job(sync_job.id)
_enqueued, queue_result = enqueue_kb_job(sync_job.id)
refreshed = db.session.get(KbJob, sync_job.id)
payload = _serialize_job(refreshed) if refreshed else {'id': sync_job.id}
payload['run_result'] = message
if not success:
payload['error'] = (refreshed.error_message if refreshed else None) or message
return (jsonify(payload), 200 if success else 400)
payload['accepted'] = True
payload['queue_result'] = queue_result
payload['message'] = refreshed.message if refreshed else '同步任务已提交,等待后台处理'
return (jsonify(payload), 202)
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['PATCH'])
def update_document(document_id: int):
@@ -589,13 +1001,51 @@ def run_job(job_id: int):
job = db.session.get(KbJob, job_id)
if not job:
raise NotFoundError('任务不存在')
if job.job_type == 'clean':
success, message = run_clean_job(job_id)
elif job.job_type == 'sync_dify':
success, message = run_sync_job(job_id)
else:
if job.job_type not in ('clean', 'sync_dify'):
raise ValidationError('当前仅支持手动执行 clean 或 sync_dify 任务')
if job.status in ('queued', 'running'):
refreshed = db.session.get(KbJob, job_id)
payload = _serialize_job(refreshed) if refreshed else {'id': job_id}
payload['accepted'] = True
payload['queue_result'] = 'already_queued'
payload['run_result'] = '任务已在后台处理中'
return jsonify(payload), 202
version = db.session.get(KbDocumentVersion, job.document_version_id) if job.document_version_id else None
if job.job_type == 'clean':
if not version:
raise NotFoundError('关联文档版本不存在')
job.status = 'queued'
job.progress = 0
job.started_at = None
job.finished_at = None
job.error_message = None
job.message = '等待清洗任务执行'
version.status = 'uploaded'
version.error_message = None
if version.document:
version.document.status = 'uploaded'
else:
if not version:
raise NotFoundError('关联文档版本不存在')
job.status = 'queued'
job.progress = 0
job.started_at = None
job.finished_at = None
job.error_message = None
job.message = '等待同步到 Dify'
if version.status in ('failed', 'ready', 'synced'):
version.error_message = None
db.session.commit()
_enqueued, queue_result = enqueue_kb_job(job.id)
refreshed = db.session.get(KbJob, job_id)
payload = _serialize_job(refreshed) if refreshed else {'id': job_id}
payload['run_result'] = message
return (jsonify(payload), 200 if success else 400)
payload['accepted'] = True
payload['queue_result'] = queue_result
payload['run_result'] = '任务已提交后台异步执行'
return jsonify(payload), 202
+87 -3
View File
@@ -225,6 +225,78 @@ def _casdoor_password_login(username: str, password: str):
raise RuntimeError(f'Casdoor password login failed: {data}')
return data
def _is_casdoor_login_mode() -> bool:
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
def _is_casdoor_configured() -> bool:
if not _clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
return False
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
return bool(base and client_id and client_secret)
def _casdoor_user_owner() -> str:
owner = _clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def _verify_casdoor_password(username: str, password: str):
_casdoor_password_login(username, password)
def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str):
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/set-password'
resp = requests.post(url, files={'userOwner': (None, user_owner), 'userName': (None, user_name), 'oldPassword': (None, old_password), 'newPassword': (None, new_password)}, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise RuntimeError(data.get('msg') or f'Casdoor set-password failed: {data}')
def _is_casdoor_password_error(message: str) -> bool:
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
def _raise_incorrect_current_password():
raise AppError(
code='AUTH.INCORRECT_CURRENT_PASSWORD',
message='Incorrect current password',
http_status=403,
)
def _verify_current_password_for_change(user, current_password: str):
if user.check_password(current_password):
return
if not _is_casdoor_configured():
_raise_incorrect_current_password()
try:
_verify_casdoor_password(user.username, current_password)
except RuntimeError as e:
if _is_casdoor_password_error(str(e)):
_raise_incorrect_current_password()
raise
def _sync_casdoor_password(username: str, current_password: str, new_password: str):
if not _is_casdoor_configured():
return
user_owner = _casdoor_user_owner()
try:
_casdoor_set_password(user_owner, username, current_password, new_password)
except RuntimeError as first_error:
if _is_casdoor_password_error(str(first_error)):
_raise_incorrect_current_password()
try:
_casdoor_set_password(user_owner, username, '', new_password)
except RuntimeError:
raise first_error
def _cleanup_wecom_state_cache():
now = datetime.utcnow()
expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now]
@@ -1362,7 +1434,10 @@ def user_profile():
@user_bp.route('/change-password', methods=['POST'])
def change_password():
"""
Change password
Change password for the current user.
Verify current password against local DB and/or Casdoor, then update both stores
to keep them in sync regardless of AUTH_LOGIN_MODE or login method.
"""
user = _get_current_user()
if not user:
@@ -1372,12 +1447,21 @@ def change_password():
new_password = data.get('new_password')
if not current_password or not new_password:
raise ValidationError('Current and new password are required')
if not user.check_password(current_password):
raise ForbiddenError('Incorrect current password')
try:
_verify_current_password_for_change(user, current_password)
_sync_casdoor_password(user.username, current_password, new_password)
user.set_password(new_password)
db.session.commit()
return jsonify({'message': 'Password changed successfully'})
except AppError:
raise
except RuntimeError as e:
db.session.rollback()
message = str(e)
if _is_casdoor_password_error(message):
_raise_incorrect_current_password()
current_app.logger.exception('[change_password] Casdoor failed user=%s', user.username)
raise AppError(code='SYSTEM.HTTP_ERROR', message=f'Failed to change password: {message}', http_status=502, details={'error_code': 'CASDOOR_SET_PASSWORD_FAILED'})
except Exception as e:
db.session.rollback()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
+8 -3
View File
@@ -69,10 +69,13 @@ class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('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_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免卡住整个 worker 队列
EDKB_FILE_TIMEOUT_SEC = int(os.getenv('EDKB_FILE_TIMEOUT_SEC', '0') or '0')
# 数据库连接池配置
SQLALCHEMY_ENGINE_OPTIONS = {
'pool_size': 20,
@@ -83,7 +86,7 @@ class Config:
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', 'sync').strip().lower()
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', '').strip().lower()
# Dify 网关配置
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
@@ -205,6 +208,8 @@ class Config:
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE')
# Casdoor organization (userOwner) for set-password and other management APIs.
CASDOOR_ORGANIZATION = (os.getenv('CASDOOR_ORGANIZATION') or 'organization_HX').strip()
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
@@ -234,7 +239,7 @@ class Config:
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin')
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
MINIO_BUCKET_NAME = os.getenv('MINIO_BUCKET_NAME', 'agent-guides')
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
+4 -1
View File
@@ -34,6 +34,9 @@ _BACKEND_DIR = Path(__file__).resolve().parents[1]
_ROOT_DIR = _BACKEND_DIR.parent
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
# Backward-compatible alias for tests and older callers that still patch/read
# the historical backend/.env location directly.
BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH
WECOM_BOOL_KEYS = {
'WECOM_ENABLED',
'WECOM_AUTO_CREATE_USER',
@@ -180,7 +183,7 @@ def _persist_to_env_file(values: dict[str, str]) -> bool:
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
merged: dict[str, str] = {}
for env_path in (LEGACY_BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
if not env_path.exists():
continue
try:
@@ -152,6 +152,16 @@ def _is_remote_document_missing(error_text: str) -> bool:
)
def _resolve_upload_name(version: KbDocumentVersion) -> str:
document_title = str(getattr(version.document, 'title', '') or '').strip()
if document_title:
return document_title
source_file_name = str(version.source_file_name or '').strip()
if source_file_name:
return source_file_name
return f'文档-{version.document_id}'
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:
@@ -177,7 +187,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
remote_document_id = None
remote_document_name = None
upload_name = version.source_file_name or document.title
upload_name = _resolve_upload_name(version)
if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash:
try:
payload = service.get_document(
@@ -4,6 +4,7 @@ backend/app/services/knowledge_cleaning/edkb_adapter.py
"""
from __future__ import annotations
import os
import shutil
import tempfile
from pathlib import Path
@@ -12,6 +13,27 @@ from pathlib import Path
TEXT_EXTS = {'.txt', '.md'}
def _temporary_env(**overrides: str):
saved: dict[str, str | None] = {}
class _EnvGuard:
def __enter__(self):
for key, value in overrides.items():
saved[key] = os.environ.get(key)
os.environ[key] = value
return self
def __exit__(self, exc_type, exc, tb):
for key, old_value in saved.items():
if old_value is None:
os.environ.pop(key, None)
else:
os.environ[key] = old_value
return False
return _EnvGuard()
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
@@ -22,6 +44,28 @@ def _find_generated_markdown(output_root: Path) -> Path:
return candidates[0]
def _find_generated_preview_markdown(output_root: Path) -> Path | None:
candidates = [path for path in output_root.rglob('03_clean_view.md') if path.is_file()]
if not candidates:
return None
candidates.sort(key=lambda item: len(item.parts))
return candidates[0]
def _rewrite_preview_markdown_if_needed(preview_path: Path, target_dir: Path) -> None:
content = preview_path.read_text(encoding='utf-8', errors='ignore')
if 'data:image/' not in content:
return
from edkb_system.skills.export import _LocalPreviewImageRewriter
images_dir = target_dir / 'images_view'
if images_dir.exists():
shutil.rmtree(images_dir)
rewriter = _LocalPreviewImageRewriter(images_dir=images_dir)
preview_path.write_text(rewriter.replace_text(content), encoding='utf-8')
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'
@@ -70,19 +114,37 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
shutil.copy2(source_path, tmp_source_path)
config = SystemConfig.load(None)
result = build_knowledge(tmp_source_path, output_dir, config, cache_dir)
# Align with the xx system: do not spend clean-time uploading images to MinIO.
# Keep embedded-image fallback so Markdown can still be produced locally.
with _temporary_env(
MINIO_UPLOAD_ENABLED='false',
MINIO_ALLOW_EMBED_FALLBACK='true',
):
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)
preview_source = _find_generated_preview_markdown(output_dir)
cleaned_path = target_dir / 'document.md'
shutil.copy2(markdown_source, cleaned_path)
preview_path = cleaned_path
if preview_source and preview_source.exists():
preview_path = target_dir / 'document_preview.md'
shutil.copy2(preview_source, preview_path)
preview_images_dir = preview_source.parent / 'images_view'
target_preview_images_dir = target_dir / 'images_view'
if target_preview_images_dir.exists():
shutil.rmtree(target_preview_images_dir)
if preview_images_dir.exists():
shutil.copytree(preview_images_dir, target_preview_images_dir)
_rewrite_preview_markdown_if_needed(preview_path, target_dir)
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),
'cleaned_preview_path': str(preview_path),
'word_count': len(content.split()),
}
@@ -12,11 +12,38 @@ import logging
from datetime import datetime, timedelta
from flask import current_app
from sqlalchemy.exc import OperationalError
from app import db
from app.models import KbDocumentVersion, KbJob
logger = logging.getLogger('kb-worker')
_WORD_EXTENSIONS = {'doc', 'docx'}
def _normalize_source_ext(value: str | None) -> str:
return str(value or '').strip().lower().lstrip('.')
def _is_word_clean_job(job: KbJob | None) -> bool:
if not job or job.job_type != 'clean' or not job.document_version:
return False
return _normalize_source_ext(job.document_version.source_file_ext) in _WORD_EXTENSIONS
def _has_running_word_clean_job() -> bool:
running_jobs = (
db.session.query(KbJob)
.join(KbDocumentVersion, KbDocumentVersion.id == KbJob.document_version_id)
.filter(
KbJob.job_type == 'clean',
KbJob.status == 'running',
KbDocumentVersion.source_file_ext.isnot(None),
)
.order_by(KbJob.started_at.asc(), KbJob.id.asc())
.all()
)
return any(_is_word_clean_job(job) for job in running_jobs)
def recover_stale_running_jobs() -> tuple[int, str]:
@@ -79,8 +106,8 @@ def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
- manual: 保留 queued,等待管理台手动执行。
"""
mode = str(
current_app.config.get('TASK_EXECUTION_MODE')
or current_app.config.get('KB_TASK_EXECUTION_MODE', 'sync')
current_app.config.get('KB_TASK_EXECUTION_MODE')
or current_app.config.get('TASK_EXECUTION_MODE', 'worker')
).strip().lower()
job = db.session.get(KbJob, job_id)
@@ -88,12 +115,14 @@ def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
return False, 'job_not_found'
if mode == 'sync':
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job, run_sync_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)
if job.job_type == 'sync_dify':
return run_sync_job(job_id)
return False, f'unsupported_sync_job:{job.job_type}'
if mode in ('worker', 'rq'):
@@ -106,23 +135,67 @@ def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
return enqueue_kb_job(job_id)
def claim_next_kb_job() -> KbJob | None:
"""
原子领取下一条 queued 任务,避免并发 worker 重复消费同一条记录。
当前运行在 PostgreSQL,可安全使用 FOR UPDATE SKIP LOCKED。
"""
now = datetime.utcnow()
try:
has_running_word_job = _has_running_word_clean_job()
candidates = (
db.session.query(KbJob)
.filter(KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')), KbJob.status == 'queued')
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
.with_for_update(skip_locked=True)
.limit(20)
.all()
)
except OperationalError:
db.session.rollback()
logger.exception('failed to claim next kb job')
return None
job = next(
(
item for item in candidates
if not (has_running_word_job and _is_word_clean_job(item))
),
None,
)
if not job:
db.session.rollback()
return None
job.status = 'running'
job.started_at = job.started_at or now
job.progress = max(int(job.progress or 0), 1)
if job.job_type == 'clean':
job.message = 'worker 已领取 Word 串行清洗任务' if _is_word_clean_job(job) else 'worker 已领取清洗任务'
elif job.job_type == 'sync_dify':
job.message = 'worker 已领取同步任务'
else:
job.message = 'worker 已领取路径上传任务'
db.session.commit()
return job
def process_next_kb_job() -> tuple[bool, str]:
# 先回收历史卡死的 running 任务,再领取下一条 queued 任务
recover_stale_running_jobs()
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()
)
job = claim_next_kb_job()
if not job:
return False, 'no_job'
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job, run_sync_job
if job.job_type == 'path_upload':
return run_path_upload_job(job.id)
if job.job_type == 'sync_dify':
return run_sync_job(job.id)
return run_clean_job(job.id)
@@ -85,12 +85,91 @@ def _safe_storage_filename(filename: str) -> str:
return f'{safe_stem}{suffix}'
def _safe_display_filename(filename: str) -> str:
candidate = Path(filename or '').name.strip()
if not candidate:
return 'uploaded_file'
invalid_chars = '\\/:*?"<>|'
sanitized = ''.join('_' if ch in invalid_chars else ch for ch in candidate).strip()
return sanitized or 'uploaded_file'
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 _resolve_path_upload_display_name(relative_path: str, original_name: str) -> str:
relative_name = Path(str(relative_path or '').replace('\\', '/')).name.strip()
if relative_name:
return relative_name
original_leaf = Path(original_name or '').name.strip()
if original_leaf:
return original_leaf
return 'uploaded_file'
def _resolve_clean_display_filename(version: KbDocumentVersion, source_path: Path) -> str:
document_title = _safe_display_filename(str(getattr(version.document, 'title', '') or ''))
if document_title:
title_path = Path(document_title)
if title_path.suffix:
return document_title
normalized_source_name = _normalized_source_filename(version, source_path)
source_suffix = Path(normalized_source_name).suffix
return f'{document_title}{source_suffix}' if source_suffix else document_title
return _safe_display_filename(_normalized_source_filename(version, source_path))
def _normalize_markdown_title_candidate(value: str) -> str:
text = str(value or '').strip()
if not text:
return ''
if text.startswith('#'):
text = text.lstrip('#').strip()
return text
def _rewrite_markdown_title(cleaned_file_path: str | None, *, preferred_title: str, fallback_source_name: str) -> None:
if not cleaned_file_path:
return
cleaned_path = Path(cleaned_file_path)
if cleaned_path.suffix.lower() != '.md' or not cleaned_path.exists():
return
preferred_stem = Path(preferred_title or '').stem.strip()
if not preferred_stem:
return
fallback_candidates = {
Path(fallback_source_name or '').stem.strip(),
Path(cleaned_path.stem or '').stem.strip(),
}
fallback_candidates = {item for item in fallback_candidates if item}
if not fallback_candidates:
return
lines = cleaned_path.read_text(encoding='utf-8', errors='ignore').splitlines()
for index, raw_line in enumerate(lines):
stripped_line = raw_line.strip()
if not stripped_line:
continue
normalized_line = _normalize_markdown_title_candidate(stripped_line)
if normalized_line not in fallback_candidates or normalized_line == preferred_stem:
return
if stripped_line.startswith('#'):
prefix = raw_line[: len(raw_line) - len(raw_line.lstrip())]
heading_prefix = raw_line[len(prefix):].split(normalized_line, 1)[0]
lines[index] = f'{prefix}{heading_prefix}{preferred_stem}'
else:
prefix = raw_line[: len(raw_line) - len(raw_line.lstrip())]
lines[index] = f'{prefix}{preferred_stem}'
cleaned_path.write_text('\n'.join(lines) + ('\n' if lines else ''), encoding='utf-8')
return
return
def _get_or_create_document(*, group_id: int, title: str, description: str | None, user_id: int | None) -> KbDocument:
document = (
db.session.query(KbDocument)
@@ -145,7 +224,7 @@ def _register_document_version_from_staged_file(
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'
display_name = _resolve_path_upload_display_name(relative_path, original_name)
if _find_existing_active_document(group_id=group_id, title=display_name):
raise FileExistsError('上传失败,文件已存在')
document = _get_or_create_document(
@@ -155,11 +234,12 @@ def _register_document_version_from_staged_file(
user_id=user_id,
)
version_no = _next_version_no(document)
source_file_name = _safe_storage_filename(original_name)
source_file_name = display_name
stored_file_name = _safe_display_filename(display_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
target_path = version_dir / stored_file_name
shutil.copy2(staged_path, target_path)
sha256, file_size = _hash_file(target_path)
@@ -375,13 +455,18 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
warnings = []
try:
normalized_name = _normalized_source_filename(version, source_path)
normalized_name = _resolve_clean_display_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)
_rewrite_markdown_title(
result.get('cleaned_file_path'),
preferred_title=str(getattr(version.document, 'title', '') or ''),
fallback_source_name=str(version.source_file_name or source_path.name),
)
job_message = '真实清洗结果已生成'
except Exception as exc:
# soffice 超时等不可恢复错误:直接失败,避免回退占位结果掩盖问题
+1 -1
View File
@@ -16,7 +16,7 @@ class MinioService:
secret_key=cfg.MINIO_SECRET_KEY,
secure=cfg.MINIO_SECURE,
)
self.bucket_name = cfg.MINIO_BUCKET_NAME
self.bucket_name = cfg.MINIO_AGENT_GUIDES_BUCKET
self._ensure_bucket_exists()
def _ensure_bucket_exists(self):
+12 -6
View File
@@ -7,6 +7,7 @@ from flask import current_app, has_app_context
class Text2SQLService:
_schema_text = None
_oracle_client_initialized = False
_oracle_dll_handles = []
@staticmethod
def _backend_dir() -> str:
@@ -86,6 +87,9 @@ class Text2SQLService:
cls._prepend_env_path("DYLD_LIBRARY_PATH", target_lib_dir)
elif system_name == "Windows":
cls._prepend_env_path("PATH", target_lib_dir)
if hasattr(os, "add_dll_directory"):
handle = os.add_dll_directory(target_lib_dir)
cls._oracle_dll_handles.append(handle)
except Exception as exc:
cls._log("warning", f"Failed to prepare Oracle runtime env: {exc}")
@@ -108,9 +112,9 @@ class Text2SQLService:
if platform.system() == 'Windows' and target_lib_dir and not target_lib_dir.isascii():
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir):
if os.path.exists(target_lib_dir):
os.makedirs(temp_dir, exist_ok=True)
shutil.copytree(target_lib_dir, safe_lib_dir)
shutil.copytree(target_lib_dir, safe_lib_dir, dirs_exist_ok=True)
target_lib_dir = safe_lib_dir
cls._prepare_oracle_runtime_env(target_lib_dir)
@@ -185,16 +189,18 @@ class Text2SQLService:
import tempfile
target_lib_dir = cls._get_oracle_client_dir()
cls._prepare_oracle_runtime_env(target_lib_dir)
if platform.system() == 'Windows' and target_lib_dir:
# OCI C-library fails to load if path contains non-ASCII.
if not target_lib_dir.isascii():
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir):
if os.path.exists(target_lib_dir):
os.makedirs(temp_dir, exist_ok=True)
shutil.copytree(target_lib_dir, safe_lib_dir)
shutil.copytree(target_lib_dir, safe_lib_dir, dirs_exist_ok=True)
target_lib_dir = safe_lib_dir
cls._prepare_oracle_runtime_env(target_lib_dir)
if target_lib_dir:
oracledb.init_oracle_client(lib_dir=target_lib_dir)
@@ -379,7 +385,6 @@ class Text2SQLService:
- 严禁生成任何 INSERT、UPDATE、DELETE、MERGE、ALTER、DROP、TRUNCATE、CREATE 语句。
- 仅允许输出单条 SELECT 或 WITH 开头的查询。
- 必须使用 Schema 中出现的精确表名,包含完整前缀,如 ERP_VIEW_USER.ERP_FAJ_FILE_V。
- 如果用户查询的是列表明细而非聚合总数(如“列出...”、“有哪些...”),你必须强制在 SQL 结尾添加 FETCH FIRST 50 ROWS ONLY,避免一次性返回几十万条数据导致系统崩溃。
- 必须只使用 Schema 中明确出现过的字段名,禁止臆造通用字段名,例如 FILE_TYPE、STATUS_NAME、AMOUNT 等。
- 优先选择最相关字段,避免 SELECT *。
- 当问题涉及“多少、总额、平均值、数量、占比、排名”时,请使用清晰的聚合逻辑与英文别名。
@@ -459,7 +464,8 @@ class Text2SQLService:
cursor.execute(sql)
columns = [col[0] for col in cursor.description]
rows = cursor.fetchall()
# Use fetchmany(50) instead of LLM-generated FETCH FIRST to support older Oracle versions
rows = cursor.fetchmany(50)
cursor.close()
connection.close()