Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import streamlit.components.v1 as components
|
3 |
+
from pyvis.network import Network
|
4 |
+
import networkx as nx
|
5 |
+
import re
|
6 |
+
import emoji
|
7 |
+
|
8 |
+
st.title('Pyvis VisJS Knowledge Graph from Markdown')
|
9 |
+
|
10 |
+
# Make Network show itself with repr_html
|
11 |
+
def 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 html
|
15 |
+
|
16 |
+
Network._repr_html_ = net_repr_html
|
17 |
+
|
18 |
+
st.sidebar.title('Upload a Markdown File')
|
19 |
+
uploaded_file = st.sidebar.file_uploader("Choose a file", type=["md"])
|
20 |
+
|
21 |
+
physics = st.sidebar.checkbox('Add physics interactivity?')
|
22 |
+
|
23 |
+
def draw_knowledge_graph(file_contents, physics):
|
24 |
+
# Extract sentences and emojis from the file
|
25 |
+
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 graph
|
30 |
+
G = nx.Graph()
|
31 |
+
|
32 |
+
# Add nodes and edges
|
33 |
+
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_words
|
39 |
+
common_emojis = set(emojis) & set(sentence) & set(other_sentence)
|
40 |
+
if common_words or common_emojis:
|
41 |
+
G.add_edge(idx, j, weight=len(common_words) + len(common_emojis))
|
42 |
+
|
43 |
+
# Visualize the graph
|
44 |
+
net = Network(notebook=True)
|
45 |
+
net.from_nx(G)
|
46 |
+
net.toggle_physics(physics)
|
47 |
+
|
48 |
+
return net._repr_html_()
|
49 |
+
|
50 |
+
if 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)
|
54 |
+
else:
|
55 |
+
st.warning("Please upload a markdown file to visualize the knowledge graph.")
|