Files
syops/backend/edkb_system/skills/table_linearize.py
T

92 lines
3.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.
from __future__ import annotations
from edkb_system.contracts import Context
COND_KWS = ["条件", "判定", "if", "IF"]
ACT_KWS = ["处理", "动作", "措施", "结果", "输出"]
OWN_KWS = ["责任", "负责人", "部门", "岗位"]
# Wide tables use row text blocks so Dify custom segmentation stays row-aligned.
WIDE_TABLE_COLS = 8
def _find_col(headers: list[str], kws: list[str]) -> int | None:
for i, h in enumerate(headers):
s = (h or "").lower()
if any(k.lower() in s for k in kws):
return i
return None
def _to_table_md_loose(headers: list[str], rows: list[list[str]]) -> str:
"""Markdown header block plus one pipe row per chunk, separated by blank lines."""
hs = [h or "-" for h in headers]
header_block = "\n".join(
[
"| " + " | ".join(hs) + " |",
"| " + " | ".join(["---"] * len(hs)) + " |",
]
)
data_blocks: list[str] = []
for row in rows:
vals = [row[i] if i < len(row) else "" for i in range(len(hs))]
data_blocks.append("| " + " | ".join(vals) + " |")
if not data_blocks:
return header_block
return header_block + "\n\n" + "\n\n".join(data_blocks)
def _to_row_text_md(headers: list[str], rows: list[list[str]]) -> str:
"""Wide-table fallback: one bullet per row for stable chunk boundaries."""
hs = [h or "-" for h in headers]
blocks: list[str] = []
for row in rows:
pairs = []
for i, header in enumerate(hs):
val = row[i] if i < len(row) else ""
pairs.append(f"{header}={val}")
blocks.append("- 【行】" + ";".join(pairs) + "。")
return "\n\n".join(blocks)
def run(input_data: list[dict] | dict, context: Context) -> str:
tables = input_data if isinstance(input_data, list) else [input_data]
parts: list[str] = []
for table in tables:
headers = [str(x).strip() for x in table.get("headers", [])]
rows = [[str(c).strip() for c in row] for row in table.get("rows", [])]
sheet_blocks: list[str] = [f"## Sheet: {table.get('sheet', 'Sheet1')}"]
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:
bullets: list[str] = []
for row in rows:
cond = row[cond_idx] if cond_idx < len(row) else "满足条件"
act = 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 "相关责任方"
)
bullets.append(
f"- 当 {cond or '满足条件'} 时,{owner or '相关责任方'} 执行 {act or '执行处理'}。"
)
if bullets:
sheet_blocks.append("\n\n".join(bullets))
elif len(headers) > WIDE_TABLE_COLS:
content = _to_row_text_md(headers, rows)
if content:
sheet_blocks.append(content)
else:
content = _to_table_md_loose(headers, rows)
if content:
sheet_blocks.append(content)
parts.append("\n\n".join(sheet_blocks))
return "\n\n".join(parts).strip() + "\n"