#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ renderer.py — Procedure DSL 可视化共享模板. 每个 case 提供 case_data (一个 dict, 见 build_html 的 docstring), import 本模块并调用 build_html(case_data) → HTML 字符串. spec 引用: spec.md §12 (.html 可视化结构规范). """ import html import json import re from pathlib import Path # ── 数据 loaders (从 spec/taxonomy 单一来源加载) ──────────────────── def _load_json(rel_path: str) -> dict: """从 spec/ 子路径加载 JSON. rel_path 是相对 spec/ 的路径 (e.g. 'taxonomy/type.json').""" return json.loads((Path(__file__).resolve().parent.parent / rel_path).read_text(encoding='utf-8')) def _load_stdlib_types() -> dict: """type stdlib 渲染元信息. 新结构 type.json 无 type_metadata → 返回 {}; stdlib 叶子的 in_tree 标记在 build_html 里按 type.json 的 $leaves 补齐.""" return {} _DRAWER_TITLES = { 'effect': ('作用 (chip 上 data-prefix="作用")', '这一步在 AIGC 生产工序链中的位置 + 作用; 从 §A.1 字典树取 L3 叶子'), 'action': ('动作 (chip 上 data-prefix="动作")', '这一步的动作动词; 从 §A.2 字典树取路径'), 'type': ('类型 (chip 上 data-type)', '领域语义类型 (按功能角色分类: 程序控制/数据复用/内容/知识); 从 §A.3 字典树取叶子'), } def _add_label_suffix(node, depth=0): """递归把 dict 的 key 加 (L1)/(L2) 显示后缀, 让 drawer UI 区分层级. leaf string 保留原状; $* 元数据 key 跳过.""" if not isinstance(node, dict): return node result = {} for k, v in node.items(): if k.startswith('$'): continue new_k = k if isinstance(v, dict): if depth == 0: new_k = f'{k} (L1)' elif depth == 1: new_k = f'{k} (L2)' result[new_k] = _add_label_suffix(v, depth + 1) return result def _tree_to_drawer(nodes): """新结构 最终分类树 (list of {分类名称, 分类说明, 子分类}) → drawer 嵌套 dict. 叶子 → {名称: 分类说明 字符串}; 非叶 → {名称: 子树 dict}. 层级即 根→叶 路径.""" out = {} for n in nodes or []: name = n.get('分类名称', '?') kids = n.get('子分类') or [] out[name] = _tree_to_drawer(kids) if kids else (n.get('分类说明', '') or '') return out def _load_drawer_tree(dim: str) -> dict: """spec/taxonomy/{dim}.json → 重塑为 drawer UI 需要的 {title, desc, tree} 格式. 新结构读 最终分类树 (中文键); 自动加 (L1)/(L2) 层级标签. dim ∈ {'effect', 'action', 'type'}.""" raw = _load_json(f'taxonomy/{dim}.json') title, desc = _DRAWER_TITLES[dim] nested = _tree_to_drawer(raw.get('最终分类树', [])) return { 'title': title, 'desc': desc, 'tree': _add_label_suffix(nested, depth=0), } # ============================================================================= # STDLIB · type registry (字典树 §A.3 叶子的 in_tree 标记基础; 现为空, build_html 按 $leaves 补齐) # ============================================================================= STDLIB_TYPE_REGISTRY = _load_stdlib_types() # ============================================================================= # 字典树 (spec §A.1 作用 / §A.2 动作 / §A.3 类型) # ============================================================================= EFFECT_TREE = _load_drawer_tree("effect") ACTION_TREE = _load_drawer_tree("action") TYPE_TREE = _load_drawer_tree("type") def _build_type_paths() -> dict: """type.json 最终分类树 → {叶子名: '根/.../叶子' 路径}, 供 chip 显示完整路径.""" raw = _load_json('taxonomy/type.json') out: dict = {} def walk(nodes, prefix): for n in nodes: path = prefix + [n.get('分类名称', '')] kids = n.get('子分类') or [] if kids: walk(kids, path) else: out[n.get('分类名称', '')] = '/'.join(path) walk(raw.get('最终分类树', []), []) return out TYPE_PATHS = _build_type_paths() FEATURE_TAXONOMY = _load_json("taxonomy/feature.json") EXTERNAL_TAXONOMIES = { '实质': {'title': '实质 (内容是什么)', 'desc': '理念 / 表象 — 911 路径', 'source': 'external', 'file': '分类库导出_实质_*.json'}, '形式': {'title': '形式 (内容怎么呈现)', 'desc': '呈现 / 架构 — 565 路径', 'source': 'external', 'file': '分类库导出_形式_*.json'}, } # ============================================================================= # Render helpers # ============================================================================= def he(s): """HTML escape, 默认 quote=True 把 `"` 转成 `"`. 这点关键: title / data-* / class 等属性值如果含 `"` 会提前终止属性, 导致 tooltip 显示不完整 (典型 bug: '原文方法 3 只说"自己写动作"' 在 title 中只显示到 "只说" 就被截断). """ if s is None: return '' return html.escape(str(s)) def render_intent(text): """目的列: 简短自然语言句, **尽量** 把其他列里的结构化值都做成 {kind:value} token. 每个 token 底色对应其引用的列, 让人一眼看出该值来自哪里. 合法 kind: effect → 作用列 (灰, 需求组) via → 外部工具列 (浅绿 + 等宽字体, 实现组) act → 动作列 (绿, 实现组) control → 逻辑控制列 (浅青, 实现组) — 并行/遍历/分支/请求/等待 in-type → 输入·类型 (黄圆胶囊) out-type → 输出·类型 (蓝圆胶囊) in-sub → 输入·实质 (黄矩形 tag) out-sub → 输出·实质 (蓝矩形 tag) in-form → 输入·形式 (黄矩形 tag 斜体) out-form → 输出·形式 (蓝矩形 tag 斜体) **特性列 (feature) 不允许在 intent 中引用** — feature 是内部执行特征 (随机/幂等/人工/读写外部), 不出现在面向使用者的描述. 写成 `ik-other` 灰色显示作为 lint 警告. 严禁变量名 token (no `{in:X}` / `{out:X}`); 严禁 dataflow 公式 / case-specific 简写. """ def sub(m): kind = m.group(1) val = m.group(2) kc = { 'effect': 'ik-effect', 'via': 'ik-via', 'act': 'ik-act', 'in-type': 'ik-in-type', 'out-type': 'ik-out-type', }.get(kind, 'ik-other') return f'{he(val)}' return re.sub(r'\{([\w-]+):([^}]+)\}', sub, text or '') def render_chip(type_name): if not type_name: return '' if type_name == '-': return he(type_name) # 显示完整路径 (e.g. 程序控制类型/指令/提示词); data-type 仍存叶子名, drawer 查找不受影响. # case-specific 类型 (不在字典树) 显示原名. disp = TYPE_PATHS.get(type_name, type_name) return f'{he(disp)}' def render_path(prefix, value): if not value: return '' if isinstance(value, list): spans = [] for val in value: if val: spans.append(f'{he(val)}') return '\n'.join(spans) if isinstance(value, str): if '+' in value: parts = [p.strip() for p in value.split('+') if p.strip()] spans = [] for val in parts: spans.append(f'{he(val)}') return '\n'.join(spans) return f'{he(value)}' return '' _VALUE_DESC_RE = re.compile(r'^<(.+)>$', re.DOTALL) def render_value(vl): """值列渲染: - 若整段以 `<...>` 括起 → 渲染为斜体浅灰背景, 表示"这是对内容的描述, 不是内容本身" (适用于无法在 cell 中直接嵌入的非文本数据: 视频/图像/音频). - 否则 → 渲染为普通文本 (适用于文本数据本身, 如 prompt 全文). """ if vl is None: return '' s = str(vl).strip() m = _VALUE_DESC_RE.match(s) if m: inner = m.group(1) return f'<{he(inner)}>' return f'{he(s)}' def render_focus_class(cell_key, focus_list): return ' row-focus' if cell_key in (focus_list or []) else '' def cell_attrs(field_key, focus, io_reason=None, is_empty=False): """组合 cell 的额外 class 和属性 (focus + 推断补全). field_key 例: 'action', 'in-value-0', 'out-type-1', etc. io_reason: 当前 cell 所属 IO item 整体被标 inferred 时, 传入 reason 字符串. is_empty: 该 cell 内容是否为空 (留空的推断 cell 角标变 推?). 返回 (class_suffix_str, extra_attrs_str). """ cls = render_focus_class(field_key, focus) extra = '' if io_reason: cls += ' is-inferred' if is_empty: cls += ' is-low-confidence' extra = f' title="推断补全: {he(io_reason)}"' return cls, extra def render_io_value(item): """IO 值列: output 的 id 作为小标签贴在值前 (供 anchor 1:1 引用对照); input 无 id.""" iid = item.get('id') id_tag = f'{he(iid)} ' if iid else '' return id_tag + render_value(item.get('value')) _OUT_ID_RE = re.compile(r'^s\d+(?:\.\d+)?o\d+$') _OUT_PATH_RE = re.compile(r's(\d+(?:\.\d+)?)\.outputs\[(\d+)\]') def _ref_output_id(anchor): """把一条输入 anchor (来源 ←) 归一到它引用的**输出编号**, 取不到返回 None. 认: ← s1o1 / ← s5o1[-1] (去索引) / ← p1.s1.outputs[0] (JSON 路径式也救, 归一成 s1o1)。 不认 (返回 None): ← 工序输入 / ← s1.名字 (按名引用) / 字面量。供"去处"自动反推用。 """ if not anchor: return None s = str(anchor).strip() if s.startswith('←'): s = s[1:].strip() m = _OUT_PATH_RE.search(s) # JSON 路径式 → sNo(idx+1) if m: return f's{m.group(1)}o{int(m.group(2)) + 1}' base = s.split('[')[0].strip() # 去掉 [i] / [-1] 索引 return base if _OUT_ID_RE.match(base) else None def build_output_consumers(proc): """扫一个工序内所有输入的来源 ← anchor, 反推 {输出编号: [消费它的步骤 id]}。 "去处"(输出 →)其实是"来源"(输入 ←)的逆: 谁的输入引用了本输出, 谁就是去处。 模型没填 → 时, 渲染层据此自动补出去处, 不必逼模型冗余地正反都填。 """ consumers: dict = {} for st in proc.get('steps', []) or []: sid = st.get('id') for io in st.get('inputs') or []: oid = _ref_output_id(io.get('anchor')) if oid: lst = consumers.setdefault(oid, []) if sid and sid not in lst: lst.append(sid) return consumers def render_step_row(step, idx_label, type_reg=None, consumers=None): """渲染一个 step (kind: step / block / nested) 为一组 tr 行 (14 列). 需求组 (rowspan): # / 目的 / 作用 / 实质 / 形式 (后两者 step 级). 输入/输出 (逐 IO): 类型 / 值 / 来源(去处). 实现组 (rowspan): 外部工具 / 动作 / 指令. type_reg: 已合并 STDLIB + case-specific 的类型注册表 (用于 chip in_tree 标记). consumers: {输出编号: [消费步骤 id]} 反向索引; 输出 → 没填时据此自动补"去处"。 """ inputs = step.get('inputs', []) outputs = step.get('outputs', []) N = max(len(inputs), len(outputs), 1) focus = step.get('focus', []) is_nested = step['kind'] == 'nested' is_block = step['kind'] == 'block' main_cls = 'step step-main' if is_block: main_cls = 'step block-header' if is_nested: main_cls = 'step step-main step-nested' sub_cls = 'step step-sub' data_step = step['id'] data_group = step.get('group', '') rows = [] for k in range(N): tr_cls = main_cls if k == 0 else sub_cls attrs = f' data-step="{data_step}"' if data_group: attrs += f' data-group="{data_group}"' attrs += f' data-focus="{",".join(focus)}"' if k == 0: attrs = f' id="{data_step}"' + attrs cells = [] if k == 0: rs = f' rowspan="{N}"' if N > 1 else '' arrow = '▼ ' if is_block else '' indent = ' └ ' if is_nested else '' cells.append(f'
{he(p)}
') kind, url = m.group(1), m.group(2) if kind == 'image': pieces.append(f'{he(p)}
') return '\n'.join(pieces) def render_source(case_data): """原文 折叠块: 元信息 + body_text 完整正文 (含内嵌图片/视频).""" src = case_data.get('source') if not src: return '' url = src.get('url', '') title = src.get('title', '') excerpt = src.get('excerpt', '') body_text = src.get('body_text', '') cover = src.get('cover_image', '') meta_bits = [b for b in [src.get('platform'), src.get('author'), src.get('date')] if b] parts = ['摘要: {he(excerpt)}
') if cover: parts.append(f'