nerdify
Browse files
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 "
|
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 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
return
|
37 |
|
38 |
except Exception as e:
|
39 |
-
return
|
40 |
|
41 |
-
def
|
42 |
fig, ax = plt.subplots()
|
43 |
-
ax.text(0.5, 0.5,
|
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="
|
55 |
outputs=gr.Image(type="numpy", label="Output"),
|
56 |
-
title="
|
|
|
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()
|