feat(pre_process_file):解决hxops上传excel行截断的问题,由markdown换为命中更好的key=value的方式;dify同步custom;行间\n\n,数据行单独成块;

This commit is contained in:
super committed 2026-06-11 11:19:21 +08:00
1 parent a18a07ef1a
commit 67d08924a4
25 files changed
+655 -25

No files matched your search

@@ -16,6 +16,30 @@ from app.services.db_sequence import add_and_flush_with_sequence_retry
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
_EXCEL_SOURCE_EXTENSIONS = frozenset({'xlsx', 'xls', 'csv'})
def _decode_separator(value: str) -> str:
"""Turn env/AppSetting escape sequences into real separator characters."""
return str(value or '').replace('\\n', '\n').replace('\\t', '\t')
def _as_bool_setting(value: str | None) -> bool:
return str(value or '').strip().lower() in ('true', '1', 'yes', 'on')
def resolve_source_file_ext(version: KbDocumentVersion) -> str | None:
"""Lowercase extension without dot, e.g. xlsx."""
ext = str(version.source_file_ext or '').strip().lower().lstrip('.')
if ext:
return ext
name = str(version.source_file_name or '').strip()
if not name:
return None
suffix = Path(name).suffix.lower().lstrip('.')
return suffix or None
class KbDifySyncError(RuntimeError):
pass
@@ -29,8 +53,44 @@ class KbDifySyncService:
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.process_mode = str(settings.get('KB_DIFY_PROCESS_MODE') or 'automatic').strip().lower()
self.process_mode_excel = str(settings.get('KB_DIFY_PROCESS_MODE_EXCEL') or 'custom').strip().lower()
self.segment_separator = _decode_separator(str(settings.get('KB_DIFY_SEGMENT_SEPARATOR') or '\\n\\n'))
self.segment_separator_excel = _decode_separator(
str(settings.get('KB_DIFY_SEGMENT_SEPARATOR_EXCEL') or '\\n\\n')
)
self.segment_max_tokens = int(str(settings.get('KB_DIFY_SEGMENT_MAX_TOKENS') or '800'))
self.segment_chunk_overlap = int(str(settings.get('KB_DIFY_SEGMENT_CHUNK_OVERLAP') or '50'))
self.remove_urls_emails = _as_bool_setting(settings.get('KB_DIFY_REMOVE_URLS'))
self.timeout = 60
def _build_process_rule(self, source_ext: str | None = None) -> dict:
ext = str(source_ext or '').strip().lower().lstrip('.')
if ext in _EXCEL_SOURCE_EXTENSIONS:
mode = self.process_mode_excel
separator = self.segment_separator_excel
else:
mode = self.process_mode
separator = self.segment_separator
if mode != 'custom':
return {'mode': 'automatic'}
return {
'mode': 'custom',
'rules': {
'pre_processing_rules': [
{'id': 'remove_extra_spaces', 'enabled': True},
{'id': 'remove_urls_emails', 'enabled': self.remove_urls_emails},
],
'segmentation': {
'separator': separator,
'max_tokens': self.segment_max_tokens,
'chunk_overlap': self.segment_chunk_overlap,
},
},
}
def _headers(self) -> dict[str, str]:
if not self.base_url:
raise KbDifySyncError('DIFY_API_BASE 未配置')
@@ -100,21 +160,36 @@ class KbDifySyncService:
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:
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
source_ext: str | None = None,
) -> dict:
payload = {
'name': name,
'text': text,
'indexing_technique': self.indexing_technique,
'doc_form': self.doc_form,
'process_rule': {'mode': 'automatic'},
'process_rule': self._build_process_rule(source_ext),
}
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:
def update_document_by_text(
self,
*,
dataset_id: str,
document_id: str,
name: str,
text: str,
source_ext: str | None = None,
) -> dict:
payload = {
'name': name,
'text': text,
'process_rule': {'mode': 'automatic'},
'process_rule': self._build_process_rule(source_ext),
}
return self._request(
'POST',
@@ -175,6 +250,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
service = KbDifySyncService()
dataset_id, dataset_name = service.ensure_dataset(group)
source_ext = resolve_source_file_ext(version)
existing_record = (
db.session.query(KbDifySyncRecord)
@@ -204,6 +280,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
dataset_id=dataset_id,
name=upload_name,
text=text,
source_ext=source_ext,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or upload_name
@@ -214,6 +291,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
document_id=existing_record.remote_document_id,
name=upload_name,
text=text,
source_ext=source_ext,
)
except KbDifySyncError as exc:
if not _is_remote_document_missing(str(exc)):
@@ -222,6 +300,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
dataset_id=dataset_id,
name=upload_name,
text=text,
source_ext=source_ext,
)
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 upload_name
@@ -230,6 +309,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
dataset_id=dataset_id,
name=upload_name,
text=text,
source_ext=source_ext,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or upload_name
@@ -52,6 +52,42 @@ def _find_generated_preview_markdown(output_root: Path) -> Path | None:
return candidates[0]
def _find_generated_chunks_jsonl(output_root: Path) -> Path | None:
candidates = [path for path in output_root.rglob('04_chunks.jsonl') if path.is_file()]
if not candidates:
return None
candidates.sort(key=lambda item: len(item.parts))
return candidates[0]
def _count_jsonl_lines(path: Path) -> int:
count = 0
with path.open(encoding='utf-8', errors='ignore') as handle:
for line in handle:
if line.strip():
count += 1
return count
def _persist_debug_chunks(output_root: Path, target_dir: Path) -> tuple[str | None, int | None]:
"""Copy edkb chunk artifacts into the KB version directory for local debugging."""
chunks_source = _find_generated_chunks_jsonl(output_root)
if not chunks_source or not chunks_source.exists():
return None, None
chunks_target = target_dir / '04_chunks.jsonl'
shutil.copy2(chunks_source, chunks_target)
chunks_dir_source = chunks_source.parent / 'chunks'
chunks_dir_target = target_dir / 'chunks'
if chunks_dir_source.is_dir():
if chunks_dir_target.exists():
shutil.rmtree(chunks_dir_target)
shutil.copytree(chunks_dir_source, chunks_dir_target)
return str(chunks_target), _count_jsonl_lines(chunks_target)
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:
@@ -141,10 +177,13 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
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')
chunks_file_path, chunks_count = _persist_debug_chunks(output_dir, target_dir)
return {
'mode': 'edkb_system',
'cleaned_file_path': str(cleaned_path),
'cleaned_preview_path': str(preview_path),
'word_count': len(content.split()),
'chunks_file_path': chunks_file_path,
'chunks_count': chunks_count,
}
@@ -20,6 +20,13 @@ SETTING_DEFAULTS = {
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
'KB_DIFY_DOC_FORM': 'text_model',
'KB_DIFY_PROCESS_MODE': 'automatic',
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
'KB_DIFY_SEGMENT_MAX_TOKENS': '800',
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50',
'KB_DIFY_REMOVE_URLS': 'false',
}