py / app.py
minhvh's picture
Update app.py
22d8c7d verified
import gradio as gr
import sys
import io
import contextlib
import ast
import os
import shutil
import tempfile
def execute(code, files):
if not code.strip():
return "No code provided", ""
try:
ast.parse(code)
except SyntaxError as e:
return str(e), ""
except Exception as e:
return str(e), ""
temp_dir = None
try:
temp_dir = tempfile.mkdtemp()
if files is not None:
for file in files:
filename = os.path.basename(file.name)
dest_path = os.path.join(temp_dir, filename)
shutil.copy2(file.name, dest_path)
sys.path.insert(0, temp_dir)
@contextlib.contextmanager
def capture_output():
stdout, stderr = io.StringIO(), io.StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = stdout, stderr
yield stdout, stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
with capture_output() as (stdout, stderr):
try:
globals_dict = {}
locals_dict = {}
code_lines = code.strip().split('\n')
if len(code_lines) > 1:
exec('\n'.join(code_lines[:-1]), globals_dict, locals_dict)
last_line = code_lines[-1].strip()
result_value = None
if last_line:
try:
compile(last_line, '<string>', 'eval')
result_value = eval(last_line, globals_dict, locals_dict)
except SyntaxError:
exec(last_line, globals_dict, locals_dict)
except Exception as e:
print(str(e), file=sys.stderr)
result_value = None
combined_output = stdout.getvalue() + stderr.getvalue()
return_value = str(result_value) if result_value is not None else ""
return combined_output, return_value
except Exception as e:
return str(e), ""
finally:
if temp_dir is not None:
try:
sys.path.remove(temp_dir)
except ValueError:
pass
try:
shutil.rmtree(temp_dir)
except:
pass
with gr.Blocks(title="Python Code Executor") as demo:
gr.Markdown("# 🔧 Python Code Executor")
gr.Markdown("Enter your Python code below or upload files, then click **Run** to execute it.")
with gr.Row():
with gr.Column():
code_input = gr.Code(label="Python Code", language="python", lines=15)
output_display = gr.Textbox(label="Log", interactive=False)
return_value_display = gr.Textbox(label="Return", interactive=False)
with gr.Column():
file_upload = gr.File(label="Upload Files (txt, csv, images, etc.)", file_types=None, file_count="multiple")
run_button = gr.Button("▶ Run Code")
run_button.click(
fn=execute,
inputs=[code_input, file_upload],
outputs=[output_display, return_value_display]
)
if __name__ == "__main__":
demo.launch()