fix(kb): 处理excel清洗问题
(cherry picked from commit 1a0ceebc3340848171e2cc14d0a7b04c2dda4748)
This commit is contained in:
1 parent
7736a6991e
commit
87ac58c394
4 files changed
+166
-75
No files matched your search
@@ -34,10 +34,7 @@ class OALeaveWorkflowError(RuntimeError):
|
||||
|
||||
class OALeaveWorkflowService:
|
||||
WORKFLOW_ID = '879'
|
||||
OA_USER_MAP = {
|
||||
'26030025': {'user_id': '21784', 'name': '梁春艳'},
|
||||
'26040006': {'user_id': '21823', 'name': '刘义亮'},
|
||||
}
|
||||
|
||||
# Keep backend leave labels aligned with the chat form options so OA browser
|
||||
# fields always receive the expected showValue instead of a raw code.
|
||||
LEAVE_TYPE_LABELS = {
|
||||
@@ -131,20 +128,6 @@ class OALeaveWorkflowService:
|
||||
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
|
||||
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败(重试{max_retries}次后仍出错):{last_exc}') from last_exc
|
||||
|
||||
@classmethod
|
||||
def resolve_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
employee_id = (employee_id or '').strip()
|
||||
if not employee_id:
|
||||
raise OALeaveWorkflowError('缺少员工工号,无法匹配 OA 用户。')
|
||||
matched = cls.OA_USER_MAP.get(employee_id)
|
||||
if not matched:
|
||||
raise OALeaveWorkflowError(f'工号 {employee_id} 暂未配置 OA userid 映射。')
|
||||
return {
|
||||
'employee_id': employee_id,
|
||||
'user_id': matched['user_id'],
|
||||
'name': (real_name or matched.get('name') or '').strip() or matched['name'],
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def resolve_creator_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='请假人')
|
||||
|
||||
@@ -25,6 +25,18 @@ class ChunkConfig(BaseModel):
|
||||
add_heading_path_prefix: bool = True
|
||||
|
||||
|
||||
class TableConfig(BaseModel):
|
||||
"""
|
||||
Excel/CSV 表格线性化配置。
|
||||
|
||||
用途:约束进入 Dify 前每段可容纳的完整原始行总字符数。
|
||||
逻辑:table_linearize 在 Excel/CSV 分支读取该值;Dify 同步仍按空行分段,
|
||||
因此本值应低于 Dify 的 max_tokens 能承载的保守字符数。
|
||||
"""
|
||||
|
||||
segment_max_chars: int = 480
|
||||
|
||||
|
||||
class CleanConfig(BaseModel):
|
||||
dedup_min_repeats: int = 3
|
||||
merge_short_line_chars: int = 15
|
||||
@@ -34,6 +46,7 @@ class SystemConfig(BaseModel):
|
||||
router: RouterConfig = Field(default_factory=RouterConfig)
|
||||
ocr: OCRConfig = Field(default_factory=OCRConfig)
|
||||
chunk: ChunkConfig = Field(default_factory=ChunkConfig)
|
||||
table: TableConfig = Field(default_factory=TableConfig)
|
||||
clean: CleanConfig = Field(default_factory=CleanConfig)
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -708,7 +708,13 @@ def _run_one(
|
||||
elif tables is not None:
|
||||
_announce("table linearize")
|
||||
t0 = time.perf_counter()
|
||||
text = table_linearize.run(tables, ctx)
|
||||
# Excel/CSV 在此按完整原始行组段;不可依赖后续通用 chunk 的字符切分,
|
||||
# 否则 Dify 段可能在一条表格记录中间断开。
|
||||
text = table_linearize.run(
|
||||
tables,
|
||||
ctx,
|
||||
segment_max_chars=cfg.table.segment_max_chars,
|
||||
)
|
||||
_mark("edkb-table-linearize", t0)
|
||||
trace_steps.append("edkb-table-linearize")
|
||||
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
"""
|
||||
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
|
||||
@@ -7,85 +15,166 @@ COND_KWS = ["条件", "判定", "if", "IF"]
|
||||
ACT_KWS = ["处理", "动作", "措施", "结果", "输出"]
|
||||
OWN_KWS = ["责任", "负责人", "部门", "岗位"]
|
||||
|
||||
# Wide tables use row text blocks so Dify custom segmentation stays row-aligned.
|
||||
# 列数较多时,Markdown 表格可读性较差,改为字段键值的行文本。
|
||||
WIDE_TABLE_COLS = 8
|
||||
DEFAULT_SEGMENT_MAX_CHARS = 480
|
||||
|
||||
|
||||
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):
|
||||
"""按候选关键词定位表头列,用于将条件-动作表转为自然语言行。"""
|
||||
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 _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)) + " |",
|
||||
def _normalize_segment_max_chars(value: int | None) -> int:
|
||||
"""归一化 Excel 段字符上限,避免非法配置导致清洗任务失败。"""
|
||||
try:
|
||||
return max(100, int(value or DEFAULT_SEGMENT_MAX_CHARS))
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_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)
|
||||
]
|
||||
)
|
||||
data_blocks: list[str] = []
|
||||
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:
|
||||
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)
|
||||
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 _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,
|
||||
segment_max_chars: int = DEFAULT_SEGMENT_MAX_CHARS,
|
||||
) -> str:
|
||||
"""
|
||||
将 Excel/CSV 表格线性化为“多完整行一个段”的 Markdown。
|
||||
|
||||
核心逻辑:识别规则表、宽表和普通窄表后,统一以原始数据行作为不可拆分原子;
|
||||
以最大字符数装箱并在每段重复工作表/表头上下文,段间仅插入 ``\n\n``。
|
||||
|
||||
def run(input_data: list[dict] | dict, context: Context) -> str:
|
||||
Args:
|
||||
input_data: loader 输出的单表或多表结构,包含 sheet、headers、rows。
|
||||
context: 当前清洗上下文,保留统一 skill 调用签名。
|
||||
segment_max_chars: 单个 Dify 段的最大字符数;不会切断超过上限的单条原始行。
|
||||
|
||||
Returns:
|
||||
str: 供 clean/export 和 Dify custom segmentation 使用的 Markdown 文本。
|
||||
"""
|
||||
del context # 当前阶段不修改上下文,保留 skill 标准入参。
|
||||
max_chars = _normalize_segment_max_chars(segment_max_chars)
|
||||
tables = input_data if isinstance(input_data, list) else [input_data]
|
||||
parts: list[str] = []
|
||||
segments: 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')}"]
|
||||
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:
|
||||
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))
|
||||
row_lines = _condition_action_row_lines(headers, rows, cond_idx, act_idx, owner_idx)
|
||||
header_lines = None
|
||||
elif len(headers) > WIDE_TABLE_COLS:
|
||||
content = _to_row_text_md(headers, rows)
|
||||
if content:
|
||||
sheet_blocks.append(content)
|
||||
row_lines = _wide_table_row_lines(headers, rows)
|
||||
header_lines = None
|
||||
else:
|
||||
content = _to_table_md_loose(headers, rows)
|
||||
if content:
|
||||
sheet_blocks.append(content)
|
||||
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)) + " |",
|
||||
]
|
||||
|
||||
parts.append("\n\n".join(sheet_blocks))
|
||||
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(parts).strip() + "\n"
|
||||
return "\n\n".join(segments).strip() + "\n"
|
||||
Reference in new issue
Block a user