akhaliq HF Staff commited on
Commit
c988e34
·
verified ·
1 Parent(s): 240812a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -146
app.py CHANGED
@@ -1,157 +1,85 @@
1
  import gradio as gr
2
- import subprocess
3
- import tempfile
4
- import os
5
  import sys
6
- from pathlib import Path
 
7
 
8
- def execute_code(code, language):
9
- """Execute code and return the output and any errors."""
10
- with tempfile.TemporaryDirectory() as tmp_dir:
11
- if language == "python":
12
- file_path = Path(tmp_dir) / "script.py"
13
- with open(file_path, "w") as f:
14
- f.write(code)
15
-
16
- # Execute the code and capture output
17
- try:
18
- result = subprocess.run(
19
- [sys.executable, file_path],
20
- capture_output=True,
21
- text=True,
22
- timeout=10 # 10 second timeout for safety
23
- )
24
- stdout = result.stdout
25
- stderr = result.stderr
26
-
27
- if result.returncode != 0:
28
- return f"Error:\n{stderr}\n\nOutput:\n{stdout}"
29
- return stdout
30
- except subprocess.TimeoutExpired:
31
- return "Execution timed out (limit: 10 seconds)"
32
- except Exception as e:
33
- return f"Error: {e}"
34
-
35
- elif language == "javascript":
36
- file_path = Path(tmp_dir) / "script.js"
37
- with open(file_path, "w") as f:
38
- f.write(code)
39
-
40
- try:
41
- result = subprocess.run(
42
- ["node", file_path],
43
- capture_output=True,
44
- text=True,
45
- timeout=10
46
- )
47
- stdout = result.stdout
48
- stderr = result.stderr
49
-
50
- if result.returncode != 0:
51
- return f"Error:\n{stderr}\n\nOutput:\n{stdout}"
52
- return stdout
53
- except subprocess.TimeoutExpired:
54
- return "Execution timed out (limit: 10 seconds)"
55
- except FileNotFoundError:
56
- return "Error: Node.js is not installed or not in PATH"
57
- except Exception as e:
58
- return f"Error: {e}"
59
-
60
- else:
61
- return f"Language '{language}' is not supported"
62
 
63
- # Example code for each language
64
- python_example = """# Python Example
65
- def fibonacci(n):
66
- if n <= 0:
67
- return []
68
- elif n == 1:
69
- return [0]
70
- elif n == 2:
71
- return [0, 1]
72
-
73
- fib = [0, 1]
74
- for i in range(2, n):
75
- fib.append(fib[i-1] + fib[i-2])
76
-
77
- return fib
78
 
79
- # Generate first 10 Fibonacci numbers
80
- result = fibonacci(10)
81
- print(f"First 10 Fibonacci numbers: {result}")
82
- """
83
 
84
- js_example = """// JavaScript Example
85
- function fibonacci(n) {
86
- if (n <= 0) return [];
87
- if (n === 1) return [0];
88
- if (n === 2) return [0, 1];
89
-
90
- const fib = [0, 1];
91
- for (let i = 2; i < n; i++) {
92
- fib.push(fib[i-1] + fib[i-2]);
93
- }
94
-
95
- return fib;
96
- }
97
 
98
- // Generate first 10 Fibonacci numbers
99
- const result = fibonacci(10);
100
- console.log(`First 10 Fibonacci numbers: ${result}`);
101
- """
 
 
 
 
102
 
103
- # Create the Gradio interface
104
- with gr.Blocks(title="Simple Code IDE") as app:
105
- gr.Markdown("# Simple Code IDE")
106
- gr.Markdown("Write, run, and see the output of your code!")
107
 
108
- with gr.Row():
109
- with gr.Column(scale=2):
110
- language = gr.Dropdown(
111
- ["python", "javascript"],
112
- label="Programming Language",
113
- value="python"
114
- )
115
-
116
- code_input = gr.Code(
117
- label="Code Editor",
118
- language="python",
119
- value=python_example
120
- )
121
-
122
- # Update code example when language changes
123
- def update_example(lang):
124
- if lang == "python":
125
- return python_example, "python"
126
- elif lang == "javascript":
127
- return js_example, "javascript"
128
-
129
- language.change(
130
- update_example,
131
- inputs=language,
132
- outputs=[code_input, code_input.language]
133
- )
134
-
135
- run_button = gr.Button("Run Code", variant="primary")
136
-
137
- with gr.Column(scale=1):
138
- output = gr.Textbox(label="Output", lines=20)
139
 
