peak / app.py
summrs's picture
app.py
a6e5427 verified
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()