minhvh commited on
Commit
4df8753
·
verified ·
1 Parent(s): 49503d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -21
app.py CHANGED
@@ -13,9 +13,7 @@ logger = logging.getLogger(__name__)
13
  # ----------------- Helper Functions -----------------
14
 
15
  def wrap_last_expr_with_return(code: str) -> str:
16
- """
17
- Nếu dòng cuối là expression, tự động chuyển thành return.
18
- """
19
  try:
20
  tree = ast.parse(code)
21
  if tree.body and isinstance(tree.body[-1], ast.Expr):
@@ -26,9 +24,7 @@ def wrap_last_expr_with_return(code: str) -> str:
26
  return code
27
 
28
  def wrap_code_for_execution(user_code: str) -> str:
29
- """
30
- Tạo wrapper code để bắt stdout/stderr và đánh dấu return_value.
31
- """
32
  indented_code = textwrap.indent(user_code, " ")
33
  template = f'''import sys
34
  import json
@@ -62,7 +58,7 @@ if stdout.getvalue():
62
  if stderr.getvalue():
63
  print(stderr.getvalue(), end="", file=sys.stderr)
64
 
65
- # Đánh dấu return_value
66
  print("__RETURN_VALUE__:" + json.dumps(result_value))
67
  '''
68
  return template
@@ -70,14 +66,12 @@ print("__RETURN_VALUE__:" + json.dumps(result_value))
70
  # ----------------- Executor -----------------
71
 
72
  def execute_code_input_stream(code, attached_files):
73
- """Chạy code input + file đính kèm, stream log realtime"""
74
- # AST transform dòng cuối
75
  code = wrap_last_expr_with_return(code)
76
-
77
  final_code = wrap_code_for_execution(code)
78
 
79
  with tempfile.TemporaryDirectory() as temp_dir:
80
- # Lưu file đính kèm nếu có
81
  if attached_files is not None:
82
  for file in attached_files:
83
  dest = os.path.join(temp_dir, os.path.basename(file.name))
@@ -91,7 +85,6 @@ def execute_code_input_stream(code, attached_files):
91
 
92
  logger.debug(f"Generated code:\n{final_code}")
93
 
94
- # Chạy subprocess
95
  process = subprocess.Popen(
96
  ["python3", script_path],
97
  cwd=temp_dir,
@@ -101,6 +94,7 @@ def execute_code_input_stream(code, attached_files):
101
  bufsize=1,
102
  )
103
 
 
104
  return_value = None
105
  for line in process.stdout:
106
  line = line.rstrip("\n")
@@ -110,13 +104,12 @@ def execute_code_input_stream(code, attached_files):
110
  except Exception:
111
  return_value = None
112
  else:
113
- yield line
 
114
 
115
  process.wait()
116
- if return_value is not None:
117
- yield f"[Return Value] {return_value}"
118
- elif process.returncode != 0:
119
- yield f"[Process exited with code {process.returncode}]"
120
 
121
  # ----------------- Gradio UI -----------------
122
 
@@ -128,7 +121,7 @@ code_examples = [
128
  ]
129
 
130
  with gr.Blocks(theme=gr.themes.Default(primary_hue="red")) as demo:
131
- gr.Markdown("# 🔴 Python Executor (Stream Realtime + Return Last Expression)")
132
 
133
  with gr.Row():
134
  with gr.Column():
@@ -140,6 +133,7 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="red")) as demo:
140
 
141
  attached_files = gr.File(
142
  label="📎 Attach Files (optional)",
 
143
  file_count="multiple"
144
  )
145
 
@@ -154,13 +148,14 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="red")) as demo:
154
  )
155
 
156
  with gr.Column():
157
- log1 = gr.Textbox(label="Execution Log", lines=15)
 
158
 
159
  run_code_btn.click(
160
  execute_code_input_stream,
161
  [code_input, attached_files],
162
- log1,
163
  )
164
 
165
  if __name__ == "__main__":
166
- demo.launch()
 
13
  # ----------------- Helper Functions -----------------
14
 
15
  def wrap_last_expr_with_return(code: str) -> str:
16
+ """Nếu dòng cuối là expression, tự động chuyển thành return."""
 
 
17
  try:
18
  tree = ast.parse(code)
19
  if tree.body and isinstance(tree.body[-1], ast.Expr):
 
24
  return code
25
 
26
  def wrap_code_for_execution(user_code: str) -> str:
27
+ """Tạo wrapper code để bắt stdout/stderr và đánh dấu return_value."""
 
 
28
  indented_code = textwrap.indent(user_code, " ")
29
  template = f'''import sys
30
  import json
 
58
  if stderr.getvalue():
59
  print(stderr.getvalue(), end="", file=sys.stderr)
60
 
61
+ # Đánh dấu return_value riêng
62
  print("__RETURN_VALUE__:" + json.dumps(result_value))
63
  '''
64
  return template
 
66
  # ----------------- Executor -----------------
67
 
68
  def execute_code_input_stream(code, attached_files):
69
+ """Chạy code input + file đính kèm, trả log và return riêng"""
 
70
  code = wrap_last_expr_with_return(code)
 
71
  final_code = wrap_code_for_execution(code)
72
 
73
  with tempfile.TemporaryDirectory() as temp_dir:
74
+ # Lưu file đính kèm
75
  if attached_files is not None:
76
  for file in attached_files:
77
  dest = os.path.join(temp_dir, os.path.basename(file.name))
 
85
 
86
  logger.debug(f"Generated code:\n{final_code}")
87
 
 
88
  process = subprocess.Popen(
89
  ["python3", script_path],
90
  cwd=temp_dir,
 
94
  bufsize=1,
95
  )
96
 
97
+ log_lines = []
98
  return_value = None
99
  for line in process.stdout:
100
  line = line.rstrip("\n")
 
104
  except Exception:
105
  return_value = None
106
  else:
107
+ log_lines.append(line)
108
+ yield "\n".join(log_lines), "" # cập nhật log liên tục, return_value tạm trống
109
 
110
  process.wait()
111
+ # Cuối cùng trả return_value
112
+ yield "\n".join(log_lines), str(return_value) if return_value is not None else ""
 
 
113
 
114
  # ----------------- Gradio UI -----------------
115
 
 
121
  ]
122
 
123
  with gr.Blocks(theme=gr.themes.Default(primary_hue="red")) as demo:
124
+ gr.Markdown("# 🔴 Python Executor (Log & Return Value Separate)")
125
 
126
  with gr.Row():
127
  with gr.Column():
 
133
 
134
  attached_files = gr.File(
135
  label="📎 Attach Files (optional)",
136
+ file_types=[".txt", ".csv", ".json", ".py", ".md", ".xml", ".yaml", ".yml"],
137
  file_count="multiple"
138
  )
139
 
 
148
  )
149
 
150
  with gr.Column():
151
+ log_box = gr.Textbox(label="Execution Log", lines=15)
152
+ return_box = gr.Textbox(label="Return Value", lines=1)
153
 
154
  run_code_btn.click(
155
  execute_code_input_stream,
156
  [code_input, attached_files],
157
+ [log_box, return_box],
158
  )
159
 
160
  if __name__ == "__main__":
161
+ demo.launch()