minhvh commited on
Commit
8e109e1
·
verified ·
1 Parent(s): b270653

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -51
app.py CHANGED
@@ -6,23 +6,76 @@ import textwrap
6
  import os
7
  import ast
8
  import zipfile
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  def execute_code_input(code, timeout=30):
11
  """Chạy code nhập trực tiếp"""
12
- # Kiểm tra cú pháp
 
 
13
  try:
14
  ast.parse(code)
15
  except SyntaxError as e:
16
- return f"SyntaxError: {e.msg}\nLine {e.lineno}: {e.text or ''}", ""
17
-
18
- # Indent code
 
19
  indented_code = textwrap.indent(code, ' ')
20
-
21
  template = '''import sys
22
  import json
23
  from io import StringIO
24
  import contextlib
25
-
26
  @contextlib.contextmanager
27
  def capture_output():
28
  stdout, stderr = StringIO(), StringIO()
@@ -32,17 +85,14 @@ def capture_output():
32
  yield stdout, stderr
33
  finally:
34
  sys.stdout, sys.stderr = old_out, old_err
35
-
36
  def execute_code():
37
  {}
38
-
39
  with capture_output() as (stdout, stderr):
40
  try:
41
  result_value = execute_code()
42
  except Exception as e:
43
  print(f"Error: {{str(e)}}", file=sys.stderr)
44
  result_value = None
45
-
46
  result = {{
47
  'stdout': stdout.getvalue(),
48
  'stderr': stderr.getvalue(),
@@ -50,13 +100,12 @@ result = {{
50
  }}
51
  print(json.dumps(result))
52
  '''
53
-
54
  final_code = template.format(indented_code)
55
-
56
  with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as temp_file:
57
  temp_file.write(final_code)
58
  temp_file.flush()
59
-
60
  try:
61
  result = subprocess.run(
62
  ['python3', temp_file.name],
@@ -64,14 +113,14 @@ print(json.dumps(result))
64
  text=True,
65
  timeout=timeout
66
  )
67
-
68
  try:
69
  output = json.loads(result.stdout)
70
  stdout = output.get('stdout', '')
71
  stderr = output.get('stderr', '')
72
  return_value = output.get('return_value', None)
73
  exit_code = result.returncode
74
-
75
  log_lines = []
76
  if stdout.strip():
77
  log_lines.append(stdout.rstrip())
@@ -79,33 +128,42 @@ print(json.dumps(result))
79
  log_lines.append(stderr.rstrip())
80
  log_lines.append(f"Exit code: {exit_code}")
81
  log_text = "\n".join(log_lines)
82
-
83
- return_display = str(return_value) if return_value is not None else ""
84
- return log_text, return_display
85
-
86
  except json.JSONDecodeError:
87
- return f"Error: Failed to parse result", ""
88
-
 
 
89
  except subprocess.TimeoutExpired:
90
- return f"Error: Execution timed out after {timeout} seconds", ""
 
 
91
  except Exception as e:
92
- return f"Error: {str(e)}", ""
 
 
93
  finally:
94
  os.unlink(temp_file.name)
95
 
96
  def execute_uploaded_files(files, main_file, timeout=30):
97
  """Chạy file upload"""
98
  if not files:
99
- return "Error: No files uploaded", ""
100
-
 
 
101
  with tempfile.TemporaryDirectory() as temp_dir:
102
- # Xử lý file upload
103
  if len(files) == 1 and files[0].name.endswith('.zip'):
104
  try:
105
  with zipfile.ZipFile(files[0].name, 'r') as zip_ref:
106
  zip_ref.extractall(temp_dir)
107
  except Exception as e:
108
- return f"Error extracting zip: {str(e)}", ""
 
 
109
  else:
110
  for file in files:
111
  filename = os.path.basename(file.name)
@@ -113,12 +171,13 @@ def execute_uploaded_files(files, main_file, timeout=30):
113
  with open(dest_path, 'wb') as f:
114
  with open(file.name, 'rb') as src:
115
  f.write(src.read())
116
-
117
- # Kiểm tra file chính
118
  main_path = os.path.join(temp_dir, main_file)
119
  if not os.path.exists(main_path):
120
- return f"Error: Main file '{main_file}' not found", ""
121
-
 
 
122
  try:
123
  result = subprocess.run(
124
  ['python3', main_path],
@@ -127,11 +186,11 @@ def execute_uploaded_files(files, main_file, timeout=30):
127
  text=True,
128
  timeout=timeout
129
  )
130
-
131
  stdout = result.stdout if result.stdout else ""
132
  stderr = result.stderr if result.stderr else ""
133
  exit_code = result.returncode
134
-
135
  log_lines = []
136
  if stdout.strip():
137
  log_lines.append(stdout.rstrip())
