File size: 13,525 Bytes
6e19f63
 
 
 
1368c37
 
ece917e
 
 
1368c37
8be8236
83a7163
1368c37
83a7163
da5bcdc
ece917e
83a7163
da5bcdc
83a7163
 
 
 
1368c37
83a7163
 
 
1368c37
 
da5bcdc
83a7163
da5bcdc
 
1368c37
6e19f63
 
 
 
 
1368c37
83a7163
1368c37
 
 
83a7163
 
1368c37
 
6e19f63
1368c37
83a7163
 
 
 
 
 
 
6e19f63
83a7163
da5bcdc
 
1368c37
44abb7c
83a7163
 
6e19f63
da5bcdc
83a7163
 
 
 
da5bcdc
44abb7c
ece917e
1368c37
6e19f63
da5bcdc
6e19f63
 
 
 
 
 
 
 
 
 
8be8236
 
 
 
 
 
 
 
 
 
 
1368c37
 
 
 
83a7163
 
 
1368c37
83a7163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1368c37
83a7163
1368c37
 
 
 
 
 
 
83a7163
 
8be8236
83a7163
6e19f63
83a7163
ece917e
83a7163
 
1368c37
83a7163
 
 
 
1368c37
83a7163
 
 
1368c37
83a7163
 
ece917e
 
83a7163
ece917e
 
83a7163
 
 
ece917e
83a7163
ece917e
83a7163
1368c37
 
83a7163
 
 
1368c37
 
 
 
 
83a7163
1368c37
 
83a7163
 
 
 
1368c37
 
 
83a7163
1368c37
fc0b4cb
83a7163
 
ece917e
6e19f63
83a7163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be8236
1368c37
 
 
 
ece917e
83a7163
1368c37
57a2c17
1368c37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83a7163
 
1368c37
 
 
 
 
 
9e8ab62
83a7163
 
 
 
8be8236
1368c37
 
ece917e
1368c37
ece917e
1368c37
44abb7c
57a2c17
83a7163
ece917e
 
 
 
 
 
 
83a7163
 
1368c37
83a7163
1368c37
ece917e
1368c37
6e19f63
ece917e
 
6e19f63
83a7163
 
 
 
 
 
 
ece917e
1368c37
ece917e
 
 
1368c37
57a2c17
ece917e
83a7163
 
1368c37
83a7163
1368c37
ece917e
1368c37
 
83a7163
1368c37
 
ece917e
1368c37
 
 
 
83a7163
 
1368c37
da5bcdc
1368c37
 
 
ece917e
1368c37
ece917e
1368c37
8be8236
83a7163
 
1368c37
83a7163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e8ab62
1368c37
 
83a7163
1368c37
ece917e
83a7163
1368c37
44abb7c
 
1368c37
 
83a7163
 
9e8ab62
7928d62
fc0b4cb
83a7163
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import gradio as gr
import requests
import re
import os
import subprocess
import tempfile
import sys
import json
import time
import atexit

# Print Python version and gradio version for debugging
print(f"Python version: {sys.version}")
print(f"Gradio version: {gr.__version__}")

# Track running processes for cleanup
running_process = None

# Clean up running process on exit
def cleanup_process():
    global running_process
    if running_process and running_process.poll() is None:
        try:
            running_process.terminate()
            running_process.wait(timeout=5)
            print(f"Terminated process {running_process.pid}")
        except Exception as e:
            print(f"Error terminating process: {e}")

atexit.register(cleanup_process)

