"""将知识库中要素表模板的英文字段值全部转为中文。 转换内容: - type: text→文本, textarea→长文本, date→日期, number→数字, select→选择, boolean→是否 - required: true→是, false→否 - doc_type 展示标签: element_template→要素表模板(仅展示用,存储值不变以兼容检索) """ import json import sys import os sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from bossai import KnowledgeStore TYPE_MAP = { "text": "文本", "textarea": "长文本", "date": "日期", "number": "数字", "select": "选择", "boolean": "是否", } REQUIRED_MAP = { True: "是", False: "否", } def convert_template(tmpl: dict) -> dict: """递归转换模板中的英文值为中文。""" # 转换 elements 中的 type 和 required elements = tmpl.get("elements", []) for e in elements: if "type" in e and e["type"] in TYPE_MAP: e["type"] = TYPE_MAP[e["type"]] if "required" in e: val = e["required"] if val in REQUIRED_MAP: e["required"] = REQUIRED_MAP[val] elif isinstance(val, str) and val.lower() == "true": e["required"] = "是" elif isinstance(val, str) and val.lower() == "false": e["required"] = "否" return tmpl def main(): store = KnowledgeStore() with store._conn() as conn: with conn.cursor() as cur: cur.execute( "SELECT id, title, content FROM knowledge_docs WHERE doc_type='element_template' ORDER BY id" ) rows = cur.fetchall() print(f"找到 {len(rows)} 条要素表模板,开始转换...") updated = 0 for doc_id, title, content in rows: try: tmpl = json.loads(content) tmpl = convert_template(tmpl) new_content = json.dumps(tmpl, ensure_ascii=False, indent=2) if new_content != content: cur.execute( "UPDATE knowledge_docs SET content=%s WHERE id=%s", (new_content, doc_id), ) updated += 1 except Exception as e: print(f" 跳过 {title}: {e}") print(f"已转换 {updated}/{len(rows)} 条记录") # 验证 with store._conn() as conn: with conn.cursor() as cur: cur.execute( "SELECT content FROM knowledge_docs WHERE doc_type='element_template' LIMIT 1" ) row = cur.fetchone() if row: tmpl = json.loads(row[0]) print(f"\n验证示例({tmpl.get('cause_of_action', '')}):") for e in tmpl.get("elements", [])[:3]: print(f" {e.get('label')}: type={e.get('type')}, required={e.get('required')}") if __name__ == "__main__": main()