Graphify と NetworkX を用いた Python コードベース構造の可視化:ゴッドノード、コミュニティ、アーキテクチャ図の作成
このチュートリアルは、Graphify と NetworkX を組み合わせて大規模な Python コードベースをオフラインで解析し、ノードの中心性やコミュニティ検出を通じてアーキテクチャ構造を可視化する実践的な手法を提供しています。
キーポイント
オフラインでのコード解析ワークフロー
LLM や API キーを必要とせず、Tree-sitter ベースの Graphify を使用してローカル環境でコードベースを知識グラフに変換する完全な手順を示しています。
高度な構造分析手法
NetworkX を活用し、ファイルタイプや関係性の分類、中心性スコアの算出、コミュニティ検出、重要なシンボル間の最短経路探索など多角的な分析を実行します。
可視化によるアーキテクチャ理解
静的およびインタラクティブなグラフ可視化を作成することで、モジュール、クラス、関数、データベースオブジェクト間の複雑な接続関係を直感的に把握できるようにします。
設定ファイルの「神ノード」化
'config.py'内のSettingsクラスは、データベース接続文字列やシークレットキーなど全モジュールで参照される重要な設定を一元管理しており、コードベース内で明確な「神ノード」として機能します。
依存関係の可視化とアーキテクチャ
このサンプルコードは、auth.pyやservices.pyなど複数のファイルがconfigやdatabaseをインポートする階層的な依存構造を持っており、NetworkXを用いたグラフ分析でこれらの結合度やコミュニティを特定できます。
動的ファイル生成による分析基盤の構築
Pythonスクリプトが事前に定義された辞書から複数のソースファイルを自動生成することで、GraphifyやNetworkXを用いた静的解析のための統一されたテスト環境(サンプルアプリ)を瞬時に構築しています。
Graphify を用いたローカル知識グラフの抽出
外部 API や LLM バックエンドを介さず、`graphify extract` コマンドを実行してプロジェクト内のモジュール間のインポートや依存関係を解析し、JSON 形式で構造化データを生成します。
影響分析・編集コメントを表示
影響分析
この記事は、大規模なソフトウェアプロジェクトの複雑さを可視化し、保守性を向上させるための実用的なツールチェーンを提示しています。特に、LLM の依存やコストを排除してコード構造を分析できる点は、開発現場におけるアーキテクチャレビューや技術的負債の特定において即戦力となる価値があります。
編集コメント
LLM を使わないアプローチでありながら、コードの構造理解という課題に対して非常に効果的な解決策を示しており、開発者の生産性向上に寄与する実用的な記事です。
このチュートリアルでは、現実的なマルチモジュール Python アプリケーションをナレッジグラフに変換する完全オフラインの Graphify ワークフローを構築します。まず、Graphify とサポート用グラフライブラリをインストールし、設定、データベース、認証、サービス、API、キャッシュ、モデル、SQL レイヤーを含む小さくも相互接続されたサンプルアプリケーションを生成します。その後、Graphify の tree-sitter ベースの分析を使用してローカルでグラフを抽出するため、API キーや LLM バックエンドは不要です。生成された graph.json を NetworkX に読み込んだ後、ファイルタイプ、関係タイプ、中心性スコア、コミュニティ検出、重要なシンボル間の最短経路などを用いてコードベースの構造を分析します。さらに、静的およびインタラクティブな可視化を作成し、プロジェクト全体にわたるモジュール、クラス、関数、データベースオブジェクトがどのように接続されているかを理解しやすくします。
Graphify と NetworkX のインストール
import subprocess, sys
def pip(*pkgs):
subprocess.run([sys.executable, "-m", "pip", "install", "-q", *pkgs], check=False)
pip("graphifyy[sql]", "pyvis", "networkx", "matplotlib")
import os, json, glob, textwrap, warnings
import networkx as nx
import matplotlib.pyplot as plt
warnings.filterwarnings("ignore")
チュートリアルに必要なグラフ分析および可視化ライブラリとともに、Graphify をインストールします。必要な Python モジュールをインポートし、グラフ処理には NetworkX を、静的プロットには Matplotlib を使用します。また、不要な警告を抑制して、ノートブックの出力がクリーンで焦点に絞られた状態になるようにしています。
サンプルコードベースの構築
コードをコピーしました別のブラウザを使用してください
ROOT = "sample_app"
os.makedirs(ROOT, exist_ok=True)
FILES = {
"config.py": '''
中央設定オブジェクト — どこでも使用されます(これは「ゴッドノード」となることを想定してください)。
class Settings:
def __init__(self):
self.db_dsn = "postgresql://localhost/app"
self.jwt_secret = "change-me"
self.rate_limit = 100
settings = Settings()
''',
"database.py": '''
from config import settings
class DatabasePool:
"""接続プール。理由:クエリごとに再接続するのではなく、ソケットを再利用するため。"""
def __init__(self, dsn):
self.dsn = dsn
self._conns = []
def acquire(self):
return {"dsn": self.dsn}
pool = DatabasePool(settings.db_dsn)
def get_connection():
return pool.acquire()
''',
"models.py": '''
class User:
def __init__(self, user_id, email):
self.user_id = user_id
self.email = email
class Session:
def __init__(self, user, token):
self.user = user
self.token = token
''',
"cache.py": '''
from config import settings
class RateLimiter:
# 注意:素朴なメモリ内リミッターです。本番環境では Redis に置き換えてください。
def __init__(self, limit):
self.limit = limit
self.hits = {}
def allow(self, key):
self.hits[key] = self.hits.get(key, 0) + 1
return self.hits[key] <= self.limit
limiter = RateLimiter(settings.rate_limit)
''',
"auth.py": '''
from config import settings
from database import get_connection
from models import User, Session
def hash_password(raw):
return f"hashed::{raw}"
def verify_password(raw, hashed):
return hash_password(raw) == hashed
class AuthService:
def __init__(self):
self.secret = settings.jwt_secret
def login(self, email, password):
conn = get_connection()
user = User(user_id=1, email=email)
return Session(user=user, token=self.secret + email)
''',
"services.py": '''
from database import get_connection
from models import User
from auth import AuthService
class UserService:
def __init__(self):
self.auth = AuthService()
def register(self, email, password):
conn = get_connection()
return User(user_id=2, email=email)
def authenticate(self, email, password):
return self.auth.login(email, password)
''',
"api.py": '''
from cache import limiter
from services import UserService
from auth import verify_password
svc = UserService()
def signup_route(email, password):
if not limiter.allow(email):
return {"error": "rate limited"}
return svc.register(email, password)
def login_route(email, password):
if not limiter.allow(email):
return {"error": "rate limited"}
return svc.authenticate(email, password)
''',
"main.py": '''
from api import signup_route, login_route
from database import pool
def run():
signup_route("a@x.com", "pw")
return login_route("a@x.com", "pw")
if __name__ == "__main__":
run()
''',
"schema.sql": '''
CREATE TABLE users (
user_id SERIAL PRIMARY KEY,
email TEXT UNIQUE NOT NULL
);
CREATE TABLE sessions (
token TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(user_id)
);
CREATE VIEW active_sessions AS
SELECT s.token, u.email
FROM sessions s JOIN users u ON s.user_id = u.user_id;
''',
}
for name, body in FILES.items():
with open(os.path.join(ROOT, name), "w") as f:
f.write(textwrap.dedent(body).lstrip())
print(f"Wrote {len(FILES)} files to ./{ROOT}/")
複数の Python モジュールと 1 つの SQL スキーマファイルを含む、現実的なサンプルアプリケーションを作成します。これらのファイルには、インポート、関数呼び出し、サービス依存関係、認証ロジック、データベースアクセス、レート制限など、意味のあるモジュール間関係を意図的に含めています。その後、これらすべてのファイルをローカルの sample_app ディレクトリに書き込み、Graphify に対して分析用の完全なミニコードベースを提供します。
ナレッジグラフの抽出
Copy CodeCopiedUse a different Browser
res = subprocess.run(
[sys.executable, "-m", "graphify", "extract", ROOT, "--no-cluster"],
capture_output=True, text=True
)
print(res.stdout[-1500:] or res.stderr[-1500:])
graph_paths = glob.glob("**/graph.json", recursive=True)
assert graph_paths, "graph.json not found — check the extract output above."
GRAPH_JSON = sorted(graph_paths, key=os.path.getmtime)[-1]
print("Graph file:", GRAPH_JSON)
def load_graphify(path):
data = json.load(open(path))
ekey = "links" if "links" in data else ("edges" if "edges" in data else None)
G = nx.DiGraph() if data.get("directed") else nx.Graph()
for n in data.get("nodes", []):
nid = n.get("id")
G.add_node(nid, **{k: v for k, v in n.items() if k != "id"})
for e in data.get(ekey or "links", []):
G.add_edge(e.get("source"), e.get("target"),
**{k: v for k, v in e.items() if k not in ("source", "target")})
G.graph.update(data.get("graph", {}))
return G
G = load_graphify(GRAPH_JSON)
UG = G.to_undirected()
print(f"\nGraph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
def label(n):
return G.nodes[n].get("label", str(n))
生成されたアプリケーション上で Graphify をローカル環境で実行し、API キーや LLM バックエンドを使用せずにプロジェクトの知識グラフを抽出します。生成された graph.json ファイルの場所を確認し、バージョン互換性のあるノードリンクローダーを使用して NetworkX に読み込みます。その後、構造的解析を容易にするためグラフを無向形式に変換し、可読性の高いノードラベルを表示するためのヘルパー関数を定義します。
中心性とコミュニティの分析
コードをコピーしました
別のブラウザを使用してください
from collections import Counter
ftypes = Counter(d.get("file_type", "?") for _, d in G.nodes(data=True))
rels = Counter(d.get("relation", "?") for *_ , d in G.edges(data=True))
conf = Counter(d.get("confidence", "?") for *_ , d in G.edges(data=True))
print("\nNodes by file_type :", dict(ftypes))
print("Edges by relation :", dict(rels))
print("Edges by confidence:", dict(conf))
deg = nx.degree_centrality(UG)
btw = nx.betweenness_centrality(UG)
print("\nTop 'god nodes' by degree centrality:")
for n, c in sorted(deg.items(), key=lambda x: -x[1])[:8]:
print(f" {label(n):<22} deg={c:.3f} betweenness={btw.get(n,0):.3f}")
try:
communities = nx.community.louvain_communities(UG, seed=42)
except Exception:
communities = list(nx.community.greedy_modularity_communities(UG))
node_comm = {n: i for i, com in enumerate(communities) for n in com}
print(f"\nDetected {len(communities)} communities:")
for i, com in enumerate(communities):
members = ", ".join(sorted(label(n) for n in com))[:90]
print(f" Community {i}: {members}")
def find(substr):
for n in G.nodes:
if substr.lower() in label(n).lower():
return n
return None
a, b = find("api"), find("DatabasePool")
if a and b and nx.has_path(UG, a, b):
path = nx.shortest_path(UG, a, b)
print(f"\nPath {label(a)} -> {label(b)}:")
print(" " + " → ".join(label(p) for p in path))
抽出したグラフを、ノードタイプ、エッジ関係、および信頼度レベルの要約によって分析します。アプリケーションの多くの部分を接続する重要な「ゴッドノード」を特定するために、次数中心性と媒介中心性を計算します。また、グラフ内のコミュニティを検出し、主要コンポーネント間の最短経路を追跡して、コードベースの各部分がどのように接続されているかを理解します。
コードグラフの可視化
コピー コピー済み別のブラウザを使用してください
plt.figure(figsize=(13, 9))
pos = nx.spring_layout(UG, k=0.7, seed=42)
nx.draw_networkx_edges(UG, pos, alpha=0.25)
nx.draw_networkx_nodes(
UG, pos,
node_color=[node_comm.get(n, 0) for n in UG.nodes],
node_size=[300 + 4000 * deg.get(n, 0) for n in UG.nodes],
cmap=plt.cm.tab20, alpha=0.9,
)
top = {n for n, _ in sorted(deg.items(), key=lambda x: -x[1])[:14]}
nx.draw_networkx_labels(UG, pos, {n: label(n) for n in top}, font_size=8)
plt.title("Graphify knowledge graph — size=centrality, color=community")
plt.axis("off"); plt.tight_layout()
plt.savefig("graph_static.png", dpi=130); plt.show()
try:
from pyvis.network import Network
net = Network(height="650px", width="100%", bgcolor="#111", font_color="white",
notebook=True, cdn_resources="in_line", directed=G.is_directed())
palette = ["#e6194B","#3cb44b","#4363d8","#f58231","#911eb4",
"#42d4f4","#f032e6","#bfef45","#fabed4","#469990"]
for n, d in G.nodes(data=True):
c = node_comm.get(n, 0)
net.add_node(n, label=label(n), title=f"{d.get('file_type','?')} · {d.get('source_file','')}",
color=palette[c % len(palette)], size=12 + 60 * deg.get(n, 0))
for s, t, d in G.edges(data=True):
net.add_edge(s, t, title=d.get("relation", ""))
net.save_graph("graph_interactive.html")
print("\nSaved interactive graph -> graph_interactive.html")
from IPython.display import HTML, display
display(HTML(open("graph_interactive.html").read()))
except Exception as e:
print("Interactive viz skipped:", e)
for cmd in (
["query", "what connects auth to the database?", "--graph", GRAPH_JSON],
["path", "AuthService", "DatabasePool", "--graph", GRAPH_JSON],
["explain", "RateLimiter", "--graph", GRAPH_JSON],
):
print("\n$ graphify " + " ".join(cmd))
r = subprocess.run([sys.executable, "-m", "graphify", *cmd],
capture_output=True, text=True)
print((r.stdout or r.stderr)[:1200])
print("\nDone. Artifacts: graph_static.png, graph_interactive.html,",
"and graphify-out/ (graph.json, GRAPH_REPORT.md).")
私たちは、静的およびインタラクティブな両方の手法を用いて知識グラフを可視化します。まず、ノードサイズが中心性を表し、ノードの色がコミュニティ所属を表す Matplotlib グラフを作成します。次に、インタラクティブな Pyvis 可視化を構築し、Graphify の CLI コマンドを実行してグラフを検索し、パスを見つけ、選択されたシンボルを説明します。
結論として、ソースコードを有用な知識グラフに変換し、グラフ解析を用いて研究するための完全なローカルパイプラインを確立しました。Graphify が Python および SQL のコードベースから意味のある関係性を抽出する方法と、NetworkX を用いて中心的な「ゴッドノード」を特定し、コミュニティを検出し、認証やデータベースロジックなどのコンポーネント間のパスを追跡する方法を確認しました。また、アーキテクチャを高レベルおよびインタラクティブな視点の両方から検査するのに役立つ視覚的出力も生成しました。このワークフローは、外部 API に依存することなく、コード構造、依存関係の流れ、アーキテクチャ上のホットスポット、ファイル間の接続について推論するための道筋を提供し、コードベースの探索、ドキュメント作成、リファクタリング、ソフトウェアアーキテクチャ分析に有用です。
完全なコードはこちらで確認できます。また、Twitter でフォローすることもお気軽にどうぞ。150k 人以上が参加する ML SubReddit への参加や、ニュースレターの購読もお忘れなく。待ってください!Telegram をご利用ですか?今なら Telegram でも私たちに参加いただけます。
GitHub リポジトリの宣伝、Hugging Face ページ、製品リリース、ウェビナーなどのプロモーションでパートナーシップを希望される場合は、ぜひご連絡ください。
Python コードベースの構造を、ゴッドノード、コミュニティ、アーキテクチャ可視化を用いてマッピングする Graphify と NetworkX の利用に関する記事は、MarkTechPost で最初に公開されました。
原文を表示
In this tutorial, we build a fully offline Graphify workflow that turns a realistic multi-module Python application into a knowledge graph. We start by installing Graphify and supporting graph libraries, then generate a small but connected sample application with configuration, database, authentication, service, API, cache, model, and SQL layers. We extract the graph locally using Graphify’s tree-sitter-based analysis, so we do not need an API key or any LLM backend. After loading the generated graph.json into NetworkX, we analyze the codebase’s structure using file types, relationship types, centrality scores, community detection, and shortest paths among important symbols. Also, we create both static and interactive visualizations, making it easier to understand how modules, classes, functions, and database objects connect across the project.
Installing Graphify and NetworkX
Copy CodeCopiedUse a different Browser
import subprocess, sys
def pip(*pkgs):
subprocess.run([sys.executable, "-m", "pip", "install", "-q", *pkgs], check=False)
pip("graphifyy[sql]", "pyvis", "networkx", "matplotlib")
import os, json, glob, textwrap, warnings
import networkx as nx
import matplotlib.pyplot as plt
warnings.filterwarnings("ignore")
We install Graphify along with the graph analysis and visualization libraries needed for the tutorial. We import the required Python modules, including NetworkX for graph processing and Matplotlib for static plotting. We also suppress unnecessary warnings so the notebook output stays clean and focused.
Building the Sample Codebase
Copy CodeCopiedUse a different Browser
ROOT = "sample_app"
os.makedirs(ROOT, exist_ok=True)
FILES = {
"config.py": '''
Central settings object — used everywhere (expect this to be a "god node").
class Settings:
def __init__(self):
self.db_dsn = "postgresql://localhost/app"
self.jwt_secret = "change-me"
self.rate_limit = 100
settings = Settings()
''',
"database.py": '''
from config import settings
class DatabasePool:
"""Connection pool. WHY: reuse sockets instead of reconnecting per query."""
def __init__(self, dsn):
self.dsn = dsn
self._conns = []
def acquire(self):
return {"dsn": self.dsn}
pool = DatabasePool(settings.db_dsn)
def get_connection():
return pool.acquire()
''',
"models.py": '''
class User:
def __init__(self, user_id, email):
self.user_id = user_id
self.email = email
class Session:
def __init__(self, user, token):
self.user = user
self.token = token
''',
"cache.py": '''
from config import settings
class RateLimiter:
# NOTE: naive in-memory limiter; swap for Redis in prod.
def __init__(self, limit):
self.limit = limit
self.hits = {}
def allow(self, key):
self.hits[key] = self.hits.get(key, 0) + 1
return self.hits[key] <= self.limit
limiter = RateLimiter(settings.rate_limit)
''',
"auth.py": '''
from config import settings
from database import get_connection
from models import User, Session
def hash_password(raw):
return f"hashed::{raw}"
def verify_password(raw, hashed):
return hash_password(raw) == hashed
class AuthService:
def __init__(self):
self.secret = settings.jwt_secret
def login(self, email, password):
conn = get_connection()
user = User(user_id=1, email=email)
return Session(user=user, token=self.secret + email)
''',
"services.py": '''
from database import get_connection
from models import User
from auth import AuthService
class UserService:
def __init__(self):
self.auth = AuthService()
def register(self, email, password):
conn = get_connection()
return User(user_id=2, email=email)
def authenticate(self, email, password):
return self.auth.login(email, password)
''',
"api.py": '''
from cache import limiter
from services import UserService
from auth import verify_password
svc = UserService()
def signup_route(email, password):
if not limiter.allow(email):
return {"error": "rate limited"}
return svc.register(email, password)
def login_route(email, password):
if not limiter.allow(email):
return {"error": "rate limited"}
return svc.authenticate(email, password)
''',
"main.py": '''
from api import signup_route, login_route
from database import pool
def run():
signup_route("a@x.com", "pw")
return login_route("a@x.com", "pw")
if __name__ == "__main__":
run()
''',
"schema.sql": '''
CREATE TABLE users (
user_id SERIAL PRIMARY KEY,
email TEXT UNIQUE NOT NULL
);
CREATE TABLE sessions (
token TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(user_id)
);
CREATE VIEW active_sessions AS
SELECT s.token, u.email
FROM sessions s JOIN users u ON s.user_id = u.user_id;
''',
}
for name, body in FILES.items():
with open(os.path.join(ROOT, name), "w") as f:
f.write(textwrap.dedent(body).lstrip())
print(f"Wrote {len(FILES)} files to ./{ROOT}/")
We create a realistic sample application with multiple Python modules and one SQL schema file. We design the files to include meaningful cross-module relationships, such as imports, function calls, service dependencies, authentication logic, database access, and rate limiting. We then write all these files to a local sample_app directory, giving Graphify a complete mini-codebase to analyze.
Extracting the Knowledge Graph
Copy CodeCopiedUse a different Browser
res = subprocess.run(
[sys.executable, "-m", "graphify", "extract", ROOT, "--no-cluster"],
capture_output=True, text=True
)
print(res.stdout[-1500:] or res.stderr[-1500:])
graph_paths = glob.glob("**/graph.json", recursive=True)
assert graph_paths, "graph.json not found — check the extract output above."
GRAPH_JSON = sorted(graph_paths, key=os.path.getmtime)[-1]
print("Graph file:", GRAPH_JSON)
def load_graphify(path):
data = json.load(open(path))
ekey = "links" if "links" in data else ("edges" if "edges" in data else None)
G = nx.DiGraph() if data.get("directed") else nx.Graph()
for n in data.get("nodes", []):
nid = n.get("id")
G.add_node(nid, **{k: v for k, v in n.items() if k != "id"})
for e in data.get(ekey or "links", []):
G.add_edge(e.get("source"), e.get("target"),
**{k: v for k, v in e.items() if k not in ("source", "target")})
G.graph.update(data.get("graph", {}))
return G
G = load_graphify(GRAPH_JSON)
UG = G.to_undirected()
print(f"\nGraph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
def label(n):
return G.nodes[n].get("label", str(n))
We run Graphify locally on the generated application and extract the project knowledge graph without using any API key or LLM backend. We locate the generated graph.json file and load it into NetworkX using a version-proof node-link loader. We then convert the graph into an undirected form for easier structural analysis and define a helper function to display readable node labels.
Analyzing Centrality and Communities
Copy CodeCopiedUse a different Browser
from collections import Counter
ftypes = Counter(d.get("file_type", "?") for _, d in G.nodes(data=True))
rels = Counter(d.get("relation", "?") for *_ , d in G.edges(data=True))
conf = Counter(d.get("confidence", "?") for *_ , d in G.edges(data=True))
print("\nNodes by file_type :", dict(ftypes))
print("Edges by relation :", dict(rels))
print("Edges by confidence:", dict(conf))
deg = nx.degree_centrality(UG)
btw = nx.betweenness_centrality(UG)
print("\nTop 'god nodes' by degree centrality:")
for n, c in sorted(deg.items(), key=lambda x: -x[1])[:8]:
print(f" {label(n):<22} deg={c:.3f} betweenness={btw.get(n,0):.3f}")
try:
communities = nx.community.louvain_communities(UG, seed=42)
except Exception:
communities = list(nx.community.greedy_modularity_communities(UG))
node_comm = {n: i for i, com in enumerate(communities) for n in com}
print(f"\nDetected {len(communities)} communities:")
for i, com in enumerate(communities):
members = ", ".join(sorted(label(n) for n in com))[:90]
print(f" Community {i}: {members}")
def find(substr):
for n in G.nodes:
if substr.lower() in label(n).lower():
return n
return None
a, b = find("api"), find("DatabasePool")
if a and b and nx.has_path(UG, a, b):
path = nx.shortest_path(UG, a, b)
print(f"\nPath {label(a)} -> {label(b)}:")
print(" " + " → ".join(label(p) for p in path))
We analyze the extracted graph by summarizing node types, edge relationships, and confidence levels. We compute degree centrality and betweenness centrality to identify important “god nodes” that connect many parts of the application. We also detect communities in the graph and trace a shortest path between key components to understand how parts of the codebase are connected.
Visualizing the Code Graph
Copy CodeCopiedUse a different Browser
plt.figure(figsize=(13, 9))
pos = nx.spring_layout(UG, k=0.7, seed=42)
nx.draw_networkx_edges(UG, pos, alpha=0.25)
nx.draw_networkx_nodes(
UG, pos,
node_color=[node_comm.get(n, 0) for n in UG.nodes],
node_size=[300 + 4000 * deg.get(n, 0) for n in UG.nodes],
cmap=plt.cm.tab20, alpha=0.9,
)
top = {n for n, _ in sorted(deg.items(), key=lambda x: -x[1])[:14]}
nx.draw_networkx_labels(UG, pos, {n: label(n) for n in top}, font_size=8)
plt.title("Graphify knowledge graph — size=centrality, color=community")
plt.axis("off"); plt.tight_layout()
plt.savefig("graph_static.png", dpi=130); plt.show()
try:
from pyvis.network import Network
net = Network(height="650px", width="100%", bgcolor="#111", font_color="white",
notebook=True, cdn_resources="in_line", directed=G.is_directed())
palette = ["#e6194B","#3cb44b","#4363d8","#f58231","#911eb4",
"#42d4f4","#f032e6","#bfef45","#fabed4","#469990"]
for n, d in G.nodes(data=True):
c = node_comm.get(n, 0)
net.add_node(n, label=label(n), title=f"{d.get('file_type','?')} · {d.get('source_file','')}",
color=palette[c % len(palette)], size=12 + 60 * deg.get(n, 0))
for s, t, d in G.edges(data=True):
net.add_edge(s, t, title=d.get("relation", ""))
net.save_graph("graph_interactive.html")
print("\nSaved interactive graph -> graph_interactive.html")
from IPython.display import HTML, display
display(HTML(open("graph_interactive.html").read()))
except Exception as e:
print("Interactive viz skipped:", e)
for cmd in (
["query", "what connects auth to the database?", "--graph", GRAPH_JSON],
["path", "AuthService", "DatabasePool", "--graph", GRAPH_JSON],
["explain", "RateLimiter", "--graph", GRAPH_JSON],
):
print("\n$ graphify " + " ".join(cmd))
r = subprocess.run([sys.executable, "-m", "graphify", *cmd],
capture_output=True, text=True)
print((r.stdout or r.stderr)[:1200])
print("\nDone. Artifacts: graph_static.png, graph_interactive.html,",
"and graphify-out/ (graph.json, GRAPH_REPORT.md).")
We visualize the knowledge graph using both static and interactive methods. We first create a Matplotlib graph where node size represents centrality and node color represents community membership. We then build an interactive Pyvis visualization and run Graphify’s CLI commands to query the graph, find paths, and explain selected symbols.
Conclusion
In conclusion, we have a complete local pipeline for converting source code into a useful knowledge graph and studying it with graph analytics. We saw how Graphify extracts meaningful relationships from a Python and SQL codebase, and we use NetworkX to identify central “god nodes,” detect communities, and trace paths between components such as authentication and database logic. We also generated visual outputs that help us inspect the architecture from both a high-level and interactive perspective. This workflow gives us a pathway to reason about code structure, dependency flow, architectural hotspots, and cross-file connections without relying on external APIs, making it useful for codebase exploration, documentation, refactoring, and software architecture analysis.
Check out the Full Codes here. Also, feel free to follow us on Twitter and don’t forget to join our 150k+ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.
Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us
The post Using Graphify and NetworkX to Map Python Codebase Structure with God Nodes, Communities, and Architecture Visualizations appeared first on MarkTechPost.
関連記事
Salesforce CodeGen チュートリアル:ユニットテストと安全性チェック付きの Python 関数の生成・検証・再ランク付け
Salesforce は Hugging Face からモデルを読み込み、自然言語から Python 関数を生成するエンドツーエンドワークフローを公開した。この手法には構文チェックや静的解析、ユニットテストによる検証が含まれる。
LLM を活用したソースコードのセキュリティ強化
Eugene Yan は、大規模言語モデル(LLM)を適用することで、ソースコードの脆弱性を検出・防止する手法について解説している。
CodeQL 2.25.2がKotlin 2.3.20サポートとその他の更新を追加
GitHubが静的解析エンジンCodeQL 2.25.2をリリースし、Kotlin 2.3.20のサポート追加、精度向上、複数言語のセキュリティ深刻度スコア調整を実施した。
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み