@@ -139,13 +198,18 @@ def execute_uploaded_files(files, main_file, timeout=30):
139
  log_lines.append(stderr.rstrip())
140
  log_lines.append(f"Exit code: {exit_code}")
141
  log_text = "\n".join(log_lines)
142
-
 
143
  return log_text, ""
144
-
145
  except subprocess.TimeoutExpired:
146
- return f"Error: Execution timed out after {timeout} seconds", ""
 
 
147
  except Exception as e:
148
- return f"Error: {str(e)}", ""
 
 
149
 
150
  # Examples
151
  code_examples = [
@@ -158,46 +222,66 @@ file_examples = [
158
  [["examples/hello.py"], "hello.py", 30],
159
  ]
160
 
161
- # Giao diện với 2 tab
162
  with gr.Blocks(theme=gr.themes.Default(primary_hue="red")) as demo:
163
  gr.Markdown("# 🔴 Python Code Executor")
164
  gr.Markdown("Run Python code - Choose your preferred method")
165
-
166
  with gr.Tabs():
167
  # Tab 1: Code trực tiếp
168
  with gr.Tab("⌨️ Direct Code Input"):
169
  with gr.Row():
170
  with gr.Column():
171
  code_input = gr.Code(
172
- label="Python Code",
173
  language="python",
174
  interactive=True
175
  )
 
 
 
 
 
 
176
  timeout1 = gr.Slider(1, 60, value=30, label="Timeout (seconds)")
177
  run_code_btn = gr.Button("▶️ Run Code", variant="primary")
178
  gr.Examples(code_examples, [code_input, timeout1])
179
-
180
  with gr.Column():
181
  log1 = gr.Textbox(label="Execution Log", lines=10)
182
  result1 = gr.Textbox(label="Return Value")
183
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  run_code_btn.click(
185
- execute_code_input,
186
- [code_input, timeout1],
187
- [log1, result1]
188
  )
189
-
190
  # Tab 2: Upload file
191
  with gr.Tab("📁 Upload Files"):
192
  with gr.Row():
193
  with gr.Column():
194
  files_upload = gr.File(
195
- label="Upload Python Files (.py) or ZIP",
196
  file_types=[".py", ".zip"],
197
  file_count="multiple"
198
  )
199
  main_file_input = gr.Textbox(
200
- label="Main File Name (with .py)",
201
  value="main.py",
202
  placeholder="e.g., main.py"
203
  )
@@ -206,16 +290,34 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="red")) as demo:
206
  gr.Markdown("### 📝 Instructions:")
207
  gr.Markdown("- Upload multiple .py files and specify main file")
208
  gr.Markdown("- Or upload a single .zip file with all Python files")
209
-
210
  with gr.Column():
211
  log2 = gr.Textbox(label="Execution Log", lines=10)
212
  result2 = gr.Textbox(label="Return Value")
213
-
214
  run_files_btn.click(
215
- execute_uploaded_files,
216
- [files_upload, main_file_input, timeout2],
217
  [log2, result2]
218
  )
219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  if __name__ == "__main__":
221
  demo.launch()
 
6
  import os
7
  import ast
8
  import zipfile
9
+ from datetime import datetime
10
+
11
+ # Lưu trữ lịch sử thực thi
12
+ execution_history = []
13
+
14
+ def add_to_history(entry_type, input_data, log, return_value):
15
+ """Thêm bản ghi vào lịch sử"""
16
+ execution_history.append({
17
+ "id": len(execution_history),
18
+ "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
19
+ "type": entry_type,
20
+ "input": input_data,
21
+ "log": log,
22
+ "return_value": return_value
23
+ })
24
+
25
+ def get_history_choices():
26
+ """Lấy danh sách lịch sử để hiển thị trong dropdown"""
27
+ choices = []
28
+ for entry in reversed(execution_history): # Mới nhất trước
29
+ preview = entry['input'][:50] + "..." if len(entry['input']) > 50 else entry['input']
30
+ choices.append(f"[{entry['time']}] {entry['type']}: {preview}")
31
+ return choices
32
+
33
+ def load_history_item(selected):
34
+ """Tải code từ lịch sử khi chọn item"""
35
+ if not selected or not execution_history:
36
+ return ""
37
+
38
+ # Parse selected string để tìm ID
39
+ try:
40
+ time_part = selected.split(']')[0][1:] # Lấy thời gian
41
+ for entry in execution_history:
42
+ if entry['time'] == time_part or selected.startswith(f"[{entry['time']}]"):
43
+ return entry['input']
44
+ except:
45
+ pass
46
+ return ""
47
+
48
+ def format_history():
49
+ """Định dạng lịch sử để hiển thị"""
50
+ if not execution_history:
51
+ return "No history yet."
52
+ lines = []
53
+ for entry in reversed(execution_history): # Mới nhất trước
54
+ lines.append(f"[{entry['time']}] {entry['type']}")
55
+ lines.append(f"Input: {entry['input']}")
56
+ lines.append(f"Output:\n{entry['log']}")
57
+ if entry['return_value']:
58
+ lines.append(f"Return: {entry['return_value']}")
59
+ lines.append("-" * 50)
60
+ return "\n".join(lines)
61
 
