diff --git a/backend/app/services/knowledge_cleaning/dify_sync_service.py b/backend/app/services/knowledge_cleaning/dify_sync_service.py index e28f217a..bf8b5cc0 100644 --- a/backend/app/services/knowledge_cleaning/dify_sync_service.py +++ b/backend/app/services/knowledge_cleaning/dify_sync_service.py @@ -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( diff --git a/backend/app/services/knowledge_cleaning/tasks.py b/backend/app/services/knowledge_cleaning/tasks.py index 4708f821..3e2df93e 100644 --- a/backend/app/services/knowledge_cleaning/tasks.py +++ b/backend/app/services/knowledge_cleaning/tasks.py @@ -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 超时等不可恢复错误:直接失败,避免回退占位结果掩盖问题