Nymbo commited on
Commit
5f048ad
·
verified ·
1 Parent(s): 57d2871

Create Modules/Code_Interpreter.py

Browse files
Files changed (1) hide show
  1. Modules/Code_Interpreter.py +49 -0
Modules/Code_Interpreter.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from io import StringIO
5
+ from typing import Annotated
6
+
7
+ import gradio as gr
8
+
9
+ from app import _log_call_end, _log_call_start, _truncate_for_log
10
+
11
+
12
+ def Code_Interpreter(code: Annotated[str, "Python source code to run; stdout is captured and returned."]) -> str:
13
+ _log_call_start("Code_Interpreter", code=_truncate_for_log(code or "", 300))
14
+ if code is None:
15
+ result = "No code provided."
16
+ _log_call_end("Code_Interpreter", result)
17
+ return result
18
+ old_stdout = sys.stdout
19
+ redirected_output = sys.stdout = StringIO()
20
+ try:
21
+ exec(code)
22
+ result = redirected_output.getvalue()
23
+ except Exception as exc: # pylint: disable=broad-except
24
+ result = str(exc)
25
+ finally:
26
+ sys.stdout = old_stdout
27
+ _log_call_end("Code_Interpreter", _truncate_for_log(result))
28
+ return result
29
+
30
+
31
+ def build_interface() -> gr.Interface:
32
+ return gr.Interface(
33
+ fn=Code_Interpreter,
34
+ inputs=gr.Code(label="Python Code", language="python"),
35
+ outputs=gr.Textbox(label="Output", lines=5, max_lines=20),
36
+ title="Code Interpreter",
37
+ description="<div style=\"text-align:center\">Execute Python code and see the output.</div>",
38
+ api_description=(
39
+ "Execute arbitrary Python code and return captured stdout or an error message. "
40
+ "Supports any valid Python code including imports, variables, functions, loops, and calculations. "
41
+ "Examples: 'print(2+2)', 'import math; print(math.sqrt(16))', 'for i in range(3): print(i)'. "
42
+ "Parameters: code (str - Python source code to execute). "
43
+ "Returns: Combined stdout output or exception text if execution fails."
44
+ ),
45
+ flagging_mode="never",
46
+ )
47
+
48
+
49
+ __all__ = ["Code_Interpreter", "build_interface"]