Demo-Revision-App / revision-app-streamlit3.py
shikharyashmaurya's picture
Upload revision-app-streamlit3.py
aa7ea9c verified
raw
history blame
8.1 kB
import streamlit as st
import json
import os
import networkx as nx
import matplotlib.pyplot as plt
import textwrap
from io import BytesIO
FILENAME = "nested_dictionary.json"
class RevisionApp:
def __init__(self):
self.load_data()
self.create_ui()
def load_data(self):
if 'data' not in st.session_state:
if os.path.exists(FILENAME):
with open(FILENAME, 'r') as file:
st.session_state.data = json.load(file)
else:
st.session_state.data = {}
def save_data(self):
with open(FILENAME, 'w') as file:
json.dump(st.session_state.data, file, indent=2)
def create_ui(self):
st.title("Concept Revision App")
st.write('''Demo app don't have functionality like unlimited tree view expand, touch,expand,export map.
No session history - after session your input information will be lost
.For full functionality see -
https://github.com/shikharyashmaurya/Revision-App''')
# Sidebar for navigation
page = st.sidebar.selectbox("Choose a page", ["Tree View", "Mind Map", "Search"])
if page == "Tree View":
self.show_tree_view()
elif page == "Mind Map":
self.show_mind_map()
elif page == "Search":
self.show_search()
def show_tree_view(self):
st.header("Tree View")
# Input for new concept
new_key = st.text_input("Enter a new concept:")
if st.button("Add Concept"):
if new_key and new_key not in st.session_state.data:
st.session_state.data[new_key] = {'next': [], 'text': []}
self.save_data()
st.success(f"Added new concept: {new_key}")
st.experimental_rerun()
# Display concepts
selected_concept = st.selectbox("Select a concept to view details:",
options=[""] + list(st.session_state.data.keys()))
if selected_concept:
self.show_concept_details(selected_concept)
def show_concept_details(self, key):
st.subheader(f"Concept: {key}")
# Display related concepts
st.write("Related Concepts:")
for next_item in st.session_state.data[key]['next']:
if st.button(f"Go to {next_item}", key=f"goto_{next_item}"):
self.show_concept_details(next_item)
return
# Add related concept
new_related = st.text_input(f"Add related concept to {key}:", key=f"related_{key}")
if st.button(f"Add related to {key}", key=f"add_related_{key}"):
if new_related and new_related not in st.session_state.data[key]['next']:
if new_related not in st.session_state.data:
st.session_state.data[new_related] = {'next': [], 'text': []}
st.session_state.data[key]['next'].append(new_related)
self.save_data()
st.success(f"Added {new_related} as related to {key}")
st.experimental_rerun()
# Display information
st.write("Information:")
for i, text_item in enumerate(st.session_state.data[key]['text']):
st.text_area(f"Info {i+1}", value=text_item, key=f"info_{key}_{i}", height=100, disabled=True)
# Add information
new_info = st.text_area(f"Add information to {key}:", key=f"new_info_{key}")
if st.button(f"Add info to {key}", key=f"add_info_{key}"):
if new_info:
st.session_state.data[key]['text'].append(new_info)
self.save_data()
st.success(f"Added new information to {key}")
st.experimental_rerun()
def show_mind_map(self):
st.header("Mind Map")
G = nx.Graph()
for key, value in st.session_state.data.items():
G.add_node(key)
for next_item in value['next']:
if next_item in st.session_state.data:
G.add_edge(key, next_item)
pos = self.custom_tree_layout(G)
plt.figure(figsize=(12, 8))
nx.draw(G, pos, with_labels=False, node_color='lightblue', node_size=3000, alpha=0.8)
for node, (x, y) in pos.items():
lines = textwrap.wrap(node, width=10)
plt.annotate('\n'.join(lines), (x, y), horizontalalignment='center', verticalalignment='center')
plt.axis('off')
# Save plot to a buffer
buf = BytesIO()
plt.savefig(buf, format="png")
buf.seek(0)
# Display the image
st.image(buf, caption='Mind Map', use_column_width=True)
def show_search(self):
st.header("Search")
query = st.text_input("Enter search term:")
if st.button("Search"):
results = self.search_data(query)
if results:
for key in results:
with st.expander(f"Concept: {key}"):
st.write("Related Concepts:")
for related in st.session_state.data[key]['next']:
st.write(f"- {related}")
st.write("Information:")
for info in st.session_state.data[key]['text']:
st.write(f"- {info}")
else:
st.write("No results found.")
def search_data(self, query):
query = query.lower()
results = set()
for key, value in st.session_state.data.items():
if query in key.lower():
results.add(key)
for next_item in value['next']:
if query in next_item.lower():
results.add(key)
for text_item in value['text']:
if query in text_item.lower():
results.add(key)
return list(results)
# def custom_tree_layout(self, G):
# # ... (custom_tree_layout method remains unchanged)
# pass
def custom_tree_layout(self, G):
if not G.nodes():
return {}
def bfs_tree(root):
tree = nx.bfs_tree(G, root)
return tree
def assign_positions(tree, root):
pos = {}
level_width = {}
max_depth = 0
def dfs(node, depth, order):
nonlocal max_depth
max_depth = max(max_depth, depth)
if depth not in level_width:
level_width[depth] = 0
level_width[depth] += 1
children = list(tree.successors(node))
if not children:
pos[node] = (order, -depth)
return order + 1
start = order
for child in children:
order = dfs(child, depth + 1, order)
pos[node] = (start + (order - start - 1) / 2, -depth)
return order
dfs(root, 0, 0)
# Normalize positions
max_width = max(level_width.values()) if level_width else 1
for node in pos:
x, y = pos[node]
pos[node] = (x / max_width, y / max_depth if max_depth != 0 else 0)
return pos
# Handle disconnected components
components = list(nx.connected_components(G))
if not components:
return {}
pos = {}
y_offset = 0
for component in components:
subgraph = G.subgraph(component)
root = max(subgraph.nodes(), key=lambda n: subgraph.degree(n))
tree = bfs_tree(root)
component_pos = assign_positions(tree, root)
# Adjust y-positions for each component
for node, (x, y) in component_pos.items():
pos[node] = (x, y + y_offset)
y_offset -= 1.5 # Increase vertical separation between components
return pos
if __name__ == "__main__":
app = RevisionApp()