File size: 9,290 Bytes
9542666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python3
"""Generate a self-contained interactive graph of the discourse (D3 force layout).

Nodes are ideas (blue) and the papers engaging them (amber); edges are typed
stances, colored so positive/negative influence is legible — solid green
argues-for, solid red argues-against, gold-dashed nuances, grey-dotted tests.
Output is ONE HTML file (D3 loaded from CDN), interactive: drag, scroll-zoom,
hover a paper for its title. This exists because building it by hand is fiddly
(edge typing, dashed legend, force params) — parameterize instead of re-deriving.

    # a few explicit ideas
    python3 _scripts/make_graph.py replay-is-necessary-for-class-IL \
        protecting-important-weights-prevents-forgetting --out reports/debate-graph.html

    # every contested idea + the papers on each side
    python3 _scripts/make_graph.py --contested --out reports/contested.html

    # one idea's whole neighbourhood
    python3 _scripts/make_graph.py --idea generative-replay-can-substitute-stored-data

Flags:
    --contested        use all ideas with `status: contested`
    --idea SLUG        shorthand for a single idea (same as passing it positionally)
    --embed            strip the page header (for embedding in an <iframe>)
    --title TEXT       header title (standalone only)
    --out PATH         output file (default reports/graph.html)

To publish into the HF Space, see skills/visualize-graph/SKILL.md — `hf upload`
tries to create-a-gradio-repo and 402s on a free static Space; use the Python
API `HfApi().upload_file(...)` instead.
"""
import argparse
import glob
import json
import os
import re

VAULT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
KIND = {"argues-for": "for", "argues-against": "against", "nuances": "nuance", "tests": "test"}


def read(p):
    return open(p, encoding="utf-8").read()


def contested_ideas():
    out = []
    for f in glob.glob(os.path.join(VAULT, "ideas", "*.md")):
        if re.search(r"^status:\s*contested", read(f), re.M):
            out.append(os.path.basename(f)[:-3])
    return out


def idea_label(slug):
    f = os.path.join(VAULT, "ideas", slug + ".md")
    if os.path.exists(f):
        m = re.search(r'^statement:\s*"?(.+?)"?\s*$', read(f), re.M)
        if m:
            s = m.group(1)
            return s if len(s) <= 60 else s[:58] + "…"
    return slug


def build(idea_slugs):
    idea_set = set(idea_slugs)
    links, papers = [], {}
    for f in glob.glob(os.path.join(VAULT, "papers", "*.md")):
        s = os.path.basename(f)[:-3]
        t = read(f)
        title = re.search(r'^title:\s*"?(.+?)"?\s*$', t, re.M)
        title = title.group(1) if title else s
        for kind, lab in KIND.items():
            for mm in re.finditer(rf"(?<![a-z]){kind}::\s*\[\[([^\]]+)\]\]", t):
                if mm.group(1) in idea_set:
                    links.append({"source": s, "target": mm.group(1), "stance": lab})
                    papers[s] = title
    nodes = [{"id": i, "label": idea_label(i), "type": "idea"} for i in idea_slugs]
    nodes += [{"id": p, "label": papers[p], "type": "paper"} for p in papers]
    return {"nodes": nodes, "links": links}


HEADER = '''<div id="hd"><h1>{title}</h1>
<p>Ideas (blue) and the papers engaging them (amber). Edge color = stance. Drag to rearrange, scroll to zoom, hover a paper for its title.</p></div>
'''

