Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,41 +1,55 @@
|
|
1 |
import gradio as gr
|
2 |
import io
|
3 |
-
import contextlib
|
4 |
import traceback
|
5 |
import matplotlib.pyplot as plt
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
|
11 |
-
|
12 |
-
|
|
|
|
|
13 |
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
figures = [plt.figure(i) for i in plt.get_fignums()]
|
|
|
20 |
if figures:
|
21 |
-
|
22 |
figures[-1].savefig(img_path)
|
23 |
-
return stdout.getvalue(), img_path
|
24 |
-
else:
|
25 |
-
return stdout.getvalue(), None
|
26 |
|
27 |
-
|
|
|
|
|
28 |
return traceback.format_exc(), None
|
29 |
|
30 |
with gr.Blocks() as demo:
|
31 |
-
gr.Markdown("##
|
32 |
-
|
33 |
code_input = gr.Code(language="python", label="Enter Python Code")
|
34 |
-
output_text = gr.Textbox(label="
|
35 |
-
plot_output = gr.Image(label="
|
36 |
|
37 |
run_button = gr.Button("Run Code")
|
38 |
-
run_button.click(fn=
|
39 |
|
40 |
if __name__ == "__main__":
|
41 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
import io
|
|
|
3 |
import traceback
|
4 |
import matplotlib.pyplot as plt
|
5 |
|
6 |
+
from IPython.display import display, HTML
|
7 |
+
from contextlib import redirect_stdout
|
8 |
+
from IPython.core.interactiveshell import InteractiveShell
|
9 |
|
10 |
+
# Create a function to capture all kinds of Jupyter-like outputs
|
11 |
+
def run_jupyter_style_code(code):
|
12 |
+
# Reset any old figures
|
13 |
+
plt.close('all')
|
14 |
|
15 |
+
# Setup for capturing output
|
16 |
+
shell = InteractiveShell.instance()
|
17 |
+
stdout = io.StringIO()
|
18 |
|
19 |
+
try:
|
20 |
+
with redirect_stdout(stdout):
|
21 |
+
result = shell.run_cell(code)
|
22 |
+
|
23 |
+
# Collect rich display outputs
|
24 |
+
rich_output = ""
|
25 |
+
if result.result is not None:
|
26 |
+
try:
|
27 |
+
display_out = display(result.result, display_id=False)
|
28 |
+
rich_output = str(result.result)
|
29 |
+
except Exception:
|
30 |
+
rich_output = str(result.result)
|
31 |
+
|
32 |
+
# Show latest matplotlib figure if available
|
33 |
figures = [plt.figure(i) for i in plt.get_fignums()]
|
34 |
+
img_path = None
|
35 |
if figures:
|
36 |
+
img_path = "plot.png"
|
37 |
figures[-1].savefig(img_path)
|
|
|
|
|
|
|
38 |
|
39 |
+
return stdout.getvalue() + "\n" + rich_output, img_path
|
40 |
+
|
41 |
+
except Exception as e:
|
42 |
return traceback.format_exc(), None
|
43 |
|
44 |
with gr.Blocks() as demo:
|
45 |
+
gr.Markdown("## 🧪 Python Code Runner with Jupyter-style Output")
|
46 |
+
|
47 |
code_input = gr.Code(language="python", label="Enter Python Code")
|
48 |
+
output_text = gr.Textbox(label="Console Output + Rich Result", lines=12)
|
49 |
+
plot_output = gr.Image(label="Plot (if any)")
|
50 |
|
51 |
run_button = gr.Button("Run Code")
|
52 |
+
run_button.click(fn=run_jupyter_style_code, inputs=code_input, outputs=[output_text, plot_output])
|
53 |
|
54 |
if __name__ == "__main__":
|
55 |
demo.launch()
|