140
- run_button.click(
141
- execute_code,
142
- inputs=[code_input, language],
143
- outputs=output
144
- )
145
-
146
- gr.Markdown("""
147
- ## Instructions
148
- 1. Select your programming language
149
- 2. Write or edit the code in the editor
150
- 3. Click "Run Code" to execute and see the output
151
-
152
- Note: Code execution is limited to 10 seconds for safety.
153
- """)
 
 
 
 
 
 
 
 
154
 
155
- # Launch the app
156
- if __name__ == "__main__":
157
- app.launch()
 
1
  import gradio as gr
2
+ import io
 
 
3
  import sys
4
+ import matplotlib.pyplot as plt
5
+ from PIL import Image
6
 
7
+ # Function to execute code and capture output
8
+ def run_code(code, namespace):
9
+ output = io.StringIO()
10
+ sys.stdout = output
11
+ images = []
12
+ try:
13
+ exec(code, namespace)
14
+ # Capture any matplotlib plots
15
+ figs = [plt.figure(i) for i in plt.get_fignums()]
16
+ for fig in figs:
17
+ buf = io.BytesIO()
18
+ fig.savefig(buf, format='png')
19
+ buf.seek(0)
20
+ img = Image.open(buf)
21
+ images.append(img)
22
+ plt.close('all')
23
+ except Exception as e:
24
+ print(f"Error: {e}")
25
+ sys.stdout = sys.__stdout__
26
+ return output.getvalue(), images, namespace
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ # Function to load code for the selected file
29
+ def select_file(file_name, files):
30
+ return files[file_name]
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+ # Function to update the files state when code is edited
33
+ def update_code(code, file_name, files):
34
+ files[file_name] = code
35
+ return files
36
 
37
+ # Function to add a new file
38
+ def add_file(files):
39
+ new_file_name = f"file_{len(files)}.py"
40
+ files[new_file_name] = "# New file"
41
+ return files, list(files.keys()), new_file_name
 
 
 
 
 
 
 
 
42
 
43
+ # Function to delete the current file
44
+ def delete_file(file_name, files):
45
+ if len(files) > 1: # Prevent deleting the last file
46
+ del files[file_name]
47
+ new_file_name = list(files.keys())[0]
48
+ return files, list(files.keys()), new_file_name, files[new_file_name]
49
+ else:
50
+ return files, list(files.keys()), file_name, files[file_name]
51
 
52
+ # Build the interface
53
+ with gr.Blocks(title="Simple IDE with Gradio") as demo:
54
+ # Initial state
55
+ initial_files = {"main.py": "# Write your code here\nprint('Hello, World!')"}
56
 
57
+ # State components
58
+ files = gr.State(initial_files)
59
+ namespace = gr.State({})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
+ # UI components
62
+ file_selector = gr.Dropdown(choices=list(initial_files.keys()), label="Select File")
63
+ code_input = gr.Code(label="Code Editor", language="python", value=initial_files["main.py"])
64
+ with gr.Row():
65
+ run_button = gr.Button("Run")
66
+ add_file_button = gr.Button("Add File")
67
+ delete_file_button = gr.Button("Delete File")
68
+ clear_button = gr.Button("Clear Output")
69
+ reset_button = gr.Button("Reset Namespace")
70
+ output_display = gr.Textbox(label="Output")
71
+ image_gallery = gr.Gallery(label="Plots")
72
+
73
+ # Event handlers
74
+ file_selector.change(select_file, inputs=[file_selector, files], outputs=code_input)
75
+ code_input.change(update_code, inputs=[code_input, file_selector, files], outputs=files)
76
+ add_file_button.click(add_file, inputs=files, outputs=[files, file_selector, file_selector])
77
+ delete_file_button.click(delete_file, inputs=[file_selector, files],
78
+ outputs=[files, file_selector, file_selector, code_input])
79
+ run_button.click(run_code, inputs=[code_input, namespace],
80
+ outputs=[output_display, image_gallery, namespace])
81
+ clear_button.click(lambda: ("", []), outputs=[output_display, image_gallery])
82
+ reset_button.click(lambda: ({}, "", []), outputs=[namespace, output_display, image_gallery])
83
 
84
+ # Launch the interface
85
+ demo.launch()