Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|