def call_openai_api(api_key, prompt):
    """Call OpenAI API to generate Gradio app code and requirements"""
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    
    system_prompt = """You are an expert at creating Python applications with Gradio.
Create a complete, standalone Gradio application based on the user's prompt.

Provide your response in the following JSON format:
{
    "app_code": "# Python code here...",
    "requirements": ["gradio==3.32.0", "other_packages"],
    "description": "Brief description of what the app does"
}

Important guidelines:
1. The app_code should be a complete Gradio application
2. Use ONLY gr.Interface (NOT gr.Blocks)
3. Always include server_name="0.0.0.0" and server_port=7861 in the launch parameters
4. First requirement must be exactly "gradio==3.32.0"
5. Keep the app simple and focused on the user's request
6. DO NOT use any flagging callbacks
7. DO NOT create or use any directories or file paths

Example:
```python
import gradio as gr
import numpy as np

def process(input_value):
    return input_value * 2

demo = gr.Interface(
    fn=process,
    inputs=gr.Number(label="Input"),
    outputs=gr.Number(label="Output"),
    title="Number Doubler"
)

demo.launch(server_name="0.0.0.0", server_port=7861)
```
"""
    
    data = {
        "model": "gpt-4o",
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.2,
        "max_tokens": 4000
    }
    
    try:
        response = requests.post(
            "https://api.openai.com/v1/chat/completions",
            headers=headers,
            json=data
        )
        
        if response.status_code != 200:
            return None, f"API Error: {response.status_code} - {response.text}"
        
        result = response.json()
        content = result["choices"][0]["message"]["content"]
        
        # Try to parse the JSON response
        try:
            # Look for JSON object
            json_pattern = r'({[\s\S]*})'
            json_match = re.search(json_pattern, content)
            
            if json_match:
                json_str = json_match.group(1)
                app_info = json.loads(json_str)
            else:
                # Try to extract code and requirements manually
                code_pattern = r'```python\s*([\s\S]*?)```'
                code_match = re.search(code_pattern, content)
                
                if not code_match:
                    return None, "No code found in the response"
                
                code = code_match.group(1)
                
                # Extract requirements from imports
                req_pattern = r'import\s+([a-zA-Z0-9_]+)'
                req_matches = re.findall(req_pattern, code)
                
                requirements = ["gradio==3.32.0"]
                for module in req_matches:
                    if module != "gradio" and module not in requirements and module not in ["os", "sys"]:
                        requirements.append(module)
                
                app_info = {
                    "app_code": code,
                    "requirements": requirements,
                    "description": "Generated Gradio application"
                }
            
            # Clean up the code if needed
            if "```python" in app_info["app_code"]:
                code_pattern = r'```python\s*([\s\S]*?)```'
                code_match = re.search(code_pattern, app_info["app_code"])
                if code_match:
                    app_info["app_code"] = code_match.group(1)
            
            return app_info, None
        except Exception as e:
            return None, f"Failed to parse API response: {str(e)}"
    except Exception as e:
        return None, f"API call failed: {str(e)}"

