add_excel_field_comment_row.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. """Insert a Chinese business-comment row (row 2) under the header of every config
  2. sheet in the rule-pack and walk-strategy workbooks.
  3. Why this is safe for loading / code-reading / JSON conversion:
  4. - The runtime never reads these .xlsx files; it reads the JSON exports only.
  5. - The inserted comment row puts a sentinel prefix "备注:" in the FIRST column,
  6. so any future Excel->JSON converter can skip it with a one-line guard:
  7. if str(row[0]).startswith("备注"): continue
  8. - The row is styled (light fill + grey italic) so humans also see it is not data.
  9. Sources of the Chinese meanings:
  10. - Rule-pack workbook: its own built-in `字段注释` dictionary sheet.
  11. - Walk-strategy workbook: tech_documents/游走策略/02_游走策略表字段说明.md (encoded below).
  12. Idempotent: re-running detects an existing "备注" row and skips that sheet.
  13. """
  14. from __future__ import annotations
  15. from pathlib import Path
  16. from openpyxl import load_workbook
  17. from openpyxl.styles import Font, PatternFill
  18. from openpyxl.utils import get_column_letter
  19. ROOT = Path(__file__).resolve().parent.parent
  20. RULE_PACK_XLSX = ROOT / "tech_documents/规则包映射/规则包映射配置表.xlsx"
  21. WALK_XLSX = ROOT / "tech_documents/游走策略/游走策略配置表.xlsx"
  22. SENTINEL = "备注:"
  23. COMMENT_FILL = PatternFill(start_color="FFF2F2F2", end_color="FFF2F2F2", fill_type="solid")
  24. COMMENT_FONT = Font(italic=True, color="FF7F7F7F")
  25. # Walk-strategy meanings, per sheet, from 02_游走策略表字段说明.md.
  26. WALK_MEANINGS: dict[str, dict[str, str]] = {
  27. "walk_strategy_meta": {
  28. "strategy_id": "游走策略 ID", "strategy_version": "游走策略版本",
  29. "platform": "平台,V1 为 douyin", "status": "策略状态,如 active / draft / deprecated",
  30. "owner": "业务负责人", "source_json_path": "对应 runtime JSON 路径",
  31. "description": "策略说明", "notes": "备注", "注释": "中文业务注释",
  32. },
  33. "walk_node_catalog": {
  34. "node_type": "节点类型,如 query、video、author、hashtag", "node_label": "产品可读名称",
  35. "node_category": "节点类别,如 input、platform_result、signal、asset",
  36. "id_field": "识别该节点的字段", "can_expand": "是否可继续扩展",
  37. "is_signal_node": "是否只是信号节点,不直接沉淀资产", "notes": "备注", "注释": "中文业务注释",
  38. },
  39. "walk_edge_catalog": {
  40. "edge_id": "边 ID", "edge_type": "边类型", "from_node_type": "起点节点类型",
  41. "to_node_type": "终点节点类型", "edge_label": "产品可读名称", "enabled": "是否启用",
  42. "runtime_stage": "所属运行阶段", "creates_new_node": "是否产生新节点",
  43. "can_loop": "是否允许循环或多轮", "priority": "边优先级,数字越小越先执行",
  44. "notes": "备注", "注释": "中文业务注释",
  45. },
  46. "walk_edge_trigger_rules": {
  47. "trigger_id": "触发规则 ID", "edge_id": "适用边",
  48. "input_level": "判断粒度,如 query、content、author、tag",
  49. "field_path": "用来判断的字段路径", "operator": "判断操作符", "expected_value": "期望值",
  50. "required": "是否必需满足", "failure_policy": "不满足时的处理方式",
  51. "notes": "备注", "注释": "中文业务注释",
  52. },
  53. "walk_rule_pack_binding": {
  54. "binding_id": "绑定 ID", "edge_id": "被绑定的边",
  55. "target_entity": "规则判断对象,如 Content、Author、Hashtag、Path、Budget",
  56. "rule_pack_id": "P5 规则包 ID", "rule_pack_version": "P5 规则包版本",
  57. "required": "是否必须通过该规则判断",
  58. "dispatch_policy": "调用方式,如 required / optional / advisory",
  59. "notes": "备注", "注释": "中文业务注释",
  60. },
  61. "walk_budget_policy": {
  62. "budget_id": "预算规则 ID", "edge_id": "适用边",
  63. "max_total_actions": "单 run 最多执行次数", "max_per_query": "每条 query 最多执行次数",
  64. "max_per_content": "每条内容最多执行次数", "max_pages": "最大页数",
  65. "max_depth": "最大游走深度", "max_tag_hops": "最大 tag 扩散跳数",
  66. "budget_tier": "预算档位", "notes": "备注", "注释": "中文业务注释",
  67. },
  68. "walk_stop_policy": {
  69. "stop_policy_id": "停止规则 ID", "edge_id": "适用边", "condition_label": "停止条件名称",
  70. "field_path": "判断字段路径", "operator": "判断操作符", "expected_value": "期望值",
  71. "stop_action": "停止后的动作", "reason_code": "停止原因码", "priority": "停止规则优先级",
  72. "notes": "备注", "注释": "中文业务注释",
  73. },
  74. "walk_retry_policy": {
  75. "retry_policy_id": "重试规则 ID", "edge_id": "适用边", "operation": "重试的外部操作",
  76. "max_retries": "最大重试次数", "retry_interval_seconds": "重试间隔秒数",
  77. "on_final_failure": "最终失败后的处理", "notes": "备注", "注释": "中文业务注释",
  78. },
  79. "walk_action_catalog": {
  80. "walk_action": "游走动作枚举", "action_label": "产品可读名称", "edge_id": "适用边",
  81. "runtime_effect": "运行影响", "is_terminal": "是否终止路径",
  82. "writes_next_hop": "是否写入下一跳节点", "notes": "备注", "注释": "中文业务注释",
  83. },
  84. "walk_source_path_mapping": {
  85. "mapping_id": "来源路径映射 ID", "edge_id": "适用边", "source_path_type": "来源路径类型",
  86. "from_node_type": "起点节点类型", "to_node_type": "终点节点类型",
  87. "origin_path_template": "来源路径模板", "source_evidence_ref_template": "来源证据引用模板",
  88. "notes": "备注", "注释": "中文业务注释",
  89. },
  90. "walk_event_mapping": {
  91. "mapping_id": "事件映射 ID", "edge_id": "适用边", "event_type": "运行事件类型",
  92. "success_status": "成功状态", "failure_status": "失败状态",
  93. "input_ref_template": "输入引用模板", "output_ref_template": "输出引用模板",
  94. "notes": "备注", "注释": "中文业务注释",
  95. },
  96. "walk_query_generation_policy": {
  97. "policy_id": "query 生成规则 ID", "edge_id": "适用边",
  98. "query_generation_method": "query 生成方式", "source_field": "生成 query 的来源字段",
  99. "dedup_policy": "去重策略", "max_queries": "最大生成 query 数",
  100. "notes": "备注", "注释": "中文业务注释",
  101. },
  102. "walk_fact_contract": {
  103. "runtime_file": "runtime 文件名", "db_table": "对应 DB 表", "required_fields": "必填字段",
  104. "json_fields": "JSON 字段", "unique_key": "唯一键", "notes": "备注", "注释": "中文业务注释",
  105. },
  106. }
  107. # Simple meanings for the rule-pack dictionary sheet itself (it has no self-entry).
  108. DICT_SHEET_NAME = "字段注释"
  109. DICT_SHEET_MEANINGS = {
  110. "sheet_name": "配置表 sheet 名", "field_name": "字段英文名",
  111. "字段中文名": "字段中文名", "注释": "字段业务含义说明",
  112. }
  113. def build_rule_pack_meanings(wb) -> dict[str, dict[str, str]]:
  114. """Read the workbook's own 字段注释 sheet into {sheet: {field: note}}."""
  115. meanings: dict[str, dict[str, str]] = {}
  116. ws = wb[DICT_SHEET_NAME]
  117. for sheet_name, field_name, _cn, note in ws.iter_rows(min_row=2, values_only=True):
  118. if not sheet_name or not field_name:
  119. continue
  120. meanings.setdefault(sheet_name, {})[field_name] = note or field_name
  121. return meanings
  122. def annotate_sheet(ws, meanings_for_sheet: dict[str, str]) -> str:
  123. headers = [c.value for c in ws[1]]
  124. if not headers or all(h is None for h in headers):
  125. return "skip(空表)"
  126. # Idempotency guard: already annotated?
  127. if ws.max_row >= 2 and str(ws.cell(row=2, column=1).value or "").startswith(SENTINEL.rstrip(":")):
  128. return "skip(已存在备注行)"
  129. ws.insert_rows(2)
  130. for col_idx, header in enumerate(headers, start=1):
  131. if header is None:
  132. continue
  133. meaning = meanings_for_sheet.get(str(header), str(header))
  134. text = (SENTINEL + meaning) if col_idx == 1 else meaning
  135. cell = ws.cell(row=2, column=col_idx, value=text)
  136. cell.fill = COMMENT_FILL
  137. cell.font = COMMENT_FONT
  138. # Keep the autofilter dropdown anchored on the header row across full range.
  139. last_col = get_column_letter(ws.max_column)
  140. ws.auto_filter.ref = f"A1:{last_col}{ws.max_row}"
  141. return f"ok({len(headers)}列)"
  142. def process(path: Path, meanings_by_sheet, skip_sheets: set[str]) -> None:
  143. wb = load_workbook(path)
  144. print(f"\n=== {path.name} ===")
  145. for ws in wb.worksheets:
  146. if ws.title in skip_sheets:
  147. print(f" - {ws.title:32s} skip(字典/说明 sheet)")
  148. continue
  149. m = meanings_by_sheet.get(ws.title, {})
  150. status = annotate_sheet(ws, m)
  151. print(f" - {ws.title:32s} {status}")
  152. wb.save(path)
  153. print(f" saved -> {path}")
  154. def main() -> None:
  155. # Rule-pack workbook: meanings from its own 字段注释 sheet; annotate that sheet too.
  156. wb_rp = load_workbook(RULE_PACK_XLSX)
  157. rp_meanings = build_rule_pack_meanings(wb_rp)
  158. rp_meanings[DICT_SHEET_NAME] = DICT_SHEET_MEANINGS
  159. process(RULE_PACK_XLSX, rp_meanings, skip_sheets=set())
  160. # Walk-strategy workbook: meanings encoded from the field-spec doc.
  161. process(WALK_XLSX, WALK_MEANINGS, skip_sheets=set())
  162. if __name__ == "__main__":
  163. main()