summrs commited on
Commit
a6e5427
·
verified ·
1 Parent(s): da831cd

import gradio as gr
import networkx as nx

# Helper Functions
def parse_graph_input(graph_input):
"""Parse user input to create an adjacency list."""
try:
# Try interpreting as a dictionary (adjacency list)
graph = eval(graph_input)
if isinstance(graph, dict):
return graph
except:
pass

try:
# Try interpreting as an edge list
edges = eval(graph_input)
if not isinstance(edges, list):
raise ValueError("Invalid graph input. Please use an adjacency list or edge list.")

graph = {}
for u, v in edges:
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u)
return graph
except:
raise ValueError("Invalid graph input. Please use a valid adjacency list or edge list.")

def visualize_graph(graph):
"""Generate a visualization of the graph using a circular layout."""
if len(graph) > 50: # Skip visualization for large graphs
return None

import matplotlib.pyplot as plt
plt.figure()
nodes = list(graph.keys())
edges = [(u, v) for u in graph for v in graph[u]]

pos = nx.circular_layout(nx.Graph(edges))
nx.draw(
nx.Graph(edges),
pos,
with_labels=True,
node_color='lightblue',
edge_color='gray',
node_size=500,
font_size=10
)
return plt.gcf()

def get_basic_graph_info(graph):
"""Return basic information about the graph."""
num_nodes = len(graph)
num_edges = sum(len(neighbors) for neighbors in graph.values()) // 2
return (
f"### Graph Information\n"
f"- Number of Nodes: {num_nodes}\n"
f"- Number of Edges: {num_edges}\n"
f"- Degree of Each Node: { {node: len(neighbors) for node, neighbors in graph.items()} }\n"
)

def process_inputs(graph1_input, graph2_input, question_type):
"""Process user inputs and perform the selected operation."""
# Parse graphs
graph1 = parse_graph_input(graph1_input)
graph2 = parse_graph_input(graph2_input)

# Determine operation based on question type
if question_type == "Basic Graph Info":
result = get_basic_graph_info(graph1) + "\n" + get_basic_graph_info(graph2)
else:
result = "Unsupported question type. Please select a valid operation."

# Visualize graphs
graph1_plot = visualize_graph(graph1)
graph2_plot = visualize_graph(graph2)

return graph1_plot, graph2_plot, result

# Gradio Interface
with gr.Blocks(title="Graph Theory Project") as demo:
gr.Markdown("# Graph Theory Project")
gr.Markdown("Analyze graphs and get basic information!")

with gr.Row():
graph1_input = gr.Textbox(label="Graph 1 Input (e.g., '{0: [1], 1: [0, 2], 2: [1]}' or edge list)")
graph2_input = gr.Textbox(label="Graph 2 Input (e.g., '{0: [1], 1: [0, 2], 2: [1]}' or edge list)")

question_type = gr.Dropdown(
choices=["Basic Graph Info"],
label="Select Question Type"
)

with gr.Row():
graph1_output = gr.Plot(label="Graph 1 Visualization")
graph2_output = gr.Plot(label="Graph 2 Visualization")

result_output = gr.Textbox(label="Results", lines=20)

submit_button = gr.Button("Run")
submit_button.click(
process_inputs,
inputs=[graph1_input, graph2_input, question_type],
outputs=[graph1_output, graph2_output, result_output]
)

# Launch the app
demo.launch()

Files changed (1) hide show
  1. app.py +108 -0
