Datasets:
fix/tree-node-distribution (#6)
Browse files- created viewer.py (e20e8e9ca6d96ec1b1fe0fb7253cdca087068baf)
- modified sidebar (6793fc46233a6dedbb092fc8aa2a2794ae0977e1)
- updated graph visualization with pyvis (a8d32863cd73fde11d669011569da5500f65c08b)
- implemented graph style selection from PyVis and NetworkX (1fdf3d016474aa2c2a769a27c24afec096980e79)
- moved sample details inside expander (5c3f970c0f9f1ecee10a9a4c78ba984ab7921832)
- modified graph height for NetworkX (191ea1806d190eb182645c0d76d20a286b413793)
- added number of samples (83dd85734e43f1f0bc8e9c65e951ca622c4398d2)
- updated README.md (68569e789bc27e269d5263987529404acdcad276)
- refactored main() into two functions (6d690044f3e789e99dfbf6390551c283b3edf2e1)
- added random pick button (8c25bcecd39c01b4229c6ef88c01f69ae9109444)
- renamed a function (c0886ffd3913f1425e469f9a999615cdd74609d1)
- debugged number of nodes for tree base graphs (dab7f7a0b0197430f67c31c2c6e18c4071748d1b)
- re-generated tree_cycle (9d6b82e8ca50013eff6485b0c78635dfc1347518)
- re-generated tree_grid (4f762c4453b94991b0d0d408ced4136c3b48a158)
- updated README (5db1de77ce5bb092aa087338c808fd1f170e5e9a)
- README.md +15 -3
- data/tree_cycle/test.jsonl +0 -0
- data/tree_cycle/train.jsonl +0 -0
- data/tree_cycle/val.jsonl +0 -0
- data/tree_grid/test.jsonl +0 -0
- data/tree_grid/train.jsonl +0 -0
- data/tree_grid/val.jsonl +0 -0
- fig/tree_cycle/node_count_hist.svg +299 -328
- fig/tree_grid/node_count_hist.svg +346 -375
- generator.py +10 -4
- viewer.py +283 -0
|
@@ -108,9 +108,9 @@ Node counts depend on the underlying base generator and motif size:
|
|
| 108 |
|
| 109 |
- `ba_shapes` (Barabási–Albert, `num_edges = 2`): 8–20 nodes.
|
| 110 |

|
| 111 |
-
- `tree_cycle` (Prüfer trees + 6-cycle motif):
|
| 112 |

|
| 113 |
-
- `tree_grid` (Prüfer trees + 3×3 grid motif):
|
| 114 |

|
| 115 |
- `ba_two_motifs` (Barabási–Albert; house vs 5-cycle motifs): 8–20 nodes.
|
| 116 |

|
|
@@ -123,7 +123,8 @@ Observed frequencies across the full 2,000-example splits for each subset are sh
|
|
| 123 |
|
| 124 |
All examples are synthetically generated using [PyTorch Geometric](https://pytorch-geometric.readthedocs.io/) (2.7.0) primitives:
|
| 125 |
|
| 126 |
-
- Detection subsets: positive samples start from certain base graphs whose node counts are drawn from a uniform distribution before a motif is injected, yielding final graphs with 8–20
|
|
|
|
| 127 |
- `ba_two_motifs`: both classes contain motifs injected into Barabási–Albert graphs—house motifs vs 5-cycle motifs—with final graphs spanning 8–20 nodes.
|
| 128 |
|
| 129 |
### Generation Process
|
|
@@ -182,6 +183,17 @@ visualize_graph(graph, "motif_example.png")
|
|
| 182 |
The script saves a PNG with motif nodes highlighted in orange.
|
| 183 |
Use absolute imports (e.g., `from motif_qa.src.utils import visualize_graph`) if you install the project as a package.
|
| 184 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
### Regenerating the Dataset Locally
|
| 186 |
|
| 187 |
```bash
|
|
|
|
| 108 |
|
| 109 |
- `ba_shapes` (Barabási–Albert, `num_edges = 2`): 8–20 nodes.
|
| 110 |

|
| 111 |
+
- `tree_cycle` (Prüfer trees + 6-cycle motif): 10–20 nodes.
|
| 112 |

|
| 113 |
+
- `tree_grid` (Prüfer trees + 3×3 grid motif): 10–20 nodes.
|
| 114 |

|
| 115 |
- `ba_two_motifs` (Barabási–Albert; house vs 5-cycle motifs): 8–20 nodes.
|
| 116 |

|
|
|
|
| 123 |
|
| 124 |
All examples are synthetically generated using [PyTorch Geometric](https://pytorch-geometric.readthedocs.io/) (2.7.0) primitives:
|
| 125 |
|
| 126 |
+
- Detection subsets: positive samples start from certain base graphs whose node counts are drawn from a uniform distribution before a motif is injected, yielding final graphs with 8–20 or 10-20 nodes depending on the type of base graphs (BA or tree).
|
| 127 |
+
Negative samples use the same process with node counts drawn from `range(MIN_NODES, MAX_NODES + 1)` and no motif.
|
| 128 |
- `ba_two_motifs`: both classes contain motifs injected into Barabási–Albert graphs—house motifs vs 5-cycle motifs—with final graphs spanning 8–20 nodes.
|
| 129 |
|
| 130 |
### Generation Process
|
|
|
|
| 183 |
The script saves a PNG with motif nodes highlighted in orange.
|
| 184 |
Use absolute imports (e.g., `from motif_qa.src.utils import visualize_graph`) if you install the project as a package.
|
| 185 |
|
| 186 |
+
### Interactive Viewer (Streamlit)
|
| 187 |
+
|
| 188 |
+
Launch the interactive graph viewer:
|
| 189 |
+
|
| 190 |
+
```bash
|
| 191 |
+
streamlit run viewer.py
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
The sidebar lets you pick the dataset source (local JSONL or Hugging Face Hub), subset, split, and sample index.
|
| 195 |
+
You can switch between an interactive PyVis view and a static NetworkX view to intuitively understand graph structures.
|
| 196 |
+
|
| 197 |
### Regenerating the Dataset Locally
|
| 198 |
|
| 199 |
```bash
|
|
The diff for this file is too large to render.
See raw diff
|
|
|
|
The diff for this file is too large to render.
See raw diff
|
|
|
|
The diff for this file is too large to render.
See raw diff
|
|
|
|
The diff for this file is too large to render.
See raw diff
|
|
|
|
The diff for this file is too large to render.
See raw diff
|
|
|
|
The diff for this file is too large to render.
See raw diff
|
|
|
|
|
|
|
|
|
|
|
|
@@ -66,11 +66,16 @@ def create_ba_shapes_graphs(num_pos_samples: int, num_neg_samples: int):
|
|
| 66 |
|
| 67 |
def create_tree_graphs(num_pos_samples: int, num_neg_samples: int, motif: Literal["cycle", "grid"]):
|
| 68 |
"""Create base datasets of tree graphs with and without motifs."""
|
| 69 |
-
MIN_NODES =
|
| 70 |
MAX_NODES = 20
|
|
|
|
| 71 |
motif_gen_args = {"cycle": {"num_nodes": 6}, "grid": None}
|
|
|
|
| 72 |
pos_ds = ExplainerDataset(
|
| 73 |
-
graph_generator=UniformPruferTreeGraph(
|
|
|
|
|
|
|
|
|
|
| 74 |
motif_generator=motif,
|
| 75 |
motif_generator_kwargs=motif_gen_args[motif],
|
| 76 |
num_motifs=1,
|
|
@@ -82,6 +87,7 @@ def create_tree_graphs(num_pos_samples: int, num_neg_samples: int, motif: Litera
|
|
| 82 |
num_graphs=num_neg_samples,
|
| 83 |
transform=ShuffleNodes(),
|
| 84 |
)
|
|
|
|
| 85 |
return pos_ds, neg_ds
|
| 86 |
|
| 87 |
|
|
@@ -154,7 +160,7 @@ def format_yes_no_answer(motif_nodes: Iterable[int], edges: list[list[int]]) ->
|
|
| 154 |
return "Yes, there is a motif." if list(motif_nodes) else "No, there is no motif."
|
| 155 |
|
| 156 |
|
| 157 |
-
def
|
| 158 |
motif_edges = [edge for edge in edges if edge[0] in motif_nodes and edge[1] in motif_nodes]
|
| 159 |
if len(motif_edges) == 6:
|
| 160 |
return "Yes, there is a house motif."
|
|
@@ -213,7 +219,7 @@ def main():
|
|
| 213 |
num_neg_samples=args.num_neg_samples,
|
| 214 |
)
|
| 215 |
case "ba_two_motifs":
|
| 216 |
-
formatter =
|
| 217 |
pos_ds, neg_ds = create_two_motif_graphs(
|
| 218 |
num_pos_samples=args.num_pos_samples,
|
| 219 |
num_neg_samples=args.num_neg_samples,
|
|
|
|
| 66 |
|
| 67 |
def create_tree_graphs(num_pos_samples: int, num_neg_samples: int, motif: Literal["cycle", "grid"]):
|
| 68 |
"""Create base datasets of tree graphs with and without motifs."""
|
| 69 |
+
MIN_NODES = 10
|
| 70 |
MAX_NODES = 20
|
| 71 |
+
motif_nnodes = {"cycle": 6, "grid": 9}
|
| 72 |
motif_gen_args = {"cycle": {"num_nodes": 6}, "grid": None}
|
| 73 |
+
|
| 74 |
pos_ds = ExplainerDataset(
|
| 75 |
+
graph_generator=UniformPruferTreeGraph(
|
| 76 |
+
range(MIN_NODES - motif_nnodes[motif], MAX_NODES - motif_nnodes[motif] + 1),
|
| 77 |
+
undirected=True,
|
| 78 |
+
),
|
| 79 |
motif_generator=motif,
|
| 80 |
motif_generator_kwargs=motif_gen_args[motif],
|
| 81 |
num_motifs=1,
|
|
|
|
| 87 |
num_graphs=num_neg_samples,
|
| 88 |
transform=ShuffleNodes(),
|
| 89 |
)
|
| 90 |
+
|
| 91 |
return pos_ds, neg_ds
|
| 92 |
|
| 93 |
|
|
|
|
| 160 |
return "Yes, there is a motif." if list(motif_nodes) else "No, there is no motif."
|
| 161 |
|
| 162 |
|
| 163 |
+
def format_two_motifs_answer(motif_nodes: Iterable[int], edges: list[list[int]]) -> str:
|
| 164 |
motif_edges = [edge for edge in edges if edge[0] in motif_nodes and edge[1] in motif_nodes]
|
| 165 |
if len(motif_edges) == 6:
|
| 166 |
return "Yes, there is a house motif."
|
|
|
|
| 219 |
num_neg_samples=args.num_neg_samples,
|
| 220 |
)
|
| 221 |
case "ba_two_motifs":
|
| 222 |
+
formatter = format_two_motifs_answer
|
| 223 |
pos_ds, neg_ds = create_two_motif_graphs(
|
| 224 |
num_pos_samples=args.num_pos_samples,
|
| 225 |
num_neg_samples=args.num_neg_samples,
|
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import random
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import networkx as nx
|
| 9 |
+
import streamlit as st
|
| 10 |
+
import torch
|
| 11 |
+
from torch_geometric.data import Data
|
| 12 |
+
from torch_geometric.utils import is_undirected, to_networkx
|
| 13 |
+
|
| 14 |
+
DATA_DIR = Path("data")
|
| 15 |
+
DEFAULT_SUBSETS = ("ba_shapes", "tree_cycle", "tree_grid", "ba_two_motifs")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _available_subsets() -> list[str]:
|
| 19 |
+
if DATA_DIR.is_dir():
|
| 20 |
+
subsets = sorted([p.name for p in DATA_DIR.iterdir() if p.is_dir()])
|
| 21 |
+
if subsets:
|
| 22 |
+
return subsets
|
| 23 |
+
return list(DEFAULT_SUBSETS)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@st.cache_data(show_spinner=False)
|
| 27 |
+
def _load_jsonl(path: Path) -> list[dict]:
|
| 28 |
+
if not path.is_file():
|
| 29 |
+
raise FileNotFoundError(f"Could not find dataset file at {path}.")
|
| 30 |
+
with path.open("r", encoding="utf-8") as f:
|
| 31 |
+
return [json.loads(line) for line in f if line.strip()]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@st.cache_data(show_spinner=False)
|
| 35 |
+
def _load_local_examples(subset: str, split: str) -> list[dict]:
|
| 36 |
+
dataset_path = DATA_DIR / subset / f"{split}.jsonl"
|
| 37 |
+
return _load_jsonl(dataset_path)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@st.cache_data(show_spinner=False)
|
| 41 |
+
def _load_hf_examples(dataset_id: str, subset: str, split: str) -> list[dict]:
|
| 42 |
+
try:
|
| 43 |
+
from datasets import load_dataset
|
| 44 |
+
except ImportError as exc:
|
| 45 |
+
raise RuntimeError("The datasets package is required for Hugging Face loading.") from exc
|
| 46 |
+
dataset = load_dataset(dataset_id, name=subset, split=split)
|
| 47 |
+
return [dataset[i] for i in range(len(dataset))]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _build_graph(example: dict) -> Data:
|
| 51 |
+
num_nodes = int(example["nnodes"])
|
| 52 |
+
edges: list[list[int]] = example.get("edges", [])
|
| 53 |
+
undirected_edges: list[tuple[int, int]] = []
|
| 54 |
+
for src, dst in edges:
|
| 55 |
+
undirected_edges.append((src, dst))
|
| 56 |
+
if src != dst:
|
| 57 |
+
undirected_edges.append((dst, src))
|
| 58 |
+
|
| 59 |
+
if undirected_edges:
|
| 60 |
+
edge_index = torch.tensor(undirected_edges, dtype=torch.long).t().contiguous()
|
| 61 |
+
else:
|
| 62 |
+
edge_index = torch.empty((2, 0), dtype=torch.long)
|
| 63 |
+
|
| 64 |
+
graph = Data(edge_index=edge_index, num_nodes=num_nodes)
|
| 65 |
+
node_mask = torch.zeros(num_nodes, dtype=torch.float32)
|
| 66 |
+
motif_nodes = example.get("motif_nodes", [])
|
| 67 |
+
if motif_nodes:
|
| 68 |
+
node_mask[motif_nodes] = 1.0
|
| 69 |
+
graph.node_mask = node_mask
|
| 70 |
+
return graph
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _graph_html(graph: Data, layout_seed: int) -> str:
|
| 74 |
+
if not is_undirected(graph.edge_index):
|
| 75 |
+
raise ValueError("The generated graph is not undirected.")
|
| 76 |
+
|
| 77 |
+
try:
|
| 78 |
+
from pyvis.network import Network
|
| 79 |
+
except ImportError as exc:
|
| 80 |
+
raise RuntimeError("pyvis is required for interactive graph visualization.") from exc
|
| 81 |
+
|
| 82 |
+
node_mask = getattr(graph, "node_mask", None)
|
| 83 |
+
motif_nodes = set(node_mask.nonzero(as_tuple=True)[0].tolist())
|
| 84 |
+
|
| 85 |
+
net = Network(height="650px", width="100%", directed=False, bgcolor="#ffffff")
|
| 86 |
+
net.barnes_hut()
|
| 87 |
+
net.set_options(
|
| 88 |
+
f"""
|
| 89 |
+
{{
|
| 90 |
+
"layout": {{
|
| 91 |
+
"randomSeed": {layout_seed}
|
| 92 |
+
}},
|
| 93 |
+
"physics": {{
|
| 94 |
+
"barnesHut": {{
|
| 95 |
+
"gravitationalConstant": -20000,
|
| 96 |
+
"springLength": 120,
|
| 97 |
+
"springConstant": 0.04
|
| 98 |
+
}},
|
| 99 |
+
"minVelocity": 0.75
|
| 100 |
+
}},
|
| 101 |
+
"nodes": {{
|
| 102 |
+
"shape": "dot",
|
| 103 |
+
"font": {{
|
| 104 |
+
"size": 24,
|
| 105 |
+
"face": "arial"
|
| 106 |
+
}}
|
| 107 |
+
}},
|
| 108 |
+
"edges": {{
|
| 109 |
+
"color": {{
|
| 110 |
+
"inherit": true
|
| 111 |
+
}},
|
| 112 |
+
"smooth": false
|
| 113 |
+
}}
|
| 114 |
+
}}
|
| 115 |
+
"""
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
for node_id in range(graph.num_nodes):
|
| 119 |
+
size = 18
|
| 120 |
+
if node_id in motif_nodes:
|
| 121 |
+
color = "#ff8c00"
|
| 122 |
+
font_color = "#111111"
|
| 123 |
+
else:
|
| 124 |
+
color = "#87ceeb"
|
| 125 |
+
font_color = "#111111"
|
| 126 |
+
label = str(node_id)
|
| 127 |
+
net.add_node(node_id, label=label, color=color, size=size, font={"color": font_color})
|
| 128 |
+
|
| 129 |
+
edge_index = graph.edge_index.t().tolist()
|
| 130 |
+
seen = set()
|
| 131 |
+
for src, dst in edge_index:
|
| 132 |
+
if src == dst:
|
| 133 |
+
continue
|
| 134 |
+
key = (min(src, dst), max(src, dst))
|
| 135 |
+
if key in seen:
|
| 136 |
+
continue
|
| 137 |
+
seen.add(key)
|
| 138 |
+
net.add_edge(src, dst)
|
| 139 |
+
|
| 140 |
+
return net.generate_html()
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _plot_graph(graph: Data, layout_seed: int) -> plt.Figure:
|
| 144 |
+
if not is_undirected(graph.edge_index):
|
| 145 |
+
raise ValueError("The generated graph is not undirected.")
|
| 146 |
+
|
| 147 |
+
G = to_networkx(graph, to_undirected=True)
|
| 148 |
+
pos = nx.spring_layout(G, seed=layout_seed)
|
| 149 |
+
|
| 150 |
+
node_mask = getattr(graph, "node_mask", None)
|
| 151 |
+
motif_nodes = node_mask.nonzero(as_tuple=True)[0].tolist()
|
| 152 |
+
normal_nodes = [n for n in G.nodes if n not in motif_nodes]
|
| 153 |
+
|
| 154 |
+
fig, ax = plt.subplots(figsize=(6, 4.5))
|
| 155 |
+
nx.draw_networkx_nodes(G, pos, nodelist=normal_nodes, node_color="skyblue", node_size=120, ax=ax)
|
| 156 |
+
nx.draw_networkx_nodes(G, pos, nodelist=motif_nodes, node_color="orange", node_size=120, ax=ax)
|
| 157 |
+
nx.draw_networkx_edges(G, pos, alpha=0.3, ax=ax)
|
| 158 |
+
|
| 159 |
+
labels = {n: str(n) for n in G.nodes()}
|
| 160 |
+
if normal_nodes:
|
| 161 |
+
nx.draw_networkx_labels(
|
| 162 |
+
G,
|
| 163 |
+
pos,
|
| 164 |
+
labels={n: labels[n] for n in normal_nodes},
|
| 165 |
+
font_size=10,
|
| 166 |
+
font_color="black",
|
| 167 |
+
ax=ax,
|
| 168 |
+
)
|
| 169 |
+
if motif_nodes:
|
| 170 |
+
nx.draw_networkx_labels(
|
| 171 |
+
G,
|
| 172 |
+
pos,
|
| 173 |
+
labels={n: labels[n] for n in motif_nodes},
|
| 174 |
+
font_size=10,
|
| 175 |
+
font_color="black",
|
| 176 |
+
ax=ax,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
ax.axis("off")
|
| 180 |
+
fig.tight_layout()
|
| 181 |
+
return fig
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def render_sidebar() -> dict | None:
|
| 185 |
+
subsets = _available_subsets()
|
| 186 |
+
with st.sidebar:
|
| 187 |
+
dataset_source = st.radio("Dataset", ["Local JSONL", "Hugging Face Hub"], index=0)
|
| 188 |
+
dataset_id = st.text_input("Dataset ID", "naos-ku/motif-qa", disabled=dataset_source != "Hugging Face Hub")
|
| 189 |
+
subset = st.selectbox("Subset", options=subsets, index=0)
|
| 190 |
+
split_choice = st.selectbox("Split", options=["train", "val", "test"], index=0)
|
| 191 |
+
|
| 192 |
+
if dataset_source == "Local JSONL":
|
| 193 |
+
split_name = "val" if split_choice == "val" else split_choice
|
| 194 |
+
try:
|
| 195 |
+
examples = _load_local_examples(subset, split_name)
|
| 196 |
+
except FileNotFoundError as exc:
|
| 197 |
+
st.error(str(exc))
|
| 198 |
+
return None
|
| 199 |
+
else:
|
| 200 |
+
split_name = "validation" if split_choice == "val" else split_choice
|
| 201 |
+
try:
|
| 202 |
+
examples = _load_hf_examples(dataset_id, subset, split_name)
|
| 203 |
+
except Exception as exc:
|
| 204 |
+
st.error(str(exc))
|
| 205 |
+
return None
|
| 206 |
+
|
| 207 |
+
if not examples:
|
| 208 |
+
st.warning("No examples found for the selected configuration.")
|
| 209 |
+
return None
|
| 210 |
+
|
| 211 |
+
st.sidebar.caption(f"Samples: {len(examples)}")
|
| 212 |
+
|
| 213 |
+
if "sample_idx" not in st.session_state:
|
| 214 |
+
st.session_state.sample_idx = 0
|
| 215 |
+
|
| 216 |
+
def _pick_random_sample() -> None:
|
| 217 |
+
st.session_state.sample_idx = random.randrange(len(examples))
|
| 218 |
+
|
| 219 |
+
sample_idx = st.sidebar.number_input(
|
| 220 |
+
"Sample idx",
|
| 221 |
+
min_value=0,
|
| 222 |
+
max_value=len(examples) - 1,
|
| 223 |
+
value=st.session_state.sample_idx,
|
| 224 |
+
step=1,
|
| 225 |
+
key="sample_idx",
|
| 226 |
+
)
|
| 227 |
+
st.sidebar.button("Pick randomly", on_click=_pick_random_sample)
|
| 228 |
+
st.sidebar.divider()
|
| 229 |
+
st.sidebar.markdown("### Visualization Settings")
|
| 230 |
+
viz_method = st.sidebar.radio("Visualization method", ["Interactive (PyVis)", "Static (NetworkX)"], index=0)
|
| 231 |
+
layout_seed = None
|
| 232 |
+
if viz_method == "Static (NetworkX)":
|
| 233 |
+
layout_seed = st.sidebar.number_input("Layout seed", min_value=0, value=42, step=1)
|
| 234 |
+
|
| 235 |
+
st.sidebar.divider()
|
| 236 |
+
st.sidebar.link_button("Open HF dataset", "https://huggingface.co/datasets/naos-ku/motif-qa", icon="🤗")
|
| 237 |
+
|
| 238 |
+
return {
|
| 239 |
+
"examples": examples,
|
| 240 |
+
"sample_idx": sample_idx,
|
| 241 |
+
"viz_method": viz_method,
|
| 242 |
+
"layout_seed": layout_seed,
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def render_content(state: dict) -> None:
|
| 247 |
+
example = state["examples"][state["sample_idx"]]
|
| 248 |
+
graph = _build_graph(example)
|
| 249 |
+
|
| 250 |
+
with st.expander("Sample details", expanded=False):
|
| 251 |
+
num_edges = example.get("nedges", len(example.get("edges", [])))
|
| 252 |
+
st.write(f"Nodes: {example.get('nnodes', 0)}")
|
| 253 |
+
st.write(f"Edges: {num_edges}")
|
| 254 |
+
motif_nodes = example.get("motif_nodes", [])
|
| 255 |
+
st.write(f"Motif nodes: {motif_nodes if motif_nodes else 'None'}")
|
| 256 |
+
if "prompt" in example:
|
| 257 |
+
st.markdown("**Prompt**")
|
| 258 |
+
st.write(example["prompt"])
|
| 259 |
+
if "response" in example:
|
| 260 |
+
st.markdown("**Response**")
|
| 261 |
+
st.write(example["response"])
|
| 262 |
+
|
| 263 |
+
if state["viz_method"] == "Static (NetworkX)":
|
| 264 |
+
fig = _plot_graph(graph, layout_seed=state["layout_seed"] or 42)
|
| 265 |
+
st.pyplot(fig, clear_figure=True)
|
| 266 |
+
plt.close(fig)
|
| 267 |
+
else:
|
| 268 |
+
html = _graph_html(graph, layout_seed=42)
|
| 269 |
+
st.components.v1.html(html, height=700, scrolling=True)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def main() -> None:
|
| 273 |
+
st.set_page_config(page_title="MotifQA Graph Viewer", layout="wide")
|
| 274 |
+
st.title("MotifQA Graph Viewer")
|
| 275 |
+
|
| 276 |
+
state = render_sidebar()
|
| 277 |
+
if state is None:
|
| 278 |
+
return
|
| 279 |
+
render_content(state)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
if __name__ == "__main__":
|
| 283 |
+
main()
|