File size: 3,495 Bytes
a6e5427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()