AlexKurinaQueens/BubbleSortApp
0
1import gradio as gr
2import time
3import matplotlib.pyplot as plt
4import random
5import io
6from PIL import Image
7
8def bubble_sort_generator(arr):
9 n = len(arr)
10 swapped = True
11 yield arr, -1, -1, "initial array state"
12 while swapped:
13 i = 0
14 swapped = False
15 while i < n - 1:
16 if arr[i] > arr[i+1]:
17 arr[i], arr[i+1] = arr[i+1], arr[i]
18 yield arr, i, i+1, f"swap {i} <-> {i+1}"
19 swapped = True
20 else:
21 yield arr, i, i+1, f"move window {i},{i+1} -> {i+1},{i+2}"
22
23 i += 1
24 n -= 1
25
26 yield arr, -1, -1, "sorted"
27
28def visualize_sort(array_size, array_maximum, delay):
29 """
30 Generates a list, sorts it with the chosen algorithm generator,
31 and yields matplotlib plots for Gradio to display.
32 """
33 arr = [random.randint(1, array_maximum) for _ in range(array_size)]
34 sort_gen = bubble_sort_generator(arr)
35
36 # iterate through states in bubble sort generator
37 for current_arr, idx1, idx2, state in sort_gen:
38
39 # Create a matplotlib figure
40 fig, ax = plt.subplots()
41
42 # Set bar colors based on the current state
43 colors = ['blue'] * array_size
44 if idx1 != -1:
45 colors[idx1] = 'red'
46 if idx2 != -1:
47 colors[idx2] = 'red'
48
49 # create matplot bar graph
50 ax.bar(range(array_size), current_arr, color=colors)
51 ax.set_xticks([])
52
53 # set the title of the graph to the current operation in the bubble sort
54 ax.set_title(state)
55
56 # disable matplot autoscaling and set plot limits
57 ax.set_ylim(0, array_maximum + 5)
58 ax.set_xlim(-1, array_size)
59 ax.autoscale(False)
60
61 # Convert plot to image
62 buffer = io.BytesIO() # create buffer to store image data
63 plt.savefig(buffer, format='png', bbox_inches='tight') # save plot as binary data to buffer
64 plt.close(fig) # close plot
65 img = Image.open(buffer) # load data from buffer as image
66
67 # yield image to gradio
68 yield img
69
70 # close image
71 buffer.close()
72
73 # apply step delay
74 if delay > 0:
75 time.sleep(delay)
76
77if __name__ == "__main__":
78 # Define inputs and outputs for the Gradio interface
79 inputs = [
80 gr.Slider(minimum=10, maximum=100, step=1, label="Array Size", value=50),
81 gr.Slider(minimum=10, maximum=100, step=1, label="Array Max", value=50),
82 gr.Slider(minimum=0, maximum=1, step=0.1, label="Step Delay (s)", value=0)
83 ]
84
85 output = gr.Image()
86
87 # Create the Gradio interface
88 gr.Interface(
89 fn=visualize_sort,
90 inputs=inputs,
91 outputs=output,
92 title="Bubble Search App",
93 description="sorts an integer array using the bubble sort algorithm while displaying operations and array states with a real-time visualizer"
94 ).launch()
95
96 