Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,24 +2,40 @@ import gradio as gr
|
|
2 |
import io
|
3 |
import contextlib
|
4 |
import traceback
|
|
|
5 |
|
6 |
def run_python_code(code):
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
8 |
try:
|
9 |
-
with contextlib.redirect_stdout(
|
10 |
-
exec(code, {}) #
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
except Exception:
|
13 |
-
return traceback.format_exc()
|
14 |
|
15 |
with gr.Blocks() as demo:
|
16 |
-
gr.Markdown("## π Python Code Runner (
|
17 |
-
|
18 |
-
code_input = gr.Code(language="python", label="Write Python Code")
|
19 |
-
output_box = gr.Textbox(label="Output", lines=10)
|
20 |
|
|
|
|
|
|
|
|
|
21 |
run_button = gr.Button("Run Code")
|
22 |
-
run_button.click(fn=run_python_code, inputs=code_input, outputs=
|
23 |
|
24 |
if __name__ == "__main__":
|
25 |
demo.launch()
|
|
|
2 |
import io
|
3 |
import contextlib
|
4 |
import traceback
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
|
7 |
def run_python_code(code):
|
8 |
+
stdout = io.StringIO()
|
9 |
+
img_path = "plot.png"
|
10 |
+
|
11 |
+
# Clean up any old plot
|
12 |
+
plt.close()
|
13 |
+
|
14 |
try:
|
15 |
+
with contextlib.redirect_stdout(stdout):
|
16 |
+
exec(code, {"plt": plt}) # Provide plt to global scope
|
17 |
+
|
18 |
+
# Check if a figure was created
|
19 |
+
figures = [plt.figure(i) for i in plt.get_fignums()]
|
20 |
+
if figures:
|
21 |
+
# Save the latest figure
|
22 |
+
figures[-1].savefig(img_path)
|
23 |
+
return stdout.getvalue(), img_path
|
24 |
+
else:
|
25 |
+
return stdout.getvalue(), None
|
26 |
+
|
27 |
except Exception:
|
28 |
+
return traceback.format_exc(), None
|
29 |
|
30 |
with gr.Blocks() as demo:
|
31 |
+
gr.Markdown("## π Python Code Runner with Plot Support (`matplotlib`, `pandas`)")
|
|
|
|
|
|
|
32 |
|
33 |
+
code_input = gr.Code(language="python", label="Enter Python Code")
|
34 |
+
output_text = gr.Textbox(label="Text Output", lines=10)
|
35 |
+
plot_output = gr.Image(label="Generated Plot")
|
36 |
+
|
37 |
run_button = gr.Button("Run Code")
|
38 |
+
run_button.click(fn=run_python_code, inputs=code_input, outputs=[output_text, plot_output])
|
39 |
|
40 |
if __name__ == "__main__":
|
41 |
demo.launch()
|