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

@@ -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()