app.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import networkx as nx
3
+
4
+ # Helper Functions
5
+ def parse_graph_input(graph_input):
6
+ """Parse user input to create an adjacency list."""
7
+ try:
8
+ # Try interpreting as a dictionary (adjacency list)
9
+ graph = eval(graph_input)
10
+ if isinstance(graph, dict):
11
+ return graph
12
+ except:
13
+ pass
14
+
15
+ try:
16
+ # Try interpreting as an edge list
17
+ edges = eval(graph_input)
18
+ if not isinstance(edges, list):
19
+ raise ValueError("Invalid graph input. Please use an adjacency list or edge list.")
20
+
21
+ graph = {}
22
+ for u, v in edges:
23
+ graph.setdefault(u, []).append(v)
24
+ graph.setdefault(v, []).append(u)
25
+ return graph
26
+ except:
27
+ raise ValueError("Invalid graph input. Please use a valid adjacency list or edge list.")
28
+
29
+ def visualize_graph(graph):
30
+ """Generate a visualization of the graph using a circular layout."""
31
+ if len(graph) > 50: # Skip visualization for large graphs
32
+ return None
33
+
34
+ import matplotlib.pyplot as plt
35
+ plt.figure()
36
+ nodes = list(graph.keys())
37
+ edges = [(u, v) for u in graph for v in graph[u]]
38
+
39
+ pos = nx.circular_layout(nx.Graph(edges))
40
+ nx.draw(
41
+ nx.Graph(edges),
42
+ pos,
43
+ with_labels=True,
44
+ node_color='lightblue',
45
+ edge_color='gray',
46
+ node_size=500,
47
+ font_size=10
48
+ )
49
+ return plt.gcf()
50
+
51
+ def get_basic_graph_info(graph):
52
+ """Return basic information about the graph."""
53
+ num_nodes = len(graph)
54
+ num_edges = sum(len(neighbors) for neighbors in graph.values()) // 2
55
+ return (
56
+ f"### Graph Information\n"
57
+ f"- Number of Nodes: {num_nodes}\n"
58
+ f"- Number of Edges: {num_edges}\n"
59
+ f"- Degree of Each Node: { {node: len(neighbors) for node, neighbors in graph.items()} }\n"
60
+ )
61
+
62
+ def process_inputs(graph1_input, graph2_input, question_type):
63
+ """Process user inputs and perform the selected operation."""
64
+ # Parse graphs
65
+ graph1 = parse_graph_input(graph1_input)
66
+ graph2 = parse_graph_input(graph2_input)
67
+
68
+ # Determine operation based on question type
69
+ if question_type == "Basic Graph Info":
70
+ result = get_basic_graph_info(graph1) + "\n" + get_basic_graph_info(graph2)
71
+ else:
72
+ result = "Unsupported question type. Please select a valid operation."
73
+
74
+ # Visualize graphs
75
+ graph1_plot = visualize_graph(graph1)
76
+ graph2_plot = visualize_graph(graph2)
77
+
78
+ return graph1_plot, graph2_plot, result
79
+
80
+ # Gradio Interface
81
+ with gr.Blocks(title="Graph Theory Project") as demo:
82
+ gr.Markdown("# Graph Theory Project")
83
+ gr.Markdown("Analyze graphs and get basic information!")
84
+
85
+ with gr.Row():
86
+ graph1_input = gr.Textbox(label="Graph 1 Input (e.g., '{0: [1], 1: [0, 2], 2: [1]}' or edge list)")
87
+ graph2_input = gr.Textbox(label="Graph 2 Input (e.g., '{0: [1], 1: [0, 2], 2: [1]}' or edge list)")
88
+
89
+ question_type = gr.Dropdown(
90
+ choices=["Basic Graph Info"],
91
+ label="Select Question Type"
92
+ )
93
+
94
+ with gr.Row():
95
+ graph1_output = gr.Plot(label="Graph 1 Visualization")
96
+ graph2_output = gr.Plot(label="Graph 2 Visualization")
97
+
98
+ result_output = gr.Textbox(label="Results", lines=20)
99
+
100
+ submit_button = gr.Button("Run")
101
+ submit_button.click(
102
+ process_inputs,
103
+ inputs=[graph1_input, graph2_input, question_type],
104
+ outputs=[graph1_output, graph2_output, result_output]
105
+ )
106
+
107
+ # Launch the app
108
+ demo.launch()