Sugamdeol commited on
Commit
69583a0
·
verified ·
1 Parent(s): 9afbe58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -28
app.py CHANGED
@@ -4,40 +4,58 @@ import numpy as np
4
  import io
5
  from PIL import Image
6
 
7
- def generate_graph_from_code(code):
8
- # Create a buffer to capture output
 
 
 
9
  buf = io.BytesIO()
10
 
11
  try:
12
- # Define a dummy multiplier if not present in the code
13
- exec(code)
14
- if 'multiplier' not in locals():
15
- multiplier = 1
 
 
 
 
 
 
16
  except Exception as e:
17
- return str(e)
18
-
19
- # Generate the graph
20
- x = np.linspace(0, 10, 100)
21
- y = np.sin(x) * multiplier
22
-
23
- plt.figure()
24
- plt.plot(x, y)
25
- plt.title("Generated Graph")
26
- plt.xlabel("x")
27
- plt.ylabel("y")
28
- plt.grid(True)
29
- plt.savefig(buf, format='png')
30
- buf.seek(0)
31
- img = Image.open(buf)
32
- return img
33
 
34
- # Define the Gradio interface using the updated API
35
  interface = gr.Interface(
36
- fn=generate_graph_from_code,
37
- inputs=gr.Textbox(lines=10, placeholder="Paste your Python code here", label="Python Code"),
38
- outputs=gr.Image(type="pil", label="Generated Graph"),
39
- title="Python Code to Graph Generator",
40
- description="Paste Python code that defines a variable `multiplier` to generate a graph."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  )
42
 
43
  if __name__ == "__main__":
 
4
  import io
5
  from PIL import Image
6
 
7
+ def execute_code_and_get_plot(code):
8
+ # Clear any existing plots
9
+ plt.clf()
10
+
11
+ # Create a BytesIO object to store the plot
12
  buf = io.BytesIO()
13
 
14
  try:
15
+ # Execute the code
16
+ exec(code, globals())
17
+
18
+ # Save the current plot to the BytesIO object
19
+ plt.savefig(buf, format='png')
20
+ buf.seek(0)
21
+
22
+ # Convert to PIL Image
23
+ image = Image.open(buf)
24
+ return image, "Code executed successfully!"
25
  except Exception as e:
26
+ return None, f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ # Define the Gradio interface
29
  interface = gr.Interface(
30
+ fn=execute_code_and_get_plot,
31
+ inputs=[
32
+ gr.Code(
33
+ label="Python Code",
34
+ language="python",
35
+ lines=20,
36
+ placeholder="""
37
+ # Example:
38
+ import matplotlib.pyplot as plt
39
+ import numpy as np
40
+
41
+ x = np.linspace(0, 10, 100)
42
+ y = np.sin(x)
43
+
44
+ plt.figure(figsize=(8, 6))
45
+ plt.plot(x, y)
46
+ plt.title('Sine Wave')
47
+ plt.xlabel('x')
48
+ plt.ylabel('sin(x)')
49
+ plt.grid(True)
50
+ """
51
+ )
52
+ ],
53
+ outputs=[
54
+ gr.Image(type="pil", label="Generated Plot"),
55
+ gr.Textbox(label="Output Message")
56
+ ],
57
+ title="Python Code to Matplotlib Plot Generator",
58
+ description="Enter Python code that generates a matplotlib plot. The plot will be displayed as an image."
59
  )
60
 
61
  if __name__ == "__main__":