Walmart-the-bag commited on
Commit
5add17c
·
verified ·
1 Parent(s): 57e6a21

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +59 -0
main.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import matplotlib.pyplot as plt
4
+ import traceback
5
+ import sys
6
+ import io
7
+ import numpy as np
8
+ from PIL import Image
9
+
10
+ def run_code(code):
11
+ try:
12
+ if any(bad_cmd in code for bad_cmd in ['rm', 'os', 'shutil']):
13
+ return "Error: This command is not allowed."
14
+
15
+ # Capture the standard output
16
+ old_stdout = sys.stdout
17
+ sys.stdout = io.StringIO()
18
+
19
+ local_env = {'plt': plt, 'subprocess': subprocess}
20
+
21
+ exec(code, {}, local_env)
22
+
23
+ output = sys.stdout.getvalue()
24
+ sys.stdout = old_stdout
25
+
26
+ buf = io.BytesIO()
27
+ plt.savefig(buf, format='png')
28
+ buf.seek(0)
29
+ img = Image.open(buf)
30
+ img_array = np.array(img)
31
+ plt.close()
32
+
33
+ if np.array(img_array).sum() > 0:
34
+ return img_array
35
+
36
+ return noplot()
37
+
38
+ except Exception as e:
39
+ return noplot()
40
+
41
+ def noplot():
42
+ fig, ax = plt.subplots()
43
+ ax.text(0.5, 0.5, "Required: matplotlib", fontsize=20, ha='center', va='center')
44
+ ax.axis('off')
45
+ buf = io.BytesIO()
46
+ plt.savefig(buf, format='png')
47
+ buf.seek(0)
48
+ img = Image.open(buf)
49
+ plt.close()
50
+ return np.array(img)
51
+
52
+ interface = gr.Interface(
53
+ fn=run_code,
54
+ inputs=gr.Code(language="python", label="code"),
55
+ outputs=gr.Image(type="numpy", label="Output"),
56
+ title="matplotlib-graph-creation",
57
+ )
58
+
59
+ interface.launch()