akhaliq HF Staff commited on
Commit
655b364
·
verified ·
1 Parent(s): 6655081

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +260 -0
app.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import tempfile
4
+ import shutil
5
+ from pathlib import Path
6
+
7
+ # Helper functions
8
+ def read_file(file_path):
9
+ if not file_path:
10
+ return "", ""
11
+
12
+ try:
13
+ with open(file_path, 'r', encoding='utf-8') as f:
14
+ content = f.read()
15
+
16
+ # Get file extension for syntax highlighting
17
+ ext = os.path.splitext(file_path)[1].lstrip('.')
18
+ if ext in ['js', 'py', 'html', 'css', 'json', 'md', 'txt']:
19
+ language = ext
20
+ elif ext in ['jsx', 'tsx']:
21
+ language = 'javascript'
22
+ else:
23
+ language = 'text'
24
+
25
+ return content, language
26
+ except Exception as e:
27
+ return f"Error reading file: {str(e)}", "text"
28
+
29
+ def save_file(file_path, content):
30
+ if not file_path:
31
+ return "No file selected"
32
+
33
+ try:
34
+ with open(file_path, 'w', encoding='utf-8') as f:
35
+ f.write(content)
36
+ return f"Successfully saved to {file_path}"
37
+ except Exception as e:
38
+ return f"Error saving file: {str(e)}"
39
+
40
+ def create_file(folder_path, file_name):
41
+ if not folder_path or not file_name:
42
+ return "Please select a folder and provide a file name"
43
+
44
+ try:
45
+ file_path = os.path.join(folder_path, file_name)
46
+ with open(file_path, 'w', encoding='utf-8') as f:
47
+ f.write("")
48
+ return f"Created file: {file_path}"
49
+ except Exception as e:
50
+ return f"Error creating file: {str(e)}"
51
+
52
+ def render_html(code):
53
+ if not code:
54
+ return "<p>No HTML to render</p>"
55
+ return code
56
+
57
+ def run_python(code):
58
+ if not code:
59
+ return "No code to run"
60
+
61
+ try:
62
+ # Create a temporary file to execute the code
63
+ with tempfile.NamedTemporaryFile(suffix='.py', delete=False) as temp:
64
+ temp_name = temp.name
65
+ temp.write(code.encode('utf-8'))
66
+
67
+ # Redirect stdout to capture output
68
+ import sys
69
+ from io import StringIO
70
+ old_stdout = sys.stdout
71
+ redirected_output = StringIO()
72
+ sys.stdout = redirected_output
73
+
74
+ # Execute the code
75
+ with open(temp_name, 'r') as f:
76
+ exec(f.read())
77
+
78
+ # Restore stdout and get the output
79
+ sys.stdout = old_stdout
80
+ output = redirected_output.getvalue()
81
+
82
+ # Clean up
83
+ os.unlink(temp_name)
84
+
85
+ return output if output.strip() else "Code executed successfully (no output)"
86
+ except Exception as e:
87
+ return f"Error executing code: {str(e)}"
88
+
89
+ # Setup demo workspace
90
+ def setup_demo_workspace():
91
+ demo_dir = os.path.join(os.getcwd(), "demo_workspace")
92
+ if not os.path.exists(demo_dir):
93
+ os.makedirs(demo_dir)
94
+
95
+ # Create some example files
96
+ with open(os.path.join(demo_dir, "index.html"), "w") as f:
97
+ f.write("""<!DOCTYPE html>
98
+ <html>
99
+ <head>
100
+ <title>Example Page</title>
101
+ <link rel="stylesheet" href="style.css">
102
+ </head>
103
+ <body>
104
+ <h1>Hello, Gradio IDE!</h1>
105
+ <p>This is a sample HTML file.</p>
106
+ <script src="script.js"></script>
107
+ </body>
108
+ </html>""")
109
+
110
+ with open(os.path.join(demo_dir, "style.css"), "w") as f:
111
+ f.write("""body {
112
+ font-family: Arial, sans-serif;
113
+ margin: 0;
114
+ padding: 20px;
115
+ background-color: #f0f0f0;
116
+ }
117
+
118
+ h1 {
119
+ color: #333;
120
+ }""")
121
+
122
+ with open(os.path.join(demo_dir, "script.js"), "w") as f:
123
+ f.write("""console.log('Hello from JavaScript!');
124
+
125
+ document.addEventListener('DOMContentLoaded', function() {
126
+ console.log('Page loaded!');
127
+ });""")
128
+
129
+ with open(os.path.join(demo_dir, "example.py"), "w") as f:
130
+ f.write("""def greet(name):
131
+ return f"Hello, {name}!"
132
+
133
+ # Test the function
134
+ print(greet("World"))
135
+
136
+ # Some example code
137
+ for i in range(5):
138
+ print(f"Count: {i}")""")
139
+
140
+ return demo_dir
141
+
142
+ # Create the Gradio interface
143
+ def create_ide():
144
+ # Setup demo workspace
145
+ workspace_dir = setup_demo_workspace()
146
+
147
+ with gr.Blocks(title="Gradio IDE") as app:
148
+ gr.Markdown("# Gradio IDE")
149
+
150
+ with gr.Row():
151
+ with gr.Column(scale=1):
152
+ gr.Markdown("### File Explorer")
153
+ file_explorer = gr.FileExplorer(
154
+ root_dir=workspace_dir,
155
+ height=500,
156
+ label="Files"
157
+ )
158
+
159
+ with gr.Row():
160
+ new_file_name = gr.Textbox(label="New File Name")
161
+ create_btn = gr.Button("Create File")
162
+
163
+ current_folder = gr.Textbox(label="Current Folder", interactive=False)
164
+ status = gr.Textbox(label="Status", interactive=False)
165
+
166
+ with gr.Column(scale=2):
167
+ current_file = gr.Textbox(label="Current File", interactive=False)
168
+ code_editor = gr.Code(
169
+ label="Code Editor",
170
+ language="python",
171
+ height=500,
172
+ elem_id="code-editor"
173
+ )
174
+
175
+ with gr.Row():
176
+ save_btn = gr.Button("Save File")
177
+ run_btn = gr.Button("Run Code")
178
+
179
+ output_console = gr.Textbox(label="Output Console", interactive=False, lines=6)
180
+
181
+ with gr.Tab("HTML Preview"):
182
+ html_preview = gr.HTML(label="Preview")
183
+ render_btn = gr.Button("Render HTML")
184
+
185
+ with gr.Tab("Help"):
186
+ gr.Markdown("""
187
+ ## How to use the Gradio IDE
188
+
189
+ 1. Browse files using the File Explorer on the left
190
+ 2. Click on a file to open it in the Code Editor
191
+ 3. Edit the file content as needed
192
+ 4. Click "Save File" to save your changes
193
+ 5. For HTML files, go to the HTML Preview tab and click "Render HTML"
194
+ 6. For Python files, click "Run Code" to execute and see the output
195
+ 7. To create a new file, enter a name and click "Create File"
196
+
197
+ Enjoy coding!
198
+ """)
199
+
200
+ # Event handlers
201
+ def update_file_selection(selected_path):
202
+ path = selected_path[0] if selected_path else ""
203
+ if os.path.isdir(path):
204
+ return "", "", path, f"Selected folder: {path}"
205
+
206
+ content, language = read_file(path)
207
+ folder = os.path.dirname(path) if path else ""
208
+ return content, language, folder, f"Opened file: {path}"
209
+
210
+ file_explorer.change(
211
+ update_file_selection,
212
+ inputs=[file_explorer],
213
+ outputs=[code_editor, code_editor.language, current_folder, status]
214
+ )
215
+
216
+ def update_current_file(selected_path):
217
+ if selected_path and os.path.isfile(selected_path[0]):
218
+ return selected_path[0]
219
+ return ""
220
+
221
+ file_explorer.change(
222
+ update_current_file,
223
+ inputs=[file_explorer],
224
+ outputs=[current_file]
225
+ )
226
+
227
+ save_btn.click(
228
+ save_file,
229
+ inputs=[current_file, code_editor],
230
+ outputs=[status]
231
+ )
232
+
233
+ create_btn.click(
234
+ create_file,
235
+ inputs=[current_folder, new_file_name],
236
+ outputs=[status]
237
+ ).then(
238
+ lambda: gr.update(value=""),
239
+ outputs=[new_file_name]
240
+ )
241
+
242
+ run_btn.click(
243
+ run_python,
244
+ inputs=[code_editor],
245
+ outputs=[output_console]
246
+ )
247
+
248
+ render_btn.click(
249
+ render_html,
250
+ inputs=[code_editor],
251
+ outputs=[html_preview]
252
+ )
253
+
254
+ return app
255
+
256
+ # Create and launch the app
257
+ ide_app = create_ide()
258
+
259
+ if __name__ == "__main__":
260
+ ide_app.launch()