62
  def execute_code_input(code, timeout=30):
63
  """Chạy code nhập trực tiếp"""
64
+ if not code.strip():
65
+ return "Error: Empty code", ""
66
+
67
  try:
68
  ast.parse(code)
69
  except SyntaxError as e:
70
+ error_msg = f"SyntaxError: {e.msg}\nLine {e.lineno}: {e.text or ''}"
71
+ add_to_history("Direct Code", code, error_msg, "")
72
+ return error_msg, ""
73
+
74
  indented_code = textwrap.indent(code, ' ')
 
75
  template = '''import sys
76
  import json
77
  from io import StringIO
78
  import contextlib
 
79
  @contextlib.contextmanager
80
  def capture_output():
81
  stdout, stderr = StringIO(), StringIO()
 
85
  yield stdout, stderr
86
  finally:
87
  sys.stdout, sys.stderr = old_out, old_err
 
88
  def execute_code():
89
  {}
 
90
  with capture_output() as (stdout, stderr):
91
  try:
92
  result_value = execute_code()
93
  except Exception as e:
94
  print(f"Error: {{str(e)}}", file=sys.stderr)
95
  result_value = None
 
96
  result = {{
97
  'stdout': stdout.getvalue(),
98
  'stderr': stderr.getvalue(),
 
100
  }}
101
  print(json.dumps(result))
102
  '''
 
103
  final_code = template.format(indented_code)
104
+
105
  with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as temp_file:
106
  temp_file.write(final_code)
107
  temp_file.flush()
108
+
109
  try:
110
  result = subprocess.run(
111
  ['python3', temp_file.name],
 
113
  text=True,
114
  timeout=timeout
115
  )
116
+
117
  try:
118
  output = json.loads(result.stdout)
119
  stdout = output.get('stdout', '')
120
  stderr = output.get('stderr', '')
121
  return_value = output.get('return_value', None)
122
  exit_code = result.returncode
123
+
124
  log_lines = []
125
  if stdout.strip():
126
  log_lines.append(stdout.rstrip())
 
128
  log_lines.append(stderr.rstrip())
129
  log_lines.append(f"Exit code: {exit_code}")
130
  log_text = "\n".join(log_lines)
131
+
132
+ add_to_history("Direct Code", code, log_text, str(return_value) if return_value else "")
133
+ return log_text, str(return_value) if return_value else ""
134
+
135
  except json.JSONDecodeError:
136
+ error_msg = "Error: Failed to parse result"
137
+ add_to_history("Direct Code", code, error_msg, "")
138
+ return error_msg, ""
139
+
140
  except subprocess.TimeoutExpired:
141
+ error_msg = f"Error: Execution timed out after {timeout} seconds"
142
+ add_to_history("Direct Code", code, error_msg, "")
143
+ return error_msg, ""
144
  except Exception as e:
145
+ error_msg = f"Error: {str(e)}"
146
+ add_to_history("Direct Code", code, error_msg, "")
147
+ return error_msg, ""
148
  finally:
149
  os.unlink(temp_file.name)
150
 
151
  def execute_uploaded_files(files, main_file, timeout=30):
152
  """Chạy file upload"""
153
  if not files:
154
+ error_msg = "Error: No files uploaded"
155
+ add_to_history("Uploaded Files", main_file, error_msg, "")
156
+ return error_msg, ""
157
+
158
  with tempfile.TemporaryDirectory() as temp_dir:
 
159
  if len(files) == 1 and files[0].name.endswith('.zip'):
160
  try:
161
  with zipfile.ZipFile(files[0].name, 'r') as zip_ref:
162
  zip_ref.extractall(temp_dir)
163
  except Exception as e:
164
+ error_msg = f"Error extracting zip: {str(e)}"
165
+ add_to_history("Uploaded ZIP", main_file, error_msg, "")
166
+ return error_msg, ""
167
  else:
168
  for file in files:
169
  filename = os.path.basename(file.name)
 
171
  with open(dest_path, 'wb') as f:
172
  with open(file.name, 'rb') as src:
173
  f.write(src.read())
174
+
 
175
  main_path = os.path.join(temp_dir, main_file)
176
  if not os.path.exists(main_path):
177
+ error_msg = f"Error: Main file '{main_file}' not found"
178
+ add_to_history("Uploaded Files", main_file, error_msg, "")
179
+ return error_msg, ""
180
+
181
  try:
182
  result = subprocess.run(
183
  ['python3', main_path],
 
186
  text=True,
187
  timeout=timeout
188
  )