TEMPLATE = '''<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>{title}</title>
<script src="https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js"></script>
<style>
  :root{{--bg:#fbfaf8;--ink:#1a1a1f;--muted:#6b6b78;--line:#e7e4de;
        --for:#2b8a6a;--against:#e11919;--nuance:#c98f24;--test:#9aa0aa;
        --idea:#3f6fd1;--paper:#e08a3c;}}
  *{{box-sizing:border-box}} html,body{{margin:0;height:100%}}
  body{{background:var(--bg);color:var(--ink);font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;overflow:hidden}}
  #hd{{position:fixed;top:0;left:0;right:0;padding:14px 20px;z-index:5;pointer-events:none}}
  #hd h1{{font:600 19px/1.2 Georgia,serif;margin:0}}
  #hd p{{margin:3px 0 0;color:var(--muted);font-size:13px;max-width:640px}}
  #legend{{position:fixed;bottom:16px;left:16px;background:#fffdfaee;border:1px solid var(--line);border-radius:10px;padding:11px 13px;font-size:12.5px;z-index:5;box-shadow:0 2px 10px #0000000d}}
  #legend b{{display:block;margin:0 0 6px;font-size:11px;letter-spacing:.05em;text-transform:uppercase;color:var(--muted)}}
  #legend .row{{display:flex;align-items:center;gap:7px;margin:3px 0}}
  #legend .sw{{width:22px;height:0;border-top-width:3px;border-top-style:solid}}
  #legend .dot{{width:12px;height:12px;border-radius:50%}}
  svg{{width:100vw;height:100vh;cursor:grab}}
  .link{{stroke-opacity:.55}}
  .node circle{{stroke:#fff;stroke-width:1}}
  .node.idea circle{{stroke:#294a94;stroke-width:1.5}}
  .lbl{{font-size:11px;fill:var(--ink);pointer-events:none;paint-order:stroke;stroke:#fbfaf8;stroke-width:3px;stroke-linejoin:round}}
  .lbl.idea{{font:600 13px Georgia,serif}}
  .lbl.paper{{opacity:0;font-size:10px;fill:var(--muted)}}
</style></head><body>
{header}<div id="legend">
  <b>Stance</b>
  <div class="row"><span class="sw" style="border-top-color:var(--for)"></span>argues for</div>
  <div class="row"><span class="sw" style="border-top-color:var(--against);border-top-width:4px"></span>argues against</div>
  <div class="row"><span class="sw" style="border-top-color:var(--nuance);border-top-style:dashed"></span>nuances</div>
  <div class="row"><span class="sw" style="border-top-color:var(--test);border-top-style:dotted"></span>tests</div>
  <b style="margin-top:9px">Node</b>
  <div class="row"><span class="dot" style="background:var(--idea)"></span>idea</div>
  <div class="row"><span class="dot" style="background:var(--paper)"></span>paper</div>
</div>
<svg></svg>
<script>
const data={data};
const C={{for:'#2b8a6a',against:'#e11919',nuance:'#c98f24',test:'#9aa0aa'}};
const svg=d3.select("svg"),W=innerWidth,H=innerHeight,g=svg.append("g");
svg.call(d3.zoom().scaleExtent([0.2,4]).on("zoom",e=>g.attr("transform",e.transform)));
const link=g.append("g").selectAll("line").data(data.links).join("line")
  .attr("class","link").attr("stroke",d=>C[d.stance]).attr("stroke-width",d=>d.stance==='against'?2.4:1.4)
  .attr("stroke-dasharray",d=>d.stance==='nuance'?"4 3":d.stance==='test'?"1 3":null);
const node=g.append("g").selectAll("g").data(data.nodes).join("g").attr("class",d=>"node "+d.type);
node.append("circle").attr("r",d=>d.type==='idea'?13:4.5).attr("fill",d=>d.type==='idea'?'#3f6fd1':'#e08a3c');
node.append("text").attr("class",d=>"lbl "+d.type).attr("x",d=>d.type==='idea'?16:7).attr("y",4)
  .text(d=>d.type==='idea'?d.label:(d.label.length>48?d.label.slice(0,46)+'\\u2026':d.label));
node.on("mouseover",function(){{d3.select(this).select(".lbl.paper").style("opacity",1)}})
    .on("mouseout",function(){{d3.select(this).select(".lbl.paper").style("opacity",0)}});
node.call(d3.drag()
  .on("start",(e,d)=>{{if(!e.active)sim.alphaTarget(.3).restart();d.fx=d.x;d.fy=d.y}})
  .on("drag",(e,d)=>{{d.fx=e.x;d.fy=e.y}})
  .on("end",(e,d)=>{{if(!e.active)sim.alphaTarget(0);d.fx=null;d.fy=null}}));
const sim=d3.forceSimulation(data.nodes)
  .force("link",d3.forceLink(data.links).id(d=>d.id).distance(d=>d.target.type==='idea'?65:40).strength(.5))
  .force("charge",d3.forceManyBody().strength(d=>d.type==='idea'?-320:-42))
  .force("x",d3.forceX(W/2).strength(.04)).force("y",d3.forceY(H/2).strength(.04))
  .force("collide",d3.forceCollide(d=>d.type==='idea'?26:7))
  .on("tick",()=>{{
    link.attr("x1",d=>d.source.x).attr("y1",d=>d.source.y).attr("x2",d=>d.target.x).attr("y2",d=>d.target.y);
    node.attr("transform",d=>`translate(${{d.x}},${{d.y}})`);
  }});
</script></body></html>'''


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("ideas", nargs="*", help="idea slugs")
    ap.add_argument("--contested", action="store_true")
    ap.add_argument("--idea", action="append", default=[])
    ap.add_argument("--embed", action="store_true")
    ap.add_argument("--title", default="Continual-learning discourse graph")
    ap.add_argument("--out", default="reports/graph.html")
    a = ap.parse_args()

    ideas = list(a.ideas) + list(a.idea)
    if a.contested:
        ideas += contested_ideas()
    ideas = list(dict.fromkeys(ideas))  # dedupe, keep order
    if not ideas:
        ap.error("give idea slugs, --idea SLUG, or --contested")
    missing = [i for i in ideas if not os.path.exists(os.path.join(VAULT, "ideas", i + ".md"))]
    if missing:
        ap.error(f"no such idea note(s): {missing}")

    data = build(ideas)
    header = "" if a.embed else HEADER.format(title=a.title)
    html = TEMPLATE.format(title=a.title, header=header, data=json.dumps(data))
    out = a.out if os.path.isabs(a.out) else os.path.join(VAULT, a.out)
    os.makedirs(os.path.dirname(out), exist_ok=True)
    with open(out, "w", encoding="utf-8") as f:
        f.write(html)
    ni = sum(1 for n in data["nodes"] if n["type"] == "idea")
    np = len(data["nodes"]) - ni
    print(f"wrote {out}: {ni} ideas + {np} papers, {len(data['links'])} stance edges")


if __name__ == "__main__":
    main()