awacke1/PyVis-Knowledge-Graph-From-Markdown
1
1import streamlit as st2import streamlit.components.v1 as components3from pyvis.network import Network4import networkx as nx5import re6import emoji7 8st.title('Pyvis VisJS Knowledge Graph from Markdown')9 10# Make Network show itself with repr_html11def net_repr_html(self):12 nodes, edges, height, width, options = self.get_network_data()13 html = self.template.render(height=height, width=width, nodes=nodes, edges=edges, options=options)14 return html15 16Network._repr_html_ = net_repr_html17 18st.sidebar.title('Upload a Markdown File')19uploaded_file = st.sidebar.file_uploader("Choose a file", type=["md"])20 21physics = st.sidebar.checkbox('Add physics interactivity?')22 23def draw_knowledge_graph(file_contents, physics):24 # Extract sentences and emojis from the file25 sentences = re.split(r'\n', file_contents)26 emojis_list = [emoji.emojize(x) for x in emoji.UNICODE_EMOJI['en']]27 emojis = [ch for ch in file_contents if ch in emojis_list]28 29 # Create a graph30 G = nx.Graph()31 32 # Add nodes and edges33 for idx, sentence in enumerate(sentences):34 G.add_node(idx, label=sentence)35 words = set(sentence.lower().split())36 for j, other_sentence in enumerate(sentences[:idx]):37 other_words = set(other_sentence.lower().split())38 common_words = words & other_words39 common_emojis = set(emojis) & set(sentence) & set(other_sentence)40 if common_words: # or common_emojis41 G.add_edge(idx, j, weight=len(common_words) + len(common_emojis))42 43 # Visualize the graph44 net = Network(notebook=True)45 net.from_nx(G)46 net.toggle_physics(physics)47 48 return net._repr_html_()49 50if uploaded_file is not None:51 file_contents = uploaded_file.read().decode("utf-8")52 html = draw_knowledge_graph(file_contents, physics)53 components.html(html, height=1200, width=1000)54else:55 st.warning("Please upload a markdown file to visualize the knowledge graph.")56 