donb-hf commited on
Commit
f7c75a5
Β·
verified Β·
1 Parent(s): f6bf57c

remove plotly

Browse files
Files changed (1) hide show
  1. app.py +54 -112
app.py CHANGED
@@ -1,15 +1,16 @@
1
- import networkx as nx
2
- import plotly.graph_objs as go
3
- from plotly.subplots import make_subplots
4
- from typing import Dict, Tuple, List, Any
5
  import gradio as gr
6
- import plotly.io as pio
 
 
 
 
 
7
 
8
  # Initialize the lesson plan graph as a directed graph
9
- lesson_graph: nx.DiGraph = nx.DiGraph()
10
 
11
  # Define color map for node types
12
- color_map: Dict[str, str] = {
13
  "User": "#FF9999", # Light Red
14
  "Subject": "#66B2FF", # Light Blue
15
  "Grade Level": "#99FF99", # Light Green
@@ -20,16 +21,7 @@ color_map: Dict[str, str] = {
20
  "School Board": "#CCCCCC" # Light Gray
21
  }
22
 
23
- def add_to_graph(
24
- teacher_name: str,
25
- subject: str,
26
- grade_level: str,
27
- learning_objective: str,
28
- activity: str,
29
- assessment: str,
30
- resource: str,
31
- school_board: str
32
- ) -> Tuple[str, go.Figure]:
33
  global lesson_graph
34
 
35
  # Clear previous graph
@@ -56,102 +48,53 @@ def add_to_graph(
56
  lesson_graph.add_edge(learning_objective, school_board, relationship="ALIGNS_WITH")
57
 
58
  # Generate search string
59
- search_string: str = f"{subject} {grade_level} {learning_objective} {activity} {resource}".strip()
60
 
61
- # Create Plotly graph
62
- fig: go.Figure = create_plotly_graph(lesson_graph)
 
63
 
64
- return search_string, fig
65
-
66
- def create_plotly_graph(graph: nx.DiGraph) -> go.Figure:
67
- pos: Dict[Any, Tuple[float, float]] = nx.spring_layout(graph, seed=42) # Adding seed for consistent layout
68
 
69
- # Edge trace initialization with descriptive labels
70
- edge_x, edge_y = [], []
71
- edge_text = []
72
-
73
- for edge in graph.edges(data=True):
74
- x0, y0 = pos[edge[0]]
75
- x1, y1 = pos[edge[1]]
76
- edge_x.extend([x0, x1, None])
77
- edge_y.extend([y0, y1, None])
78
- edge_text.append(f"{edge[0]} -> {edge[1]}: {edge[2]['relationship']}") # Adding edge relationship label
79
-
80
- # Create edge trace with hover text for relationship descriptions
81
- edge_trace = go.Scatter(
82
- x=edge_x,
83
- y=edge_y,
84
- line=dict(width=1.0, color='#888'),
85
- hoverinfo='text',
86
- text=edge_text,
87
- mode='lines',
88
- name="Edges"
89
- )
90
-
91
- # Node trace initialization with improved style
92
- node_x, node_y, node_text, node_color = [], [], [], []
93
-
94
- for node in graph.nodes():
95
- x, y = pos[node]
96
- node_x.append(x)
97
- node_y.append(y)
98
- node_text.append(
99
- f"Node: {node}<br>Type: {graph.nodes[node]['type']}<br>{graph.nodes[node].get('description', '')}"
100
- )
101
- node_color.append(color_map[graph.nodes[node]['type']])
102
-
103
- # Create node trace with enhanced marker styles and hover info
104
- node_trace = go.Scatter(
105
- x=node_x,
106
- y=node_y,
107
- text=node_text,
108
- mode='markers',
109
- hoverinfo='text',
110
- marker=dict(
111
- showscale=True,
112
- colorscale='Viridis',
113
- reversescale=True,
114
- color=node_color,
115
- size=20, # Increased size for better visibility
116
- line=dict(width=3, color='DarkSlateGrey') # Added border for better contrast
117
- ),
118
- name="Nodes"
119
- )
120
-
121
- # Create the figure and add traces with enhanced layout and better spacing
122
- fig = go.Figure()
123
- fig.add_trace(edge_trace)
124
- fig.add_trace(node_trace)
125
- fig.update_layout(
126
- title='Your Educational Landscape',
127
- titlefont_size=20,
128
- showlegend=True,
129
- hovermode='closest',
130
- margin=dict(b=20, l=5, r=5, t=40),
131
- annotations=[dict(
132
- text="",
133
- showarrow=False,
134
- xref="paper", yref="paper",
135
- x=0.005, y=-0.002
136
- )],
137
- xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
138
- yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
139
- plot_bgcolor='rgba(240, 240, 240, 0.95)'
140
- )
141
-
142
- # Add legend groups
143
- for node_type, color in color_map.items():
144
- fig.add_trace(go.Scatter(
145
- x=[],
146
- y=[],
147
- mode='markers',
148
- marker=dict(size=10, color=color),
149
- name=node_type
150
- ))
151
-
152
- return fig
153
 
154
- def clear_graph() -> str:
155
  global lesson_graph
156
  lesson_graph.clear()
157
  return "Landscape cleared. You can start a new lesson plan."
@@ -184,7 +127,7 @@ with demo:
184
  clear_btn = gr.Button("Clear Landscape")
185
 
186
  search_output = gr.Textbox(label="Content Discovery Search String")
187
- graph_output = gr.Plot(label="Your Educational Landscape")
188
  message_output = gr.Textbox(label="Landscape Status")
189
 
190
  generate_btn.click(
@@ -196,5 +139,4 @@ with demo:
196
  clear_btn.click(clear_graph, outputs=message_output)
197
 
198
  # Launch the EduScape app
199
- if __name__ == "__main__":
200
- demo.launch()
 
 
 
 
 
1
  import gradio as gr
2
+ import networkx as nx
3
+ import matplotlib.pyplot as plt
4
+ from io import BytesIO
5
+ from PIL import Image
6
+ import matplotlib.patches as mpatches
7
+ import mplcursors
8
 
9
  # Initialize the lesson plan graph as a directed graph
10
+ lesson_graph = nx.DiGraph()
11
 
12
  # Define color map for node types
13
+ color_map = {
14
  "User": "#FF9999", # Light Red
15
  "Subject": "#66B2FF", # Light Blue
16
  "Grade Level": "#99FF99", # Light Green
 
21
  "School Board": "#CCCCCC" # Light Gray
22
  }
23
 
24
+ def add_to_graph(teacher_name, subject, grade_level, learning_objective, activity, assessment, resource, school_board):
 
 
 
 
 
 
 
 
 
25
  global lesson_graph
26
 
27
  # Clear previous graph
 
48
  lesson_graph.add_edge(learning_objective, school_board, relationship="ALIGNS_WITH")
49
 
50
  # Generate search string
51
+ search_string = f"{subject} {grade_level} {learning_objective} {activity} {resource}".strip()
52
 
53
+ # Visualize the graph using Matplotlib
54
+ fig, ax = plt.subplots(figsize=(14, 10))
55
+ pos = nx.spring_layout(lesson_graph, k=0.9, iterations=50)
56
 
57
+ # Draw nodes with color coding
58
+ node_colors = [color_map[lesson_graph.nodes[node]['type']] for node in lesson_graph.nodes()]
59
+ nx.draw_networkx_nodes(lesson_graph, pos, node_color=node_colors, node_size=3000, alpha=0.8, ax=ax)
 
60
 
61
+ # Draw edges with arrows to show direction
62
+ nx.draw_networkx_edges(lesson_graph, pos, edge_color='gray', arrows=True, arrowsize=20, ax=ax)
63
+ nx.draw_networkx_labels(lesson_graph, pos, font_size=10, font_weight="bold", ax=ax)
64
+
65
+ # Add edge labels
66
+ edge_labels = nx.get_edge_attributes(lesson_graph, 'relationship')
67
+ nx.draw_networkx_edge_labels(lesson_graph, pos, edge_labels=edge_labels, font_size=8, ax=ax)
68
+
69
+ # Create a legend that categorizes node types
70
+ legend_elements = [mpatches.Patch(color=color, label=node_type) for node_type, color in color_map.items()]
71
+ plt.legend(handles=legend_elements, loc='upper left', bbox_to_anchor=(1, 1), title="Node Types")
72
+
73
+ plt.title("Your Educational Landscape", fontsize=16)
74
+ plt.axis('off')
75
+ plt.tight_layout()
76
+
77
+ # Add hover functionality
78
+ cursor = mplcursors.cursor(hover=True)
79
+
80
+ @cursor.connect("add")
81
+ def on_add(sel):
82
+ node = list(lesson_graph.nodes())[sel.target.index]
83
+ node_data = lesson_graph.nodes[node]
84
+ sel.annotation.set_text(f"Node: {node}\nType: {node_data['type']}\n{node_data.get('description', '')}")
85
+
86
+ # Save the plot to a bytes object
87
+ buf = BytesIO()
88
+ plt.savefig(buf, format="png", dpi=300, bbox_inches="tight")
89
+ buf.seek(0)
90
+ plt.close(fig)
91
+
92
+ # Convert BytesIO to PIL Image
93
+ image = Image.open(buf)
94
+
95
+ return search_string, image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ def clear_graph():
98
  global lesson_graph
99
  lesson_graph.clear()
100
  return "Landscape cleared. You can start a new lesson plan."
 
127
  clear_btn = gr.Button("Clear Landscape")
128
 
129
  search_output = gr.Textbox(label="Content Discovery Search String")
130
+ graph_output = gr.Image(label="Your Educational Landscape")
131
  message_output = gr.Textbox(label="Landscape Status")
132
 
133
  generate_btn.click(
 
139
  clear_btn.click(clear_graph, outputs=message_output)
140
 
141
  # Launch the EduScape app
142
+ demo.launch()