Spaces:
Build error
Build error
File size: 10,034 Bytes
c9a75fc d7e687c 121ffc2 c9a75fc 121ffc2 d7e687c 121ffc2 2293b42 121ffc2 2293b42 135bcee 2293b42 135bcee 2293b42 135bcee d7e687c 25dabdb 2293b42 25dabdb 2293b42 25dabdb 2293b42 25dabdb 2293b42 25dabdb d7e687c 2293b42 d7e687c 25dabdb d7e687c 2293b42 d7e687c 2293b42 d7e687c 2293b42 d7e687c 2293b42 d7e687c 2293b42 d7e687c 2293b42 7ddd13d 2293b42 135bcee 2293b42 135bcee 2293b42 5044d19 2293b42 5044d19 2293b42 7ddd13d 2293b42 d7e687c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | import streamlit as st
import asyncio
from typing import Dict, Any, Optional
from streamlit_agraph import agraph, Config
from src.network import make_payload, get_graph
from src.graph import build_tree_structure, create_hierarchical_view, tree_to_dot
def get_id_from_input(val: str) -> Optional[int]:
try:
return int(val)
except Exception:
return None
def display_tree_summary(graph: Dict[str, Any], root_id: int) -> None:
tree = build_tree_structure(graph, root_id)
if not tree:
return
max_depth = max(node["depth"] for node in tree.values()) if tree else 0
total_nodes = len(tree)
depth_counts: dict[int, int] = {}
for node in tree.values():
depth = node["depth"]
depth_counts[depth] = depth_counts.get(depth, 0) + 1
# display metrics in two columns to give more space
col1, col2 = st.columns(2)
with col1:
st.metric("Total Mathematicians", total_nodes)
st.metric("Generations Back", max_depth)
with col2:
root_name = tree.get(root_id, {}).get("name", "Unknown")
st.write("**Root Mathematician:**")
st.write(root_name)
def main():
st.title("Math Genealogy Ancestor Tree")
st.write("Interactive visualization of academic advisor relationships from the Mathematics Genealogy Project")
mathematicians = [
("Tristan Hearn", 162833),
("Alexander Grothendieck", 31245),
("Emmy Noether", 6967),
("David Hilbert", 7298),
("Sophie Germain", 55175),
("Carl Friedrich Gauss", 18231),
]
names = [f"{name} ({mid})" for name, mid in mathematicians]
default_index = 0 # Tristan Hearn
# initialize session state
if "mgp_id_str" not in st.session_state:
st.session_state["mgp_id_str"] = str(mathematicians[default_index][1])
if "graph_data" not in st.session_state:
st.session_state["graph_data"] = None
if "root_id" not in st.session_state:
st.session_state["root_id"] = None
# input section
st.subheader("Select Mathematician")
mgp_id_str = st.text_input(
"Enter MGP ID (integer):",
key="mgp_id_str",
help="You can type a custom ID or use the selection below."
)
def on_select():
st.session_state["mgp_id_str"] = str(mathematicians[st.session_state["mathematician_idx"]][1])
selected_idx = st.selectbox(
"Or select a mathematician:",
range(len(names)),
format_func=lambda i: names[i],
index=default_index,
key="mathematician_idx",
on_change=on_select,
)
progress_placeholder = st.empty()
# fetch data
run_btn = st.button("Fetch Ancestor Tree", type="primary")
if run_btn:
mgp_id = get_id_from_input(st.session_state["mgp_id_str"])
if mgp_id is None:
st.error("Please enter a valid integer MGP ID.")
return
payload = make_payload(mgp_id)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
def progress_cb(progress):
progress_placeholder.info(
f"Queued: {progress['queued']} | Fetching: {progress['fetching']} | Done: {progress['done']}"
)
async def runner():
graph = await get_graph(payload, progress_cb)
st.session_state["graph_data"] = graph
st.session_state["root_id"] = mgp_id
try:
loop.run_until_complete(runner())
progress_placeholder.success("Data fetched successfully!")
except Exception as e:
print(f"Error: {e}")
progress_placeholder.error(f"Error: {e}")
return
# display visualizations if data is available
if st.session_state["graph_data"] is not None:
graph = st.session_state["graph_data"]
root_id = st.session_state["root_id"]
# force sidebar open using JS injection
st.markdown(
"""
<script>
try {
window.parent.document.querySelector('section[data-testid="stSidebar"]').style.transform = "none";
} catch (e) {}
</script>
""",
unsafe_allow_html=True,
)
# sidebar timeline table
import pandas as pd
nodes = graph.get("nodes", {})
data = []
for node_id, node in nodes.items():
name = node.get("name", "")
year = node.get("year", None)
institution = node.get("institution", "")
# try to convert year to int for sorting, else None
try:
year_int = int(year)
except Exception:
year_int = None
data.append({"Name": name, "Year": year_int, "Institution": institution, "node_id": node_id})
df = pd.DataFrame(data)
df = df.dropna(subset=["Year"])
df = df.sort_values("Year", ascending=False)
st.sidebar.title("Timeline")
st.sidebar.dataframe(
df[["Year", "Name", "Institution"]],
use_container_width=True,
height=1000
)
st.divider()
# show summary
display_tree_summary(graph, root_id)
st.divider()
# export to pdf button
import io
from graphviz import Source
dot = tree_to_dot(graph)
pdf_bytes = None
try:
src = Source(dot)
pdf_bytes = src.pipe(format="pdf")
except Exception as e:
st.warning(f"Could not generate PDF: {e}")
if pdf_bytes:
st.download_button(
label="Download Graph as PDF",
data=pdf_bytes,
file_name="math_genealogy_tree.pdf",
mime="application/pdf"
)
# visualization options
st.subheader("Choose Visualization")
viz_option = st.radio(
"Select visualization type:",
["Interactive Hierarchical Tree", "Traditional Graph (Graphviz)"],
help="Different views for exploring the genealogy tree"
)
if viz_option == "Interactive Hierarchical Tree":
st.write("**Hierarchical Tree View** - Best for exploring direct lineages")
# depth filter
tree = build_tree_structure(graph, root_id)
max_available_depth = max(node["depth"] for node in tree.values()) if tree else 0
if max_available_depth > 0:
depth_filter = st.slider(
"Show generations back:",
min_value=0,
max_value=max_available_depth,
value=min(3, max_available_depth),
help="Limit the number of generations to display for better readability"
)
else:
depth_filter = 0
# create hierarchical view
nodes_list, edges_list = create_hierarchical_view(graph, root_id, depth_filter)
if nodes_list:
# configure for better dark mode compatibility
config = Config(
width=800,
height=600,
directed=True,
physics=True,
hierarchical=True,
nodeHighlightBehavior=True,
highlightColor="#F7A7A6",
collapsible=False,
# dark mode friendly settings
node={
"font": {
"color": "black", # ensure text is always black for readability
"size": 12,
"face": "arial"
},
"borderWidth": 2,
"borderWidthSelected": 3
}
)
selected = agraph(nodes=nodes_list, edges=edges_list, config=config)
selected_node_id = None
if selected and "id" in selected:
selected_node_id = selected["id"]
st.session_state["selected_node_id"] = selected_node_id
# debug output
if selected_node_id:
st.write(f"DEBUG: Selected node ID: {selected_node_id}")
else:
st.warning("No data to display with current filters.")
else: # Traditional Graph
st.write("**Traditional Graph View** - Standard graphviz layout")
st.graphviz_chart(dot)
# search functionality
st.divider()
st.subheader("Search Mathematicians")
nodes = graph.get("nodes", {})
search_term = st.text_input("Search by name:", placeholder="e.g., Gauss, Euler, Newton")
if search_term:
matches = []
for node_id, node in nodes.items():
name = node.get("name", "")
if search_term.lower() in name.lower():
year = node.get("year", "N/A")
institution = node.get("institution", "N/A")
matches.append({
"id": node_id,
"name": name,
"year": year,
"institution": institution
})
if matches:
st.write(f"Found {len(matches)} match(es):")
for match in matches[:10]: # limit to 10 results
st.write(f"• **{match['name']}** ({match['year']}) - {match['institution']} (ID: {match['id']})")
if len(matches) > 10:
st.write(f"... and {len(matches) - 10} more")
else:
st.write("No matches found.")
if __name__ == "__main__":
main()
|