def install_and_run_app(code, requirements):
    """Install requirements and run the app in a subprocess"""
    global running_process
    
    try:
        # Clean up any previous process
        if running_process and running_process.poll() is None:
            running_process.terminate()
            running_process.wait(timeout=5)
        
        # Create a temporary file for the app
        fd, app_file = tempfile.mkstemp(suffix='.py')
        os.close(fd)
        
        with open(app_file, 'w') as f:
            f.write(code)
        
        # Install requirements
        install_output = ""
        for req in requirements:
            try:
                cmd = [sys.executable, "-m", "pip", "install", "--upgrade", "--no-cache-dir", req]
                result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=120)
                install_output += f"Installing {req}: {'SUCCESS' if result.returncode == 0 else 'FAILED'}\n"
                if result.returncode != 0:
                    install_output += f"Error: {result.stderr}\n"
            except Exception as e:
                install_output += f"Error installing {req}: {str(e)}\n"
        
        # Run the app
        running_process = subprocess.Popen(
            [sys.executable, app_file],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        # Wait a bit for the app to start
        time.sleep(5)
        
        # Check if the process is still running
        if running_process.poll() is not None:
            stdout, stderr = running_process.communicate()
            os.unlink(app_file)
            return None, f"App failed to start:\n{stderr}\n\nInstallation log:\n{install_output}"
        
        return {
            "app_file": app_file,
            "install_output": install_output
        }, None
    except Exception as e:
        if 'app_file' in locals() and os.path.exists(app_file):
            os.unlink(app_file)
        return None, f"Error setting up and running app: {str(e)}"

def stop_running_app():
    """Stop the running app"""
    global running_process
    
    if running_process and running_process.poll() is None:
        try:
            running_process.terminate()
            running_process.wait(timeout=5)
            running_process = None
            return True
        except Exception as e:
            print(f"Error stopping app: {str(e)}")
    
    running_process = None
    return False

# Create the Gradio interface
with gr.Blocks(title="Gradio App Generator") as demo:
    gr.Markdown("# 🤖 Gradio App Generator")
    gr.Markdown("""
    This app generates a Gradio application based on your description, installs required packages,
    and runs it directly. The generated app will be displayed below.
    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            api_key = gr.Textbox(
                label="OpenAI API Key", 
                placeholder="sk-...",
                type="password",
                info="Your key is used only for this session"
            )
            
            prompt = gr.Textbox(
                label="App Description", 
                placeholder="Describe the Gradio app you want to create...",
                lines=5
            )
            
            with gr.Row():
                generate_btn = gr.Button("Generate & Run App", variant="primary")
                stop_btn = gr.Button("Stop Running App", variant="stop", visible=False)
            
            with gr.Accordion("Generated Code", open=False):
                code_output = gr.Code(language="python", label="App Code")
            
            with gr.Accordion("Installation Log", open=False):
                install_output = gr.Textbox(label="Package Installation Log", lines=5)
            
            status_output = gr.Markdown("")
        
        with gr.Column(scale=2):
            # Frame to display the running app
            app_frame = gr.HTML("<div style='text-align:center; padding:50px;'><h3>Your generated app will appear here</h3></div>")
    
    # App file path storage
    app_file_state = gr.State(None)
    
    def on_generate(api_key_val, prompt_val):
        # Validate API key
        if not api_key_val or len(api_key_val) < 20 or not api_key_val.startswith("sk-"):
            return (
                None, None, "⚠️ Please provide a valid OpenAI API key", 
                "<div style='text-align:center; padding:50px;'><h3>Invalid API key</h3></div>",
                gr.update(visible=False), None
            )
        
        try:
            # Generate app code and requirements
            status_message = "⏳ Generating app code..."
            yield (
                None, None, status_message, 
                "<div style='text-align:center; padding:50px;'><h3>Generating code...</h3></div>",
                gr.update(visible=False), None
            )
            
            app_info, error = call_openai_api(api_key_val, prompt_val)
            if error or not app_info:
                return (
                    None, None, f"⚠️ {error or 'Failed to generate app'}", 
                    "<div style='text-align:center; padding:50px;'><h3>Error generating app</h3></div>",
                    gr.update(visible=False), None
                )
            
            code = app_info["app_code"]
            requirements = app_info["requirements"]
            
            # Make sure server_name and server_port are specified
            if "server_name" not in code or "server_port" not in code:
                if "demo.launch(" in code:
                    code = code.replace("demo.launch(", "demo.launch(server_name=\"0.0.0.0\", server_port=7861, ")
                else:
                    code += "\n\ndemo.launch(server_name=\"0.0.0.0\", server_port=7861)"
            
            status_message = "⏳ Installing packages and starting app..."
            yield (
                code, None, status_message,
                "<div style='text-align:center; padding:50px;'><h3>Installing packages...</h3></div>",
                gr.update(visible=False), None
            )
            
            # Install packages and run the app
            run_result, run_error = install_and_run_app(code, requirements)
            if run_error or not run_result:
                return (
                    code, None, f"⚠️ {run_error}",
                    "<div style='text-align:center; padding:50px;'><h3>Error running app</h3></div>",
                    gr.update(visible=False), None
                )
            
            # Show the app in an iframe
            iframe_html = f"""
            <div style="height:600px; border:1px solid #ddd; border-radius:5px; overflow:hidden;">
                <iframe src="http://localhost:7861" width="100%" height="100%" frameborder="0"></iframe>
            </div>
            """
            
            return (
                code, run_result["install_output"], f"✅ App is running! View it below.", 
                iframe_html, gr.update(visible=True), run_result["app_file"]
            )
        except Exception as e:
            import traceback
            error_details = traceback.format_exc()
            return (
                None, None, f"⚠️ Error: {str(e)}\n\n{error_details}",
                "<div style='text-align:center; padding:50px;'><h3>An error occurred</h3></div>",
                gr.update(visible=False), None
            )
    
    def on_stop(app_file):
        stopped = stop_running_app()
        
        # Clean up the app file
        if app_file and os.path.exists(app_file):
            try:
                os.unlink(app_file)
            except:
                pass
        
        if stopped:
            return (
                "✅ App stopped successfully", 
                "<div style='text-align:center; padding:50px;'><h3>App stopped</h3></div>",
                gr.update(visible=False), None
            )
        else:
            return (
                "⚠️ No app was running", 
                "<div style='text-align:center; padding:50px;'><h3>No app was running</h3></div>",
                gr.update(visible=False), None
            )
    
    generate_btn.click(
        on_generate,
        inputs=[api_key, prompt],
        outputs=[
            code_output, install_output, status_output, app_frame, 
            stop_btn, app_file_state
        ]
    )
    
    stop_btn.click(
        on_stop,
        inputs=[app_file_state],
        outputs=[status_output, app_frame, stop_btn, app_file_state]
    )

if __name__ == "__main__":
    # Make sure we're not trying to use flagging
    demo.launch(server_name="0.0.0.0", server_port=7860, flagging_callback=None)