Spaces:
Sleeping
Sleeping
File size: 4,252 Bytes
5edc6a5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
import gradio as gr
import subprocess
import io
import sys
# Function to handle input() calls in code by simulating user input
class InputMock:
def __init__(self, inputs):
# Split inputs by commas and remove any '=' sign to handle cases like 'x=10' -> '10'
self.inputs = [i.split('=')[-1].strip() for i in inputs.split(",")]
self.index = 0
def readline(self):
if self.index < len(self.inputs):
# Return the current input and move to the next
value = self.inputs[self.index]
self.index += 1
return value
else:
# No more inputs, raise EOF to simulate end of input
return ''
# Function to install pip packages
def install_packages(packages):
try:
if packages:
package_list = packages.split(',')
for package in package_list:
package = package.strip()
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
return "Packages installed successfully.\n"
except subprocess.CalledProcessError as e:
return f"Package installation failed: {str(e)}\n"
# Function to execute Python, Bash, and HTML code
def execute_code(code, language, inputs, packages):
try:
# Handle pip installations if any packages are provided
install_msg = install_packages(packages)
# Handle Python code execution
if language == "Python":
old_stdout = sys.stdout
new_stdout = io.StringIO()
sys.stdout = new_stdout
# Replace input() with mock input
sys_input_backup = sys.stdin
sys.stdin = InputMock(inputs)
exec(code) # Execute the Python code
# Restore stdout and input after execution
output = new_stdout.getvalue()
sys.stdout = old_stdout
sys.stdin = sys_input_backup
return f"{install_msg}Output:\n{output}\nErrors: None"
# Handle Bash code execution
elif language == "Bash":
output = subprocess.check_output(code, shell=True).decode("utf-8")
return f"{install_msg}Output:\n{output}\nErrors: None"
# Handle HTML code execution
elif language == "HTML":
# Save the HTML code to a temporary file
with open("temp.html", "w") as f:
f.write(code)
# Open the HTML file in the default browser
subprocess.check_call(["start", "temp.html"], shell=True)
# Wait for 5 seconds to allow the browser to load
import time
time.sleep(5)
# Capture any errors from the console
output = subprocess.check_output(["tasklist", "/FI", "IMAGENAME eq chrome.exe"], shell=True).decode("utf-8")
return f"{install_msg}Output:\n{output}\nErrors: None"
else:
return "Output: None\nErrors: Unsupported language"
except Exception as e:
return f"{install_msg}Output: None\nErrors: {str(e)}"
# Gradio interface setup
demo = gr.Blocks()
with demo:
gr.Markdown("## Python, Bash, and HTML IDE with Inputs\nEnter your code, inputs, and select the language to run it")
with gr.Row():
code_input = gr.Code(label="Editor", language="python", lines=20)
language_dropdown = gr.Dropdown(label="Language", choices=["Python", "Bash", "HTML"], value="Python")
# Clarified that input values should only be raw values, not variable assignments like 'x=5'
inputs_field = gr.Textbox(label="Inputs", placeholder="Enter values separated by commas (e.g., 5, 10)")
packages_field = gr.Textbox(label="Packages", placeholder="Enter pip packages separated by commas (e.g., numpy, pandas)")
output = gr.Textbox(label="Output", placeholder="Output will appear here", lines=10)
# Button to trigger execution
run_button = gr.Button("Run Code")
# Bind the button to the function that executes the code
run_button.click(fn=execute_code, inputs=[code_input, language_dropdown, inputs_field, packages_field], outputs=output)
# Launch the Gradio app
demo.launch() |