Walmart-the-bag commited on
Commit
fc737eb
1 Parent(s): 67792f8
Files changed (1) hide show
  1. app.py +19 -20
app.py CHANGED
@@ -10,37 +10,35 @@ from PIL import Image
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')
@@ -51,9 +49,10 @@ def noplot():
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()
 
10
  def run_code(code):
11
  try:
12
  if any(bad_cmd in code for bad_cmd in ['rm', 'os', 'shutil']):
13
+ return create_image("")
14
+
 
15
  old_stdout = sys.stdout
16
  sys.stdout = io.StringIO()
17
 
18
  local_env = {'plt': plt, 'subprocess': subprocess}
 
19
  exec(code, {}, local_env)
20
 
21
  output = sys.stdout.getvalue()
22
  sys.stdout = old_stdout
23
 
24
+ if any('plt' in line for line in code.splitlines()):
25
+ buf = io.BytesIO()
26
+ plt.savefig(buf, format='png')
27
+ buf.seek(0)
28
+ img = Image.open(buf)
29
+ img_array = np.array(img)
30
+ plt.close()
31
+ if np.array(img_array).sum() > 0:
32
+ return img_array
33
+
34
+ return create_image("")
35
 
36
  except Exception as e:
37
+ return create_image("")
38
 
39
+ def create_image(message):
40
  fig, ax = plt.subplots()
41
+ ax.text(0.5, 0.5, message, fontsize=20, ha='center', va='center')
42
  ax.axis('off')
43
  buf = io.BytesIO()
44
  plt.savefig(buf, format='png')
 
49
 
50
  interface = gr.Interface(
51
  fn=run_code,
52
+ inputs=gr.Code(language="python", label="Enter Python Code"),
53
  outputs=gr.Image(type="numpy", label="Output"),
54
+ title="Python Interpreter",
55
+ description="Run Python code. Requires matplotlib for plots."
56
  )
57
 
58
  interface.launch()