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

@@ -0,0 +1,86 @@
"""Tests for Dify sync process_rule selection (Excel custom vs default automatic)."""
from __future__ import annotations
from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module
def _make_service(monkeypatch, **overrides):
settings = {
'DIFY_API_BASE': 'http://dify.example/v1',
'DIFY_API_KEY': 'dataset-test-key',
'KB_DIFY_PERMISSION': 'only_me',
'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',
}
settings.update(overrides)
monkeypatch.setattr(dify_sync_module, 'get_kb_dify_settings', lambda: settings)
return dify_sync_module.KbDifySyncService()
def test_build_process_rule_xlsx_uses_custom_segmentation(monkeypatch):
service = _make_service(monkeypatch)
rule = service._build_process_rule('xlsx')
assert rule['mode'] == 'custom'
assert rule['rules']['segmentation']['separator'] == '\n\n'
assert rule['rules']['segmentation']['max_tokens'] == 800
assert rule['rules']['segmentation']['chunk_overlap'] == 50
assert rule['rules']['pre_processing_rules'][1]['enabled'] is False
def test_build_process_rule_docx_defaults_to_automatic(monkeypatch):
service = _make_service(monkeypatch)
rule = service._build_process_rule('docx')
assert rule == {'mode': 'automatic'}
def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
service = _make_service(monkeypatch)
captured: dict = {}
def fake_request(method, path, **kwargs):
captured['method'] = method
captured['path'] = path
captured['json'] = kwargs.get('json')
return {'document': {'id': 'doc-1', 'name': 'demo.xlsx'}}
monkeypatch.setattr(service, '_request', fake_request)
service.create_document_by_text(
dataset_id='ds-1',
name='demo.xlsx',
text='row one\n\nrow two',
source_ext='xlsx',
)
assert captured['method'] == 'POST'
assert captured['path'] == '/datasets/ds-1/document/create-by-text'
process_rule = captured['json']['process_rule']
assert process_rule['mode'] == 'custom'
assert process_rule['rules']['segmentation']['separator'] == '\n\n'
assert process_rule['rules']['segmentation']['max_tokens'] == 800
def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch):
service = _make_service(monkeypatch, KB_DIFY_REMOVE_URLS='true')
rule = service._build_process_rule('csv')
remove_urls = next(
item for item in rule['rules']['pre_processing_rules']
if item['id'] == 'remove_urls_emails'
)
assert remove_urls['enabled'] is True
def test_resolve_source_file_ext_from_filename():
class _Version:
source_file_ext = None
source_file_name = 'report.XLSX'
assert dify_sync_module.resolve_source_file_ext(_Version()) == 'xlsx'
+62
View File
@@ -0,0 +1,62 @@
"""Tests for persisting edkb 04_chunks.jsonl into KB version directories."""
from __future__ import annotations
from pathlib import Path
from app.services.knowledge_cleaning import edkb_adapter
def _fake_build_knowledge(file_path: Path, output_dir: Path, config, cache_dir):
out_sub = output_dir / 'sample'
out_sub.mkdir(parents=True, exist_ok=True)
(out_sub / '03_clean.md').write_text(
'## Sheet: Data\n\n| A | B |\n| --- | --- |\n\n| 1 | 2 |\n',
encoding='utf-8',
)
(out_sub / '04_chunks.jsonl').write_text(
'{"id":"chunk-0","text":"row one"}\n{"id":"chunk-1","text":"row two"}\n',
encoding='utf-8',
)
chunks_dir = out_sub / 'chunks'
chunks_dir.mkdir()
(chunks_dir / 'chunk_0000.md').write_text('row one\n', encoding='utf-8')
(chunks_dir / 'chunk_0001.md').write_text('row two\n', encoding='utf-8')
return [{'status': 'success', 'file': str(file_path)}]
def test_build_clean_result_persists_chunks_jsonl(monkeypatch, tmp_path):
source_path = tmp_path / 'sample.xlsx'
source_path.write_bytes(b'fake-xlsx-content')
target_dir = tmp_path / 'output'
monkeypatch.setattr('edkb_system.controller.build_knowledge', _fake_build_knowledge)
class _FakeConfig:
@staticmethod
def load(_path):
return _FakeConfig()
monkeypatch.setattr('edkb_system.config.SystemConfig', _FakeConfig)
result = edkb_adapter.build_clean_result(source_path, target_dir)
chunks_path = target_dir / '04_chunks.jsonl'
assert chunks_path.exists()
assert (target_dir / 'document.md').exists()
assert (target_dir / 'chunks' / 'chunk_0000.md').exists()
assert (target_dir / 'chunks' / 'chunk_0001.md').exists()
assert result['chunks_file_path'] == str(chunks_path)
assert result['chunks_count'] == 2
def test_persist_debug_chunks_skips_missing_jsonl(tmp_path):
output_root = tmp_path / 'output'
output_root.mkdir()
target_dir = tmp_path / 'target'
target_dir.mkdir()
chunks_file_path, chunks_count = edkb_adapter._persist_debug_chunks(output_root, target_dir)
assert chunks_file_path is None
assert chunks_count is None
assert not (target_dir / '04_chunks.jsonl').exists()
+23
View File
@@ -0,0 +1,23 @@
"""Tests for edkb per-file timeout selection."""
from __future__ import annotations
from pathlib import Path
from edkb_system.controller import _file_timeout_sec
def test_excel_skips_spawn_timeout_wrapper(monkeypatch):
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
assert _file_timeout_sec(Path('report.xlsx')) is None
assert _file_timeout_sec(Path('data.csv')) is None
def test_word_still_uses_word_timeout(monkeypatch):
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
monkeypatch.setenv('EDKB_WORD_FILE_TIMEOUT_SEC', '420')
assert _file_timeout_sec(Path('manual.docx')) == 420
def test_other_formats_use_global_timeout(monkeypatch):
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
assert _file_timeout_sec(Path('slides.pptx')) == 180
+3
View File
@@ -27,8 +27,11 @@ def test_build_clean_result_generates_markdown_for_xlsx(tmp_path):
assert result['cleaned_preview_path'] == str(cleaned_path)
content = cleaned_path.read_text(encoding='utf-8')
assert content.strip()
assert '供应链' in content
assert '能耗' in content
# Narrow Excel tables should expose Dify-friendly row boundaries.
assert '\n\n|' in content or '| 供应链 | 能耗 |' in content
def test_normalized_source_filename_infers_xlsx_extension(tmp_path):
+70
View File
@@ -0,0 +1,70 @@
"""Tests for Excel table linearization chunk boundaries."""
from __future__ import annotations
from edkb_system.contracts import Context
from edkb_system.skills import table_linearize
def test_condition_action_table_uses_double_newline_between_bullets():
tables = [
{
'sheet': 'Rules',
'headers': ['条件', '处理', '责任'],
'rows': [
['库存不足', '补货', '采购部'],
['价格变动', '更新报价', '销售部'],
],
}
]
output = table_linearize.run(tables, Context())
assert '\n\n- 当' in output
assert output.count('- 当') == 2
assert output.startswith('## Sheet: Rules')
def test_narrow_table_separates_data_rows_with_double_newline():
tables = [
{
'sheet': 'Data',
'headers': ['A', 'B', 'C'],
'rows': [
['1', '2', '3'],
['4', '5', '6'],
],
}
]
output = table_linearize.run(tables, Context())
assert '| --- | --- | --- |' in output
assert '\n\n|' in output
assert '| 1 | 2 | 3 |' in output
assert '| 4 | 5 | 6 |' in output
assert '【行】' not in output
def test_wide_table_uses_row_text_blocks():
headers = [f'列{i}' for i in range(1, 11)]
rows = [[str(i * 10 + j) for j in range(10)] for i in range(1, 4)]
tables = [{'sheet': 'Wide', 'headers': headers, 'rows': rows}]
output = table_linearize.run(tables, Context())
assert '【行】' in output
assert '\n\n' in output
assert output.count('【行】') == 3
assert '列1=10' in output
assert '|' not in output.split('## Sheet: Wide')[-1]
def test_multiple_sheets_separated_by_double_newline():
tables = [
{'sheet': 'S1', 'headers': ['X'], 'rows': [['a']]},
{'sheet': 'S2', 'headers': ['Y'], 'rows': [['b']]},
]
output = table_linearize.run(tables, Context())
assert '## Sheet: S1' in output
assert '## Sheet: S2' in output
assert output.index('## Sheet: S2') > output.index('## Sheet: S1')
assert '\n\n## Sheet: S2' in output