#!/usr/bin/env python3 """ Generate a fast, cluster-first graph viewer from graphify graph.json. Uses Canvas2D with viewport culling, squared distance tests, and batched stroke drawing. """ import json import math import random import sys import os from collections import defaultdict, Counter random.seed(42) SCOPE_CONFIGS = { "studiq": { "json": "/Users/baljotchohan/Projects/StudIQ/studiq/graphify-out/graph.json", "out": "/Users/baljotchohan/Projects/StudIQ/studiq/graphify-out/graph_fast.html", "title": "StudIQ Codebase Graph", }, "root": { "json": "/Users/baljotchohan/Projects/StudIQ/graphify-out/graph.json", "out": "/Users/baljotchohan/Projects/StudIQ/graphify-out/graph_fast.html", "title": "StudIQ Root Graph", } } COLORS = [ "#00f2fe", "#b224ef", "#ff007f", "#39ff14", "#ff00ff", "#00ffff", "#ffb703", "#fb8500", "#ff006e", "#8338ec", "#3a86c8", "#ffbe0b", "#4895ef", "#4cc9f0", "#7209b7", "#f72585", "#3f37c9", "#3b28cc", "#a900ff", "#00bbf9", ] def spiral_layout(communities): """Place communities in a tight spiral layout.""" comms = sorted(communities.items(), key=lambda x: -len(x[1])) positions = {} golden = (1 + math.sqrt(5)) / 2 for i, (cid, nodes) in enumerate(comms): r = math.sqrt(i + 1) * 160 theta = 2 * math.pi * i / (golden ** 2) positions[cid] = (r * math.cos(theta), r * math.sin(theta)) return positions def build_fast_html(scope: str): cfg = SCOPE_CONFIGS[scope] print(f"[{scope}] Reading {cfg['json']}...") with open(cfg["json"]) as f: data = json.load(f) raw_nodes = data["nodes"] raw_links = data["links"] target_dir = "/Users/baljotchohan/Projects/StudIQ" if scope == "root" else "/Users/baljotchohan/Projects/StudIQ/studiq" # Determine top-level folder prefix for each node node_folder = {} for n in raw_nodes: sf = n.get("source_file", "") sf = sf.replace("\\", "/") folder = "root" if sf.startswith(target_dir): rel = sf[len(target_dir):].lstrip("/") parts = rel.split("/") if parts and parts[0]: folder = parts[0] node_folder[n["id"]] = folder # Re-map small communities (size < min_size) to folder-specific misc communities min_size = 15 if scope == "root" else 6 orig_comm_sizes = Counter(n.get("community", 0) for n in raw_nodes) for n in raw_nodes: cid = n.get("community", 0) if orig_comm_sizes[cid] < min_size: folder = node_folder.get(n["id"], "other") n["community"] = f"misc_{folder}" # Build community structure comm_nodes = defaultdict(list) node_by_id = {} for n in raw_nodes: cid = n["community"] comm_nodes[cid].append(n) node_by_id[n["id"]] = n # Assign colors to communities comm_hex = {} comm_rgb = {} comm_list = sorted(comm_nodes.keys(), key=lambda x: str(x)) for i, cid in enumerate(comm_list): hex_color = COLORS[i % len(COLORS)] comm_hex[cid] = hex_color # Parse hex to rgb string for Canvas usage r_val = int(hex_color[1:3], 16) g_val = int(hex_color[3:5], 16) b_val = int(hex_color[5:7], 16) comm_rgb[cid] = f"{r_val},{g_val},{b_val}" # Determine community labels comm_label = {} for cid, ns in comm_nodes.items(): if str(cid).startswith("misc_"): folder = str(cid)[5:] comm_label[cid] = f"Other {folder} files ({len(ns)})" else: folders = [node_folder.get(n["id"], "other") for n in ns] dom_folder = Counter(folders).most_common(1)[0][0] if folders else "other" comm_label[cid] = f"{dom_folder} - Comm {cid} ({len(ns)})" # Spiral layout for communities comm_positions = spiral_layout(comm_nodes) # Pre-compute node positions within each community (mini circle) node_positions = {} for cid, ns in comm_nodes.items(): cx, cy = comm_positions.get(cid, (0, 0)) count = len(ns) radius = max(30, math.sqrt(count) * 20) for i, n in enumerate(ns): angle = 2 * math.pi * i / max(count, 1) nx = cx + radius * math.cos(angle) ny = cy + radius * math.sin(angle) node_positions[n["id"]] = (nx, ny) # Build lightweight node list for cluster view cluster_nodes = [] for cid in comm_list: ns = comm_nodes[cid] cx, cy = comm_positions.get(cid, (0, 0)) sz = max(15, min(65, math.sqrt(len(ns)) * 8)) cluster_nodes.append({ "id": f"c_{cid}", "cid": cid, "label": comm_label.get(cid, str(cid)), "x": cx, "y": cy, "r": sz, "color": comm_hex.get(cid, "#4E79A7"), "color_rgb": comm_rgb.get(cid, "78,121,167"), "count": len(ns), }) # Build cluster-level edges (edges between communities) cluster_edge_counts = defaultdict(int) for lnk in raw_links: src = node_by_id.get(lnk["source"]) tgt = node_by_id.get(lnk["target"]) if src and tgt: sc = src["community"] tc = tgt["community"] if sc != tc: key = (min(str(sc), str(tc)), max(str(sc), str(tc))) cluster_edge_counts[key] += 1 cluster_edges = [] for (sc, tc), cnt in cluster_edge_counts.items(): cluster_edges.append({ "source": f"c_{sc}", "target": f"c_{tc}", "w": min(4, 1 + cnt // 5) }) # Full nodes per community (for drill-down) community_data = {} for cid, ns in comm_nodes.items(): community_data[str(cid)] = { "nodes": [ { "id": n["id"], "label": n.get("label", n["id"])[:40], "file_type": n.get("file_type", "code"), "source_file": n.get("source_file", ""), "x": node_positions[n["id"]][0], "y": node_positions[n["id"]][1], "color": comm_hex.get(cid, "#4E79A7"), "color_rgb": comm_rgb.get(cid, "78,121,167"), } for n in ns ], "links": [ {"s": lnk["source"], "t": lnk["target"]} for lnk in raw_links if node_by_id.get(lnk["source"], {}).get("community") == cid and node_by_id.get(lnk["target"], {}).get("community") == cid ], "color": comm_hex.get(cid, "#4E79A7"), "color_rgb": comm_rgb.get(cid, "78,121,167"), "label": comm_label.get(cid, str(cid)), } stats_str = f"{len(raw_nodes):,} nodes · {len(raw_links):,} edges · {len(comm_list):,} communities" # Compute bounding box for initial viewport all_cx = [c["x"] for c in cluster_nodes] all_cy = [c["y"] for c in cluster_nodes] if all_cx: min_x, max_x = min(all_cx), max(all_cx) min_y, max_y = min(all_cy), max(all_cy) else: min_x = max_x = min_y = max_y = 0 center_x = (min_x + max_x) / 2 center_y = (min_y + max_y) / 2 html = f"""