Files
syops/backend/edkb_system/skills/table_linearize.py
T
2026-08-20 19:37:09 +08:00

184 lines
7.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
edkb_system/skills/table_linearize.py
用途:将 Excel/CSV 结构化表格转换为供 Dify 自定义分段使用的 Markdown。
依赖:edkb_system.contracts.Context、controller 的 Excel/CSV loader 编排。
逻辑:每个 Dify 段由工作表上下文、表头和若干完整原始行组成;controller 随后清洗并导出 document.md,
dify_sync_service 以空行作为段分隔符上传,因而不能在此拆开任何一条原始行。
"""
from __future__ import annotations
from edkb_system.contracts import Context
COND_KWS = ["条件", "判定", "if", "IF"]
ACT_KWS = ["处理", "动作", "措施", "结果", "输出"]
OWN_KWS = ["责任", "负责人", "部门", "岗位"]
# 列数较多时,Markdown 表格可读性较差,改为字段键值的行文本。
WIDE_TABLE_COLS = 8
# 仅 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:
"""按候选关键词定位表头列,用于将条件-动作表转为自然语言行。"""
for i, header in enumerate(headers):
normalized = (header or "").lower()
if any(keyword.lower() in normalized for keyword in kws):
return i
return None
def _normalize_table_segment_max_chars(value: int | None) -> int:
"""归一化表格专用段字符上限,避免非法配置导致 Excel/CSV 清洗任务失败。"""
try:
return max(100, int(value or DEFAULT_TABLE_SEGMENT_MAX_CHARS))
except (TypeError, ValueError):
return DEFAULT_TABLE_SEGMENT_MAX_CHARS
def _pack_atomic_rows(
*,
sheet_name: str,
row_lines: list[str],
header_lines: list[str] | None,
max_chars: int,
) -> list[str]:
"""
将连续的完整 Excel 行组装为 Dify 段,绝不在单行中间按字符截断。
核心逻辑:每个段重复工作表名和(如有)表头,段内用单换行保留多行表格,
段间用两个换行供 Dify custom segmentation 识别。下一整行加入后超限时,
当前段立即结束,整行移动到下一段;单行本身超限时仍作为一个完整段保留。
Args:
sheet_name: 来源工作表名,用于每段保留检索语境。
row_lines: 已线性化且每项对应一条原始数据行的文本。
header_lines: 窄表的 Markdown 表头;键值/规则文本表为 None。
max_chars: 单段最大字符数,包含工作表名、表头和数据行。
Returns:
list[str]: 可用两个换行拼接的 Dify 段列表。
"""
prefix_lines = [f"## Sheet: {sheet_name}"]
if header_lines:
prefix_lines.extend(header_lines)
prefix = "\n".join(prefix_lines)
if not row_lines:
return [prefix]
segments: list[str] = []
current = prefix
for row_line in row_lines:
candidate = f"{current}\n{row_line}"
if current != prefix and len(candidate) > max_chars:
segments.append(current)
# [STEP 1] 新段从完整原始行开始,禁止切取 row_line 的字符子串。
current = f"{prefix}\n{row_line}"
continue
current = candidate
segments.append(current)
return segments
def _narrow_table_row_lines(headers: list[str], rows: list[list[str]]) -> list[str]:
"""将窄表的每条数据行渲染为一条 Markdown 表格行,作为不可拆分单元。"""
return [
"| " + " | ".join(row[i] if i < len(row) else "" for i in range(len(headers))) + " |"
for row in rows
]
def _wide_table_row_lines(headers: list[str], rows: list[list[str]]) -> list[str]:
"""将宽表的一条原始行转为字段键值文本,避免宽 Markdown 表格降低召回质量。"""
row_lines: list[str] = []
for row in rows:
pairs = [
f"{header}={row[i] if i < len(row) else ''}"
for i, header in enumerate(headers)
]
row_lines.append("- 【行】" + ";".join(pairs) + "。")
return row_lines
def _condition_action_row_lines(
headers: list[str],
rows: list[list[str]],
cond_idx: int,
act_idx: int,
owner_idx: int | None,
) -> list[str]:
"""将条件-动作表的每个原始行转为一条完整、可独立理解的规则文本。"""
row_lines: list[str] = []
for row in rows:
condition = row[cond_idx] if cond_idx < len(row) else "满足条件"
action = row[act_idx] if act_idx < len(row) else "执行处理"
owner = row[owner_idx] if owner_idx is not None and owner_idx < len(row) else "相关责任方"
row_lines.append(
f"- 当 {condition or '满足条件'} 时,{owner or '相关责任方'} 执行 {action or '执行处理'}。"
)
return row_lines
def run(
input_data: list[dict] | dict,
context: Context,
table_segment_max_chars: int = DEFAULT_TABLE_SEGMENT_MAX_CHARS,
) -> str:
"""
将 Excel/CSV 表格线性化为“多完整行一个段”的 Markdown。
核心逻辑:识别规则表、宽表和普通窄表后,统一以原始数据行作为不可拆分原子;
以最大字符数装箱并在每段重复工作表/表头上下文,段间仅插入 ``\n\n``。
Args:
input_data: loader 输出的单表或多表结构,包含 sheet、headers、rows。
context: 当前清洗上下文,保留统一 skill 调用签名。
table_segment_max_chars: 仅表格使用的单个 Dify 段最大字符数;超过上限时在
上一完整原始行结束,单条行本身超限时仍完整保留。
Returns:
str: 供 clean/export 和 Dify custom segmentation 使用的 Markdown 文本。
"""
del context # 当前阶段不修改上下文,保留 skill 标准入参。
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] = []
for table in tables:
sheet_name = str(table.get("sheet", "Sheet1")).strip() or "Sheet1"
headers = [str(value).strip() for value in table.get("headers", [])]
rows = [[str(cell).strip() for cell in row] for row in table.get("rows", [])]
cond_idx = _find_col(headers, COND_KWS)
act_idx = _find_col(headers, ACT_KWS)
owner_idx = _find_col(headers, OWN_KWS)
if cond_idx is not None and act_idx is not None:
row_lines = _condition_action_row_lines(headers, rows, cond_idx, act_idx, owner_idx)
header_lines = None
elif len(headers) > WIDE_TABLE_COLS:
row_lines = _wide_table_row_lines(headers, rows)
header_lines = None
else:
normalized_headers = [header or "-" for header in headers]
row_lines = _narrow_table_row_lines(normalized_headers, rows)
header_lines = [
"| " + " | ".join(normalized_headers) + " |",
"| " + " | ".join(["---"] * len(normalized_headers)) + " |",
]
segments.extend(
_pack_atomic_rows(
sheet_name=sheet_name,
row_lines=row_lines,
header_lines=header_lines,
max_chars=max_chars,
)
)
return "\n\n".join(segments).strip() + "\n"