mkdocs-nodegraph 0.1.0__py3-none-any.whl

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,3 @@
1
+ from mkdocs_nodegraph.plugin import GraphViewPlugin
2
+
3
+ __version__ = "0.1.0"
File without changes
@@ -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
+ }
File without changes