xd11yggy commited on
Commit
d49345d
·
verified ·
1 Parent(s): 5bf8606
Files changed (1) hide show
  1. app.py +68 -31
app.py CHANGED
@@ -1,57 +1,94 @@
1
  import gradio as gr
2
  import subprocess
3
  import tempfile
 
4
  import traceback
5
 
6
-
7
  class CodeExecutor:
8
  def __init__(self):
9
  self.temp_dir = tempfile.TemporaryDirectory()
10
 
11
- def execute(self, code, inputs):
12
- input_file = f"{self.temp_dir.name}/input.txt"
13
- with open(input_file, "w") as f:
14
- f.write(inputs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  output_file = f"{self.temp_dir.name}/output.txt"
17
  error_file = f"{self.temp_dir.name}/error.txt"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  try:
19
- with open(output_file, "w") as f, open(error_file, "w") as e:
20
- subprocess.run(
21
- ["python", "-c", code], check=True, timeout=5, stdin=open(input_file, "r"), stdout=f, stderr=e
22
- )
23
- with open(output_file, "r") as f:
24
- output = f.read()
25
- with open(error_file, "r") as f:
26
- error = f.read()
27
- if error:
28
- output = f"Error:\n{error}"
29
- except subprocess.CalledProcessError as e:
30
- output = f"Error:\n{e}\n\n{traceback.format_exc()}"
31
- except subprocess.TimeoutExpired:
32
- output = "Execution timed out."
33
  except Exception as e:
34
- output = f"Error:\n{e}\n\n{traceback.format_exc()}"
 
 
35
 
36
- return f"User's Code:\n```python\n{code}\n```\n\nOutput:\n{output}"
 
37
 
 
 
 
38
 
39
  def create_interface():
40
  with gr.Blocks() as demo:
41
  gr.Markdown("# Code Interpreter")
42
- gr.Markdown("Enter Python code and inputs to execute.")
43
- code_input = gr.Code(language="python", label="Code")
44
- inputs_input = gr.Textbox(label="Inputs")
45
- output_text = gr.Textbox(label="Output", lines=20)
 
46
  run_button = gr.Button("Run")
47
  run_button.click(
48
- CodeExecutor().execute, inputs=[code_input, inputs_input], outputs=output_text
 
 
49
  )
50
- demo.inputs = [code_input, inputs_input]
51
- demo.outputs = [output_text]
52
  return demo
53
 
54
-
55
  if __name__ == "__main__":
56
- app = create_interface()
57
- app.launch()
 
1
  import gradio as gr
2
  import subprocess
3
  import tempfile
4
+ import shutil
5
  import traceback
6
 
 
7
  class CodeExecutor:
8
  def __init__(self):
9
  self.temp_dir = tempfile.TemporaryDirectory()
10
 
11
+ def _install_packages(self, packages):
12
+ for package in packages:
13
+ try:
14
+ subprocess.check_call(["pip", "install", package], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
15
+ except subprocess.CalledProcessError as e:
16
+ raise Exception(f"Error installing package {package}: {e}")
17
+
18
+ def _uninstall_packages(self, packages):
19
+ for package in packages:
20
+ try:
21
+ subprocess.check_call(["pip", "uninstall", "-y", package], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
22
+ except subprocess.CalledProcessError as e:
23
+ raise Exception(f"Error uninstalling package {package}: {e}")
24
+
25
+ def _execute_code(self, code, inputs):
26
+ temp_file = f"{self.temp_dir.name}/temp.py"
27
+ with open(temp_file, "w") as f:
28
+ f.write(code)
29
 
30
  output_file = f"{self.temp_dir.name}/output.txt"
31
  error_file = f"{self.temp_dir.name}/error.txt"
32
+ with open(output_file, "w") as output, open(error_file, "w") as error:
33
+ try:
34
+ process = subprocess.Popen(["python", temp_file], stdin=subprocess.PIPE, stdout=output, stderr=error)
35
+ if inputs:
36
+ for input_value in inputs:
37
+ process.stdin.write(input_value.encode())
38
+ process.stdin.write(b"\n")
39
+ process.stdin.close()
40
+ process.wait()
41
+ except Exception as e:
42
+ error.write(traceback.format_exc())
43
+
44
+ with open(output_file, "r") as output, open(error_file, "r") as error:
45
+ output_text = output.read()
46
+ error_text = error.read()
47
+ if error_text:
48
+ return f"{code}\n\nTraceback (most recent call last):\n{error_text}"
49
+ return f"{code}\n\nOutput:\n{output_text}"
50
+
51
+ def execute(self, code, inputs, packages):
52
  try:
53
+ if not packages:
54
+ packages = []
55
+ else:
56
+ packages = [p.strip() for p in packages.split(",")]
57
+ if packages:
58
+ self._install_packages(packages)
59
+ input_values = [i.strip() for i in inputs.split(",")] if inputs else []
60
+ output = self._execute_code(code, input_values)
61
+ if packages:
62
+ self._uninstall_packages(packages)
63
+ return output
 
 
 
64
  except Exception as e:
65
+ return f"Error: {str(e)}"
66
+ finally:
67
+ shutil.rmtree(self.temp_dir.name)
68
 
69
+ def __del__(self):
70
+ shutil.rmtree(self.temp_dir.name)
71
 
72
+ def wrapper_execute(code, inputs, packages):
73
+ executor = CodeExecutor()
74
+ return executor.execute(code, inputs, packages)
75
 
76
  def create_interface():
77
  with gr.Blocks() as demo:
78
  gr.Markdown("# Code Interpreter")
79
+ gr.Markdown("Enter Python code and inputs to execute")
80
+ code_input = gr.Textbox(label="Code", lines=20)
81
+ inputs_input = gr.Textbox(label="Inputs (comma-separated)", lines=1)
82
+ packages_input = gr.Textbox(label="Install Packages (comma-separated)", lines=1)
83
+ output_text = gr.Text(label="Output", lines=20)
84
  run_button = gr.Button("Run")
85
  run_button.click(
86
+ wrapper_execute,
87
+ inputs=[code_input, inputs_input, packages_input],
88
+ outputs=output_text
89
  )
 
 
90
  return demo
91
 
 
92
  if __name__ == "__main__":
93
+ demo = create_interface()
94
+ demo.launch()