Delete app.py
Browse filesimport gradio as gr, numpy as np, matplotlib.pyplot as plt, io, contextlib, traceback, sys
from PIL import Image
def run(code:str, prev_globals:dict):
out, figs = "", []
loc = {"__builtins__": __builtins__, "plt": plt, "np": np}
if prev_globals: loc.update(prev_globals)
try:
s = io.StringIO()
with contextlib.redirect_stdout(s):
exec(code, loc)
out = s.getvalue()
for num in plt.get_fignums():
buf = io.BytesIO()
plt.figure(num).savefig(buf, format='png', bbox_inches='tight')
buf.seek(0); figs.append(Image.open(buf))
plt.close(num)
except Exception as e:
out = traceback.format_exc()
return out, figs, loc
def py_cell(code, state):
txt, imgs, new_state = run(code, state)
return txt, gr.Gallery(imgs), new_state
with gr.Blocks(title="py@hf") as demo:
st = gr.State({})
gr.Markdown("## Python în browser – rulează `py>`")
code = gr.Textbox(lines=8, label="Code", placeholder="print('Hello py@hf')")
run_btn = gr.Button("Run")
out_txt = gr.Textbox(label="stdout")
out_img = gr.Gallery(label="plots")
run_btn.click(py_cell, inputs=[code, st], outputs=[out_txt, out_img, st])
demo.queue().launch()
|
@@ -1,38 +0,0 @@
|
|
| 1 |
-
import gradio as gr, sys, io, contextlib, traceback, tempfile, os, base64
|
| 2 |
-
from matplotlib import pyplot as plt
|
| 3 |
-
from PIL import Image
|
| 4 |
-
|
| 5 |
-
def run(code:str, prev_globals:dict):
|
| 6 |
-
out, figs = "", []
|
| 7 |
-
loc = {"__builtins__": __builtins__, "plt": plt, "np": __import__("numpy")}
|
| 8 |
-
if prev_globals: loc.update(prev_globals)
|
| 9 |
-
try:
|
| 10 |
-
# capturăm stdout
|
| 11 |
-
s = io.StringIO()
|
| 12 |
-
with contextlib.redirect_stdout(s):
|
| 13 |
-
exec(code, loc)
|
| 14 |
-
out = s.getvalue()
|
| 15 |
-
# salvăm figuri deschise
|
| 16 |
-
for num in plt.get_fignums():
|
| 17 |
-
buf = io.BytesIO()
|
| 18 |
-
plt.figure(num).savefig(buf, format='png', bbox_inches='tight')
|
| 19 |
-
buf.seek(0); figs.append(Image.open(buf))
|
| 20 |
-
plt.close(num)
|
| 21 |
-
except Exception as e:
|
| 22 |
-
out = traceback.format_exc()
|
| 23 |
-
return out, figs, loc
|
| 24 |
-
|
| 25 |
-
def py_cell(code, state):
|
| 26 |
-
txt, imgs, new_state = run(code, state)
|
| 27 |
-
return txt, gr.Gallery(imgs), new_state
|
| 28 |
-
|
| 29 |
-
with gr.Blocks(title="py@hf") as demo:
|
| 30 |
-
st = gr.State({})
|
| 31 |
-
gr.Markdown("## Python în browser – rulează `py>`")
|
| 32 |
-
code = gr.Textbox(lines=6, label="Code", placeholder="print('Hello py@hf')")
|
| 33 |
-
run_btn = gr.Button("Run")
|
| 34 |
-
out_txt = gr.Textbox(label="stdout")
|
| 35 |
-
out_img = gr.Gallery(label="plots")
|
| 36 |
-
run_btn.click(py_cell, inputs=[code, st], outputs=[out_txt, out_img, st])
|
| 37 |
-
|
| 38 |
-
demo.queue().launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|