189
+
190
  stdout = result.stdout if result.stdout else ""
191
  stderr = result.stderr if result.stderr else ""
192
  exit_code = result.returncode
193
+
194
  log_lines = []
195
  if stdout.strip():
196
  log_lines.append(stdout.rstrip())
 
198
  log_lines.append(stderr.rstrip())
199
  log_lines.append(f"Exit code: {exit_code}")
200
  log_text = "\n".join(log_lines)
201
+
202
+ add_to_history("Uploaded Files", main_file, log_text, "")
203
  return log_text, ""
204
+
205
  except subprocess.TimeoutExpired:
206
+ error_msg = f"Error: Execution timed out after {timeout} seconds"
207
+ add_to_history("Uploaded Files", main_file, error_msg, "")
208
+ return error_msg, ""
209
  except Exception as e:
210
+ error_msg = f"Error: {str(e)}"
211
+ add_to_history("Uploaded Files", main_file, error_msg, "")
212
+ return error_msg, ""
213
 
214
  # Examples
215
  code_examples = [
 
222
  [["examples/hello.py"], "hello.py", 30],
223
  ]
224
 
225
+ # Giao diện với 3 tab
226
  with gr.Blocks(theme=gr.themes.Default(primary_hue="red")) as demo:
227
  gr.Markdown("# 🔴 Python Code Executor")
228
  gr.Markdown("Run Python code - Choose your preferred method")
229
+
230
  with gr.Tabs():
231
  # Tab 1: Code trực tiếp
232
  with gr.Tab("⌨️ Direct Code Input"):
233
  with gr.Row():
234
  with gr.Column():
235
  code_input = gr.Code(
236
+ label="Python Code",
237
  language="python",
238
  interactive=True
239
  )
240
+ # Dropdown lịch sử
241
+ history_dropdown = gr.Dropdown(
242
+ choices=[],
243
+ label="History",
244
+ interactive=True
245
+ )
246
  timeout1 = gr.Slider(1, 60, value=30, label="Timeout (seconds)")
247
  run_code_btn = gr.Button("▶️ Run Code", variant="primary")
248
  gr.Examples(code_examples, [code_input, timeout1])
249
+
250
  with gr.Column():
251
  log1 = gr.Textbox(label="Execution Log", lines=10)
252
  result1 = gr.Textbox(label="Return Value")
253
+
254
+ # Khi chọn item từ history
255
+ history_dropdown.change(
256
+ load_history_item,
257
+ [history_dropdown],
258
+ [code_input]
259
+ )
260
+
261
+ # Khi chạy code, cập nhật lại history dropdown
262
+ def run_and_update_history(code, timeout):
263
+ log, result = execute_code_input(code, timeout)
264
+ # Cập nhật dropdown choices
265
+ choices = get_history_choices()
266
+ return log, result, gr.update(choices=choices)
267
+
268
  run_code_btn.click(
269
+ run_and_update_history,
270
+ [code_input, timeout1],
271
+ [log1, result1, history_dropdown]
272
  )
273
+
274
  # Tab 2: Upload file
275
  with gr.Tab("📁 Upload Files"):
276
  with gr.Row():
277
  with gr.Column():
278
  files_upload = gr.File(
279
+ label="Upload Python Files (.py) or ZIP",
280
  file_types=[".py", ".zip"],
281
  file_count="multiple"
282
  )
283
  main_file_input = gr.Textbox(
284
+ label="Main File Name (with .py)",
285
  value="main.py",
286
  placeholder="e.g., main.py"
287
  )
 
290
  gr.Markdown("### 📝 Instructions:")
291
  gr.Markdown("- Upload multiple .py files and specify main file")
292
  gr.Markdown("- Or upload a single .zip file with all Python files")
293
+
294
  with gr.Column():
295
  log2 = gr.Textbox(label="Execution Log", lines=10)
296
  result2 = gr.Textbox(label="Return Value")
297
+
298
  run_files_btn.click(
299
+ execute_uploaded_files,
300
+ [files_upload, main_file_input, timeout2],
301
  [log2, result2]
302
  )
303
 
304
+ # Tab 3: History
305
+ with gr.Tab("🕒 History"):
306
+ history_output = gr.Textbox(label="Execution History", lines=20, interactive=False)
307
+ refresh_btn = gr.Button("🔄 Refresh History")
308
+
309
+ def refresh_history():
310
+ return format_history()
311
+
312
+ refresh_btn.click(refresh_history, None, history_output)
313
+ demo.load(refresh_history, None, history_output)
314
+
315
+ # Load history choices khi khởi động
316
+ demo.load(
317
+ lambda: gr.update(choices=get_history_choices()),
318
+ None,
319
+ [history_dropdown]
320
+ )
321
+
322
  if __name__ == "__main__":
323
  demo.launch()