feat: excel清理优化
This commit is contained in:
1 parent
87ac58c394
commit
ca5782b6cd
16 files changed
+132
-27
No files matched your search
@@ -135,7 +135,11 @@ class KbDifySyncService:
|
||||
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'))
|
||||
# 普通文档与 Excel/CSV 使用独立 Token 上限,避免放大表格分段影响制度类文档。
|
||||
self.segment_max_tokens = int(str(settings.get('KB_DIFY_SEGMENT_MAX_TOKENS') or '600'))
|
||||
self.segment_max_tokens_excel = int(
|
||||
str(settings.get('KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL') or '1200')
|
||||
)
|
||||
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
|
||||
@@ -148,9 +152,11 @@ class KbDifySyncService:
|
||||
if ext in _EXCEL_SOURCE_EXTENSIONS:
|
||||
mode = self.process_mode_excel
|
||||
separator = self.segment_separator_excel
|
||||
max_tokens = self.segment_max_tokens_excel
|
||||
else:
|
||||
mode = self.process_mode
|
||||
separator = self.segment_separator
|
||||
max_tokens = self.segment_max_tokens
|
||||
|
||||
if mode != 'custom':
|
||||
return {'mode': 'automatic'}
|
||||
@@ -164,7 +170,7 @@ class KbDifySyncService:
|
||||
],
|
||||
'segmentation': {
|
||||
'separator': separator,
|
||||
'max_tokens': self.segment_max_tokens,
|
||||
'max_tokens': max_tokens,
|
||||
'chunk_overlap': self.segment_chunk_overlap,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -36,7 +36,10 @@ SETTING_DEFAULTS = {
|
||||
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
|
||||
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
|
||||
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
|
||||
# 普通文档的 Dify 自定义分段上限;保持原值,避免制度类文档分段变大。
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS': '600',
|
||||
# Excel/CSV 专用的 Dify 分段上限;表格行较长时允许一个 Segment 容纳更多完整行。
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL': '1200',
|
||||
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100',
|
||||
'KB_DIFY_REMOVE_URLS': 'false',
|
||||
}
|
||||
@@ -98,6 +101,12 @@ def _normalize_retrieval_settings(values: dict[str, object]) -> dict[str, object
|
||||
minimum=1,
|
||||
maximum=10000,
|
||||
)
|
||||
excel_segment_max_tokens = _normalize_positive_integer_setting(
|
||||
normalized,
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL',
|
||||
minimum=1,
|
||||
maximum=10000,
|
||||
)
|
||||
segment_chunk_overlap = _normalize_positive_integer_setting(
|
||||
normalized,
|
||||
'KB_DIFY_SEGMENT_CHUNK_OVERLAP',
|
||||
@@ -108,12 +117,22 @@ def _normalize_retrieval_settings(values: dict[str, object]) -> dict[str, object
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS',
|
||||
default=600,
|
||||
)
|
||||
# Excel 专用上限独立校验;未提交时读取已保存值,避免 PATCH 单字段时误判。
|
||||
effective_excel_segment_max_tokens = (
|
||||
excel_segment_max_tokens
|
||||
if excel_segment_max_tokens is not None
|
||||
else _get_positive_integer_setting('KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL', default=1200)
|
||||
)
|
||||
effective_segment_chunk_overlap = segment_chunk_overlap if segment_chunk_overlap is not None else _get_positive_integer_setting(
|
||||
'KB_DIFY_SEGMENT_CHUNK_OVERLAP',
|
||||
default=100,
|
||||
)
|
||||
if effective_segment_chunk_overlap >= effective_segment_max_tokens:
|
||||
raise ValidationError('KB_DIFY_SEGMENT_CHUNK_OVERLAP 必须小于 KB_DIFY_SEGMENT_MAX_TOKENS')
|
||||
if effective_segment_chunk_overlap >= effective_excel_segment_max_tokens:
|
||||
raise ValidationError(
|
||||
'KB_DIFY_SEGMENT_CHUNK_OVERLAP 必须小于 KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL'
|
||||
)
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
@@ -29,12 +29,15 @@ class TableConfig(BaseModel):
|
||||
"""
|
||||
Excel/CSV 表格线性化配置。
|
||||
|
||||
用途:约束进入 Dify 前每段可容纳的完整原始行总字符数。
|
||||
逻辑:table_linearize 在 Excel/CSV 分支读取该值;Dify 同步仍按空行分段,
|
||||
因此本值应低于 Dify 的 max_tokens 能承载的保守字符数。
|
||||
用途:约束 Excel/CSV 表格进入 Dify 前,每个段可容纳的完整原始数据行总字符数。
|
||||
逻辑:仅 table_linearize 的表格分支读取该值;它在加入下一行会超限时于上一完整行结束,
|
||||
保证一条原始 Excel 行不会被切断。Dify 仍按空行分段,因此本值应低于
|
||||
Dify 的 max_tokens 能承载的保守字符数,避免 Dify 二次截断表格行。
|
||||
"""
|
||||
|
||||
segment_max_chars: int = 480
|
||||
# Excel/CSV 表格专用:每段最多累计约 1000 个字符,并且只在完整数据行之间换段。
|
||||
# 该值不是普通文档的 chunk.max_chars,也不是 Dify 的 Token 上限。
|
||||
table_segment_max_chars: int = 1000
|
||||
|
||||
|
||||
class CleanConfig(BaseModel):
|
||||
|
||||
@@ -713,7 +713,7 @@ def _run_one(
|
||||
text = table_linearize.run(
|
||||
tables,
|
||||
ctx,
|
||||
segment_max_chars=cfg.table.segment_max_chars,
|
||||
table_segment_max_chars=cfg.table.table_segment_max_chars,
|
||||
)
|
||||
_mark("edkb-table-linearize", t0)
|
||||
trace_steps.append("edkb-table-linearize")
|
||||
|
||||
@@ -17,7 +17,9 @@ OWN_KWS = ["责任", "负责人", "部门", "岗位"]
|
||||
|
||||
# 列数较多时,Markdown 表格可读性较差,改为字段键值的行文本。
|
||||
WIDE_TABLE_COLS = 8
|
||||
DEFAULT_SEGMENT_MAX_CHARS = 480
|
||||
# 仅 Excel/CSV 表格分段使用:按字符累计完整原始行,防止 Dify 在单行中间二次截断。
|
||||
# 取 1000 左右可让专利类宽表通常容纳约 3~4 条数据行,减少 top-k=10 的覆盖损失。
|
||||
DEFAULT_TABLE_SEGMENT_MAX_CHARS = 1000
|
||||
|
||||
|
||||
def _find_col(headers: list[str], kws: list[str]) -> int | None:
|
||||
@@ -29,12 +31,12 @@ def _find_col(headers: list[str], kws: list[str]) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_segment_max_chars(value: int | None) -> int:
|
||||
"""归一化 Excel 段字符上限,避免非法配置导致清洗任务失败。"""
|
||||
def _normalize_table_segment_max_chars(value: int | None) -> int:
|
||||
"""归一化表格专用段字符上限,避免非法配置导致 Excel/CSV 清洗任务失败。"""
|
||||
try:
|
||||
return max(100, int(value or DEFAULT_SEGMENT_MAX_CHARS))
|
||||
return max(100, int(value or DEFAULT_TABLE_SEGMENT_MAX_CHARS))
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_SEGMENT_MAX_CHARS
|
||||
return DEFAULT_TABLE_SEGMENT_MAX_CHARS
|
||||
|
||||
|
||||
def _pack_atomic_rows(
|
||||
@@ -125,7 +127,7 @@ def _condition_action_row_lines(
|
||||
def run(
|
||||
input_data: list[dict] | dict,
|
||||
context: Context,
|
||||
segment_max_chars: int = DEFAULT_SEGMENT_MAX_CHARS,
|
||||
table_segment_max_chars: int = DEFAULT_TABLE_SEGMENT_MAX_CHARS,
|
||||
) -> str:
|
||||
"""
|
||||
将 Excel/CSV 表格线性化为“多完整行一个段”的 Markdown。
|
||||
@@ -136,13 +138,14 @@ def run(
|
||||
Args:
|
||||
input_data: loader 输出的单表或多表结构,包含 sheet、headers、rows。
|
||||
context: 当前清洗上下文,保留统一 skill 调用签名。
|
||||
segment_max_chars: 单个 Dify 段的最大字符数;不会切断超过上限的单条原始行。
|
||||
table_segment_max_chars: 仅表格使用的单个 Dify 段最大字符数;超过上限时在
|
||||
上一完整原始行结束,单条行本身超限时仍完整保留。
|
||||
|
||||
Returns:
|
||||
str: 供 clean/export 和 Dify custom segmentation 使用的 Markdown 文本。
|
||||
"""
|
||||
del context # 当前阶段不修改上下文,保留 skill 标准入参。
|
||||
max_chars = _normalize_segment_max_chars(segment_max_chars)
|
||||
max_chars = _normalize_table_segment_max_chars(table_segment_max_chars)
|
||||
tables = input_data if isinstance(input_data, list) else [input_data]
|
||||
segments: list[str] = []
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ def _make_service(monkeypatch, **overrides):
|
||||
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
|
||||
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS': '600',
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL': '1200',
|
||||
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100',
|
||||
'KB_DIFY_REMOVE_URLS': 'false',
|
||||
}
|
||||
@@ -36,7 +37,8 @@ def test_build_process_rule_xlsx_uses_custom_segmentation(monkeypatch):
|
||||
assert rule['mode'] == 'custom'
|
||||
assert rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
# 断言完整行仍由空行隔开,避免表格字段在 Dify 中被拆散。
|
||||
assert rule['rules']['segmentation']['max_tokens'] == 600
|
||||
# Excel 使用独立上限,允许一个 Segment 容纳更多完整表格行。
|
||||
assert rule['rules']['segmentation']['max_tokens'] == 1200
|
||||
assert rule['rules']['segmentation']['chunk_overlap'] == 100
|
||||
assert rule['rules']['pre_processing_rules'][1]['enabled'] is False
|
||||
|
||||
@@ -72,7 +74,7 @@ def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
|
||||
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'] == 600
|
||||
assert process_rule['rules']['segmentation']['max_tokens'] == 1200
|
||||
|
||||
|
||||
def test_build_process_rule_uses_configured_segment_limits(monkeypatch):
|
||||
@@ -91,6 +93,18 @@ def test_build_process_rule_uses_configured_segment_limits(monkeypatch):
|
||||
}
|
||||
|
||||
|
||||
def test_build_process_rule_keeps_excel_limit_separate_from_documents(monkeypatch):
|
||||
service = _make_service(
|
||||
monkeypatch,
|
||||
KB_DIFY_SEGMENT_MAX_TOKENS='900',
|
||||
KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL='1500',
|
||||
)
|
||||
|
||||
# 普通文档仍使用普通配置,Excel 才使用 Excel 专用配置。
|
||||
assert service._build_process_rule('docx')['rules']['segmentation']['max_tokens'] == 900
|
||||
assert service._build_process_rule('xlsx')['rules']['segmentation']['max_tokens'] == 1500
|
||||
|
||||
|
||||
def test_create_dataset_uses_admin_retrieval_settings(monkeypatch):
|
||||
service = _make_service(
|
||||
monkeypatch,
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
"""Tests for Excel table linearization chunk boundaries."""
|
||||
"""
|
||||
backend/tests/test_table_linearize.py
|
||||
|
||||
用途:验证 Excel/CSV 表格线性化的行原子性和 Dify 段边界。
|
||||
依赖:edkb_system.skills.table_linearize、Context。
|
||||
逻辑:覆盖窄表、宽表和条件动作表;确保表格专用字符上限只在完整原始行之间换段。
|
||||
"""
|
||||
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():
|
||||
def test_condition_action_table_keeps_rows_together_until_table_limit():
|
||||
tables = [
|
||||
{
|
||||
'sheet': 'Rules',
|
||||
@@ -18,12 +24,13 @@ def test_condition_action_table_uses_double_newline_between_bullets():
|
||||
]
|
||||
output = table_linearize.run(tables, Context())
|
||||
|
||||
assert '\n\n- 当' in output
|
||||
# 段内使用单换行保留多条完整行;空行只用于真正的 Dify 段边界。
|
||||
assert '\n- 当' in output
|
||||
assert output.count('- 当') == 2
|
||||
assert output.startswith('## Sheet: Rules')
|
||||
|
||||
|
||||
def test_narrow_table_separates_data_rows_with_double_newline():
|
||||
def test_narrow_table_keeps_data_rows_in_one_dify_segment_by_default():
|
||||
tables = [
|
||||
{
|
||||
'sheet': 'Data',
|
||||
@@ -37,7 +44,7 @@ def test_narrow_table_separates_data_rows_with_double_newline():
|
||||
output = table_linearize.run(tables, Context())
|
||||
|
||||
assert '| --- | --- | --- |' in output
|
||||
assert '\n\n|' in output
|
||||
assert '\n| 1 | 2 | 3 |\n| 4 | 5 | 6 |' in output
|
||||
assert '| 1 | 2 | 3 |' in output
|
||||
assert '| 4 | 5 | 6 |' in output
|
||||
assert '【行】' not in output
|
||||
@@ -51,7 +58,7 @@ def test_wide_table_uses_row_text_blocks():
|
||||
output = table_linearize.run(tables, Context())
|
||||
|
||||
assert '【行】' in output
|
||||
assert '\n\n' in output
|
||||
assert '\n- 【行】' in output
|
||||
assert output.count('【行】') == 3
|
||||
assert '列1=10' in output
|
||||
assert '|' not in output.split('## Sheet: Wide')[-1]
|
||||
@@ -68,3 +75,31 @@ def test_multiple_sheets_separated_by_double_newline():
|
||||
assert '## Sheet: S2' in output
|
||||
assert output.index('## Sheet: S2') > output.index('## Sheet: S1')
|
||||
assert '\n\n## Sheet: S2' in output
|
||||
|
||||
|
||||
def test_table_segment_max_chars_groups_complete_rows_and_repeats_headers():
|
||||
"""
|
||||
表格专用字符上限必须只在完整行之间切段,并为后续段补回列语义。
|
||||
|
||||
核心逻辑:以刚好容纳一条数据行的上限运行;第二条较长数据行进入新段,
|
||||
断言其文本未被截取且新段含工作表名和表头。
|
||||
"""
|
||||
tables = [
|
||||
{
|
||||
'sheet': 'Honors',
|
||||
'headers': ['序号', '荣誉', '认定单位'],
|
||||
'rows': [
|
||||
['1', '国家级专精特新“小巨人”企业', '工业和信息化部'],
|
||||
['2', '2020年度开发区智能化改造和数字化转型先进企业', '中共吴江经济技术开发区工作委员会'],
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
output = table_linearize.run(tables, Context(), table_segment_max_chars=80)
|
||||
segments = output.strip().split('\n\n')
|
||||
|
||||
# 关键断言:两条原始数据行分别完整出现,长行不会被 max_chars 从中间截断。
|
||||
assert '| 1 | 国家级专精特新“小巨人”企业 | 工业和信息化部 |' in segments[0]
|
||||
assert '| 2 | 2020年度开发区智能化改造和数字化转型先进企业 | 中共吴江经济技术开发区工作委员会 |' in segments[1]
|
||||
# 后段必须带回 Sheet 和表头,使 Dify 单独召回时仍能理解每列含义。
|
||||
assert segments[1].startswith('## Sheet: Honors\n| 序号 | 荣誉 | 认定单位 |')
|
||||
Reference in new issue
Block a user