mkdocs-nodegraph 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-2025 JeongYong Hwang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.1
2
+ Name: mkdocs-nodegraph
3
+ Version: 0.1.0
4
+ Summary: MkDocs plugin supports nodegraph
5
+ Home-page:
6
+ Author: JeongYong Hwang
7
+ Author-email: yonge123@gmail.com
8
+ License: MIT
9
+ Keywords: mkdocs,plugin,nodegraph
10
+ Requires-Dist: mkdocs>=1.4.0
11
+ Requires-Dist: mkdocs-material>=9.5.31
12
+ Requires-Dist: pyembed-markdown>=1.1.0
13
+ Requires-Dist: mkdocs-glightbox>=0.4.0
14
+ Requires-Dist: pyvis>=0.3.0
15
+ Requires-Dist: PyYAML>=6.0.2
@@ -0,0 +1,119 @@
1
+ # mkdocs-nodegraph
2
+
3
+ mkdocs-nodegraph - A Plugin for Visualizing Network Graphs in MkDocs
4
+
5
+ ## Summary
6
+
7
+ mkdocs-nodegraph is a documents network graph visualization plugin for the mkdocs-material.
8
+
9
+ It allows you to create interactive visualizations of your documentation structure, helping users navigate through topics more easily.
10
+
11
+
12
+ ## Example
13
+
14
+
15
+ ![Example Network Graph Visualization](./sources/example_image_001.png)
16
+
17
+ <br>
18
+
19
+ YouTube Link
20
+
21
+ - https://www.youtube.com/watch?v=KD1AsW304kc
22
+
23
+
24
+ <iframe width="800" height="550" src="https://www.youtube.com/embed/KD1AsW304kc" title="mkdocs nodegraph 002" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
25
+
26
+
27
+ <br>
28
+
29
+ ## Install
30
+
31
+
32
+ ```shell
33
+
34
+ python.exe setup.py install
35
+
36
+ ```
37
+
38
+ <br>
39
+
40
+
41
+ ## Setup Tags, Node Icon and Color on Markdown Files
42
+
43
+ ```md
44
+
45
+ ---
46
+ tags:
47
+ - CG
48
+ - 3D software
49
+ mdfile_icon: "_sources/svgs/blender.svg"
50
+ mdfile_color: "#ea7600"
51
+ ---
52
+
53
+ ```
54
+
55
+
56
+ <br>
57
+
58
+ ## mkdocs.yml Configuration
59
+
60
+
61
+ ```yml
62
+
63
+ theme:
64
+ # pip install mkdocs-material
65
+ name: material
66
+ # name: readthedocs
67
+ features:
68
+ # - navigation.tabs
69
+ - content.code.copy
70
+ palette:
71
+ # Palette toggle for dark mode
72
+ - media: "(prefers-color-scheme: dark)"
73
+ scheme: slate
74
+ primary: blue
75
+ accent: blue
76
+ toggle:
77
+ icon: material/brightness-7
78
+ name: Switch to light mode
79
+ # Palette toggle for light mode
80
+ - media: "(prefers-color-scheme: light)"
81
+ scheme: default
82
+ primary: blue
83
+ accent: blue
84
+ toggle:
85
+ icon: material/brightness-4
86
+ name: Switch to dark mode
87
+
88
+ plugins:
89
+ - search
90
+ - offline
91
+ - glightbox:
92
+ skip_classes:
93
+ - collapse-btn
94
+ - nodegraph:
95
+ graphfile: "nodegraph.html"
96
+
97
+ ```
98
+
99
+ <br>
100
+
101
+ After setting up the nodegraph plugin with its graphfile path, you can build your site
102
+
103
+ ```shell
104
+ mkdocs build
105
+ ```
106
+
107
+ <br>
108
+
109
+ After building the site, you can click the button ![](./sources/graph_icon.svg) to open the graph file.
110
+
111
+ <br>
112
+
113
+
114
+ ## References
115
+
116
+ - https://github.com/barrettotte/md-graph?tab=readme-ov-file
117
+ - https://pyvis.readthedocs.io/en/latest/
118
+
119
+ <br>
@@ -0,0 +1,3 @@
1
+ from mkdocs_nodegraph.plugin import GraphViewPlugin
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,341 @@
1
+ import os, json
2
+ from .mdparser import MdParser
3
+ import networkx as nx
4
+ from pyvis.network import Network
5
+ import copy
6
+ import os
7
+ import re
8
+
9
+
10
+ beautifulcolors = [
11
+ "#E9967A",
12
+ "#00CED1",
13
+ "#90EE90",
14
+ "#CD5C5C",
15
+ "#FF1493",
16
+ "#32CD32",
17
+ "#FF00FF",
18
+ "#4682B4",
19
+ "#DA70D6",
20
+ "#FFD700",
21
+ "#C71585",
22
+ "#FFDAB9",
23
+ "#20B2AA",
24
+ "#FF69B4",
25
+ "#DAA520",
26
+ "#48D1CC",
27
+ "#F0E68C",
28
+ "#9400D3",
29
+ "#FF7F50",
30
+ "#8B008B",
31
+ "#98FB98",
32
+ "#DDA0DD",
33
+ "#6495ED",
34
+ "#4169E1",
35
+ "#87CEEB",
36
+ "#800080",
37
+ "#FFA500",
38
+ "#8E44AD",
39
+ "#9370DB",
40
+ "#3CB371",
41
+ "#8A2BE2",
42
+ "#66CDAA",
43
+ "#9932CC",
44
+ "#BA55D3",
45
+ "#4ECDC4",
46
+ "#8FBC8F",
47
+ "#5F9EA0",
48
+ "#45B7D1",
49
+ "#FA8072",
50
+ "#00FA9A",
51
+ "#F4A460",
52
+ "#6A5ACD",
53
+ "#D2691E",
54
+ "#7B68EE",
55
+ "#40E0D0",
56
+ "#F08080",
57
+ "#B0C4DE",
58
+ "#FF6B6B",
59
+ "#1E90FF",
60
+ "#FF4500",
61
+ "#FFB6C1",
62
+ "#FFA07A",
63
+ "#87CEFA",
64
+ ]
65
+
66
+
67
+ def set_edge_color_by_dominant_node(net, nx_graph):
68
+ """
69
+ Color each edge based on the color of its most connected node
70
+ """
71
+ # assign node color to font colorS
72
+ for node_id in nx_graph.nodes():
73
+ degree = nx_graph.degree(node_id)
74
+ color = net.get_node(node_id)['color']
75
+ net.get_node(node_id)['font']['color'] = color
76
+
77
+ # Count connections for each node
78
+ node_connections = {}
79
+ for node in nx_graph.nodes():
80
+ node_connections[node] = len(list(nx_graph.neighbors(node)))
81
+
82
+ # For each edge, get its linked nodes and color based on the node with more connections
83
+ for i, edge in enumerate(net.edges):
84
+ from_node = edge['from']
85
+ to_node = edge['to']
86
+
87
+ # Determine which node has more connections
88
+ if node_connections[from_node] >= node_connections[to_node]:
89
+ node_with_more_connections = from_node
90
+ else:
91
+ node_with_more_connections = to_node
92
+
93
+ # Find this node in the PyVis nodes list to get its color
94
+ for node in net.nodes:
95
+ if node['id'] == node_with_more_connections:
96
+ node_color = node['color']
97
+ break
98
+
99
+ # Set the edge color
100
+ net.edges[i]['color'] = node_color
101
+
102
+
103
+ class GraphOptions():
104
+ def __init__(self, width, height, heading, bgcolor, font_color):
105
+ self.width = width
106
+ self.height = height
107
+ self.heading = heading
108
+ self.bgcolor = bgcolor
109
+ self.font_color = font_color
110
+
111
+
112
+ class GraphBuilder():
113
+ def __init__(self, pyvis_opts, graph_opts, graph_out, config_graphfile, docs_dir, site_dir):
114
+ self.pyvis_opts = pyvis_opts # js variable as raw string
115
+ self.graph_opts = graph_opts # GraphOptions obj
116
+ self.graph_out = graph_out # output path for graph as HTML
117
+ self.config_graphfile = config_graphfile
118
+ self.docsdir = docs_dir
119
+ self.site_dir = site_dir
120
+ self.net = Network(width=graph_opts.width, height=graph_opts.height,
121
+ heading=graph_opts.heading, bgcolor=graph_opts.bgcolor,
122
+ font_color=graph_opts.font_color,
123
+ # select_menu=True,
124
+ # filter_menu=True
125
+ )
126
+ template_dir = os.path.dirname(__file__) + "/templates/"
127
+ self.net.set_template_dir(template_dir)
128
+ self.net.set_template = template_dir + "/template.html"
129
+
130
+ self.net.set_options(self.pyvis_opts)
131
+
132
+ # self.net.show_buttons(filter_=['physics', 'nodes', 'links'])
133
+ # build graph from parsed markdown pages
134
+ def build(self, mdfiles):
135
+ nx_graph = nx.Graph()
136
+ edget_info_dic = dict()
137
+ color_list = copy.deepcopy(beautifulcolors)
138
+
139
+ data_dic = dict()
140
+ for mdfile in mdfiles:
141
+ if mdfile.uid not in data_dic:
142
+ data_dic[mdfile.uid] = set()
143
+
144
+ for link_uid in mdfile.link_uids:
145
+ if link_uid not in data_dic:
146
+ data_dic[link_uid] = set()
147
+
148
+ data_dic[mdfile.uid].add(link_uid)
149
+ data_dic[link_uid].add(mdfile.uid)
150
+
151
+ config_graphfile = self.config_graphfile.replace("\\", "/") if "\\" in self.config_graphfile else self.config_graphfile
152
+ level_count = config_graphfile.count('/')
153
+ icon_prefix = ""
154
+ if level_count:
155
+ icon_prefix = (level_count*"../")
156
+
157
+ for mdfile in mdfiles:
158
+ if not color_list:
159
+ color_list = copy.deepcopy(beautifulcolors)
160
+
161
+ docsdir = self.docsdir.replace("\\", "/") + "/"
162
+ site_folder_name = os.path.basename(self.site_dir)
163
+ filepath = mdfile.file_path.replace("\\", "/")
164
+ prefix = filepath.replace(docsdir.replace("\\", "/"), "")
165
+ html = prefix.replace(".md", ".html")
166
+ html = icon_prefix + html
167
+
168
+ icon = ""
169
+ color = ""
170
+ shape="dot"
171
+
172
+ metadata = mdfile.metadata
173
+ if metadata:
174
+ if "mdfile_icon" in metadata:
175
+ # variable relative path ../_source/svgs/blender.svg
176
+ icon = icon_prefix + metadata["mdfile_icon"]
177
+ if "mdfile_color" in metadata:
178
+ color = metadata["mdfile_color"]
179
+
180
+ if icon:
181
+ shape="image"
182
+
183
+ if not color:
184
+ color = color_list.pop(0)
185
+ count_links = len(mdfile.link_uids)
186
+ if count_links <= 1:
187
+ color = "#9CA3AF"
188
+
189
+ size = 50 + (count_links * 4)
190
+ if size > 120:
191
+ size = 120
192
+ nx_graph.add_node(mdfile.uid,
193
+ label=mdfile.title,
194
+ url=html,
195
+ size=size,
196
+ shape=shape,
197
+ image=icon,
198
+ color=color,
199
+ opacity=1,
200
+ borderWidth=2,
201
+ )
202
+
203
+ for idx, link_uid in enumerate(mdfile.link_uids):
204
+ if mdfile.uid in data_dic:
205
+ max_link = len(data_dic[mdfile.uid])
206
+ if link_uid in data_dic:
207
+ if max_link < len(data_dic[link_uid]):
208
+ max_link = len(data_dic[link_uid])
209
+ edge_len = max_link * 45 + ( idx * 35)
210
+ nx_graph.add_edge(mdfile.uid, link_uid, length=edge_len)
211
+
212
+ # self.net.from_nx(nx_graph)
213
+ self.net.from_nx(nx_graph,
214
+ default_node_size=50,
215
+ default_edge_weight=12)
216
+
217
+ # assign node color to font colorS
218
+ for node_id in nx_graph.nodes():
219
+ degree = nx_graph.degree(node_id)
220
+ color = self.net.get_node(node_id)['color']
221
+ self.net.get_node(node_id)['font']['color'] = color
222
+
223
+ set_edge_color_by_dominant_node(self.net, nx_graph)
224
+
225
+ # save network graph as HTML
226
+ self.net.save_graph(self.graph_out)
227
+
228
+
229
+ def read_config(file_path):
230
+ try:
231
+ with open(file_path, 'r') as f:
232
+ return json.load(f)
233
+ except Exception as e:
234
+ raise IOError(f'Failed to read file -> "{file_path}"')
235
+
236
+
237
+ def load_graph_opts(config):
238
+ return GraphOptions(config['width'], config['height'], config['heading'],
239
+ config['bgcolor'], config['font_color'] )
240
+
241
+
242
+ def load_pyvis_opts(file_path):
243
+ with open(file_path, 'r') as fout:
244
+ return fout.read()
245
+
246
+
247
+ def build_graph(docs_dir, site_dir, output_file, pyvis_opts_file, graph_opts_file, config_graphfile):
248
+ if not os.path.isfile(pyvis_opts_file):
249
+ raise IOError(f'Failed to find file -> "{pyvis_opts_file}"')
250
+
251
+ if not os.path.isfile(graph_opts_file):
252
+ raise IOError(f'Failed to find file -> "{graph_opts_file}"')
253
+
254
+ outputDir = os.path.dirname(output_file)
255
+ os.makedirs(outputDir, exist_ok=True)
256
+
257
+ parser = MdParser(docs_dir)
258
+ mdfiles = parser.parse()
259
+
260
+ graph_config = read_config(graph_opts_file)
261
+ graph_opts = load_graph_opts(graph_config)
262
+ pyvis_opts = load_pyvis_opts(pyvis_opts_file)
263
+
264
+ builder = GraphBuilder(pyvis_opts, graph_opts, output_file, config_graphfile, docs_dir, site_dir)
265
+ builder.build(mdfiles)
266
+
267
+
268
+ def rebuild_graph_html(index_path, graph_path, output_path=None):
269
+ """
270
+ Extracts head and body content from graph.html and replaces the content
271
+ of the article tag with class 'md-content__inner md-typeset' in index.html.
272
+ Also adds a custom script at the end of the body.
273
+
274
+ Args:
275
+ index_path (str): Path to index.html file
276
+ graph_path (str): Path to graph.html file
277
+ output_path (str, optional): Path to save the merged file. If None, overwrites index.html
278
+ """
279
+ # Read the HTML files
280
+ with open(index_path, 'r', encoding='utf-8') as f:
281
+ index_content = f.read()
282
+
283
+ with open(graph_path, 'r', encoding='utf-8') as f:
284
+ graph_content = f.read()
285
+
286
+ # Find and extract article content
287
+ article_pattern = r'<article class="md-content__inner md-typeset">.*?</article>'
288
+ article_match = re.search(article_pattern, index_content, re.DOTALL)
289
+
290
+ if not article_match:
291
+ raise ValueError("Could not find article with class 'md-content__inner md-typeset' in index.html")
292
+
293
+ # Extract head and body from graph_content
294
+ head_content = ""
295
+ body_content = ""
296
+
297
+ head_match = re.search(r'<head>.*?</head>', graph_content, re.DOTALL)
298
+ if head_match:
299
+ head_content = head_match.group(0)
300
+
301
+ body_match = re.search(r'<body>.*?</body>', graph_content, re.DOTALL)
302
+ if body_match:
303
+ body_content = body_match.group(0)
304
+
305
+ # Create new article content
306
+ new_article_content = f'<article class="md-content__inner md-typeset">{head_content}{body_content}</article>'
307
+
308
+ # Replace the article content
309
+ modified_content = index_content.replace(article_match.group(0), new_article_content)
310
+
311
+ # Define the custom script to add at the end of the body
312
+ custom_script = """
313
+ <script>
314
+ document.addEventListener('DOMContentLoaded', function() {
315
+ const footerMetas = document.querySelectorAll('.md-footer-meta.md-typeset');
316
+ footerMetas.forEach(function(element) {
317
+ element.remove();
318
+ });
319
+
320
+ document.querySelector('.md-typeset').style.fontSize = '0px';
321
+ document.querySelector('.md-typeset').style.margin = '0px';
322
+ });
323
+ var right_sidebar = document.getElementsByClassName('md-sidebar md-sidebar--secondary');
324
+ if (right_sidebar.length > 0) {
325
+ right_sidebar[0].style.width = '0px';
326
+ }
327
+
328
+ </script>
329
+ """
330
+
331
+ # Add script before closing body tag
332
+ modified_content = modified_content.replace('</body>', f'{custom_script}</body>')
333
+
334
+ # Save the merged HTML
335
+ if output_path is None:
336
+ output_path = index_path
337
+
338
+ with open(output_path, 'w', encoding='utf-8') as f:
339
+ f.write(modified_content)
340
+
341
+ print(f"Successfully replaced article content in {index_path} with content from {graph_path}, added custom script, and saved to {output_path}")
@@ -0,0 +1,7 @@
1
+ {
2
+ "width": "100%",
3
+ "height": "1400px",
4
+ "heading": "",
5
+ "bgcolor": "#222222",
6
+ "font_color": "#94A3B8"
7
+ }
@@ -0,0 +1,14 @@
1
+
2
+
3
+ class MdFile():
4
+ def __init__(self, file_path, base_name, title, mdlinks, link_uids, metadata=""):
5
+ self.uid = 0
6
+ self.file_path = file_path
7
+ self.base_name = base_name
8
+ self.title = title if title else base_name
9
+ self.mdlinks = mdlinks
10
+ self.link_uids = link_uids
11
+ self.metadata = metadata
12
+
13
+ def __str__(self):
14
+ return f'{self.uid}: {self.file_path}, {self.title}, {self.mdlinks}, {self.metadata}'
@@ -0,0 +1,95 @@
1
+ import os, re, yaml
2
+ from .mdfile import MdFile
3
+
4
+ INLINE_LINK_RE = re.compile(r'\[([^\]]+)\]\(([^)]+\.md)\)')
5
+ FOOTNOTE_LINK_TEXT_RE = re.compile(r'\[([^\]]+)\]\[(\d+)\]')
6
+ FOOTNOTE_LINK_URL_RE = re.compile(r'\[(\d+)\]:\s+(\S+)')
7
+
8
+
9
+ def find_md_links(md):
10
+ """ Return dict of links in markdown """
11
+ links = dict(INLINE_LINK_RE.findall(md))
12
+ footnote_links = dict(FOOTNOTE_LINK_TEXT_RE.findall(md))
13
+ footnote_urls = dict(FOOTNOTE_LINK_URL_RE.findall(md))
14
+
15
+ for key, value in footnote_links.items():
16
+ footnote_links[key] = footnote_urls[value]
17
+ links.update(footnote_links)
18
+
19
+ return links
20
+
21
+
22
+ def iterMarkdownLink(mdfile):
23
+ with open(mdfile, 'r', encoding="UTF-8") as fin:
24
+ read = fin.read()
25
+ links = find_md_links(read)
26
+ for label, url in links.items():
27
+ yield url
28
+
29
+
30
+ def getMetadata(mdfile):
31
+ metadata = ""
32
+ count = 0
33
+ with open(mdfile, 'r', encoding="UTF-8") as fin:
34
+ for line in fin.readlines():
35
+
36
+ if count >= 2:
37
+ break
38
+
39
+ if line.strip().startswith('#'):
40
+ break
41
+
42
+ if line.strip() == "---":
43
+ count += 1
44
+ else:
45
+ if count >= 1:
46
+ metadata += line
47
+
48
+ return metadata
49
+
50
+
51
+ class MdParser():
52
+
53
+ def __init__(self, target_dir):
54
+ self.mdfiles = []
55
+ self.target_dir = target_dir
56
+
57
+ def parse_md(self, file_name):
58
+ base_name = os.path.basename(file_name)
59
+ links = list(iterMarkdownLink(file_name))
60
+ link_uids = list()
61
+ title = ""
62
+ metadata = ""
63
+ return MdFile(file_name, base_name, title, links, link_uids, metadata)
64
+
65
+ def parse(self):
66
+ uid = 1
67
+ for subdir, dirs, files in os.walk(self.target_dir):
68
+ for f in files:
69
+ if f.endswith('md'):
70
+ path = os.path.join(subdir, f)
71
+
72
+ if not any(x for x in self.mdfiles if x.file_path == path):
73
+ md = self.parse_md(path)
74
+ parseMedata = getMetadata(path)
75
+ if parseMedata:
76
+ metadata = yaml.safe_load(parseMedata)
77
+ md.metadata = metadata
78
+
79
+ md.uid = uid
80
+ uid += 1
81
+ self.mdfiles.append(md)
82
+
83
+ for mdfile in self.mdfiles:
84
+ uids = set()
85
+
86
+ for link in mdfile.mdlinks:
87
+ link_basename = os.path.basename(link)
88
+ link_new = link.replace("../", "/").replace("./", "").replace("/", "").replace(".", "")
89
+ uid = list(filter(lambda x: (x.file_path.replace("\\", "").replace("../", "/").replace("./", "").replace("/", "").replace(".", "").endswith(link_new) and os.path.basename(x.file_path) == link_basename), self.mdfiles))
90
+ if len(uid) > 0:
91
+ uids.add(uid[0].uid)
92
+
93
+ mdfile.link_uids = list(uids)
94
+
95
+ return self.mdfiles
@@ -0,0 +1,37 @@
1
+ var options = {
2
+ "nodes": {
3
+ "font": {
4
+ "size": 70,
5
+ "align": "middle"
6
+ },
7
+ "scaling": {
8
+ "min": 70,
9
+ "max": 120
10
+ },
11
+ "borderWidth": 0,
12
+ "size": 100
13
+ },
14
+ "edges": {
15
+ "color": {
16
+ "inherit": true
17
+ },
18
+ "smooth": false
19
+ },
20
+ "physics": {
21
+ "stabilization": {
22
+ "enabled": false
23
+ },
24
+ "forceAtlas2Based": {
25
+ "theta": 0.5,
26
+ "gravitationalConstant": -1100,
27
+ "centralGravity": 0.009,
28
+ "springConstant": 0.08,
29
+ "springLength": 600,
30
+ "damping": 0.2,
31
+ "avoidOverlap": 0
32
+ },
33
+ "solver": "forceAtlas2Based",
34
+ "minVelocity": 0.75,
35
+ "timestep": 0.50
36
+ }
37
+ }