nakas commited on
Commit
8e2d0d0
·
verified ·
1 Parent(s): 917232a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -161
app.py CHANGED
@@ -1,32 +1,20 @@
1
- import os
2
  import gradio as gr
3
- import openai
4
- from openai import OpenAI
5
  import sys
6
- import io
7
- from contextlib import redirect_stdout
8
- import traceback
9
- import json
10
  import re
11
- import subprocess
12
- import pkg_resources
13
- import importlib
14
- import inspect
15
 
16
  class GradioAgentBuilder:
17
- def __init__(self, api_key=None):
18
- self.api_key = api_key
19
  self.client = None
20
  self.current_code = ""
21
- self.error_history = []
22
- self.execution_history = []
23
- self.generated_demo = None
24
- self.base_requirements = {
25
- 'gradio': '==3.50.2',
26
- 'openai': '>=1.0.0',
27
- 'matplotlib': '>=3.7.0'
28
- }
29
-
30
  def initialize_client(self, api_key):
31
  self.api_key = api_key
32
  self.client = OpenAI(api_key=api_key)
@@ -37,60 +25,53 @@ class GradioAgentBuilder:
37
  code = re.sub(r'\n```$', '', code)
38
  code = code.strip()
39
  return code
40
-
41
- def extract_imports(self, code):
42
- import_lines = []
43
- packages = set()
44
-
45
- for line in code.split('\n'):
46
- if line.startswith(('import ', 'from ')):
47
- import_lines.append(line)
48
- package = line.split()[1].split('.')[0]
49
- packages.add(package)
50
 
51
- return list(packages)
52
-
53
  def get_completion(self, prompt, error_context=None):
54
  if not self.client:
55
  return "Please set your OpenAI API key first!"
56
 
57
  messages = [
58
  {"role": "system", "content": """You are an AI agent specialized in creating Gradio applications.
59
- Generate complete, working Python code for Gradio apps based on user prompts.
60
 
61
- IMPORTANT REQUIREMENTS:
62
- - Return only pure Python code without any markdown formatting
63
- - Do not use markdown code blocks (```)
64
- - Always include all necessary imports at the top
65
- - Create a function that returns the Gradio Blocks interface
66
- - Do not include demo.launch() at the end
67
 
68
- Example structure:
69
  import gradio as gr
70
- import matplotlib.pyplot as plt
71
 
72
- def create_interface():
73
- with gr.Blocks() as demo:
74
- gr.Markdown("# My App")
75
- button = gr.Button("Click")
76
- output = gr.Image()
77
-
78
- def create_plot():
79
- plt.figure()
80
- plt.plot([1, 2, 3], [1, 2, 3])
81
- plt.savefig("plot.png")
82
- plt.close()
83
- return "plot.png"
84
-
85
- button.click(fn=create_plot, outputs=output)
86
-
87
- return demo"""}
 
 
 
 
 
 
88
  ]
89
 
90
  if error_context:
91
- messages.append({"role": "user", "content": f"The previous code generated an error: {error_context}. Please fix the code following the requirements above. Return only pure Python code."})
92
  else:
93
- messages.append({"role": "user", "content": f"Create a Gradio app that: {prompt}. Follow the requirements above and return only pure Python code."})
94
 
95
  try:
96
  response = self.client.chat.completions.create(
@@ -105,62 +86,52 @@ class GradioAgentBuilder:
105
  except Exception as e:
106
  return f"Error generating code: {str(e)}"
107
 
 
 
 
 
 
 
 
 
108
  def execute_code(self, code):
109
  if not code or isinstance(code, str) and code.startswith("Error"):
110
  return "", "No valid code to execute"
111
-
112
- stdout = io.StringIO()
113
  output = ""
114
  error = None
115
 
116
  try:
117
  cleaned_code = self.clean_code(code)
118
- required_packages = self.extract_imports(cleaned_code)
119
- for package in required_packages:
120
- if package not in sys.modules and package not in {'os', 'sys', 'io', 're', 'json'}:
121
- try:
122
- importlib.import_module(package)
123
- except ImportError:
124
- output += f"Package {package} not available\n"
125
-
126
- # Create a fresh namespace for execution
127
- namespace = {'__name__': '__main__'}
128
 
129
- # Add necessary imports to the namespace
130
- import gradio as gr
131
- namespace['gr'] = gr
132
- namespace['math'] = __import__('math')
133
- namespace['random'] = __import__('random')
134
- namespace['numpy'] = __import__('numpy')
135
 
136
- # Execute the code in the namespace
137
- exec(cleaned_code, namespace)
 
138
 
139
- # Find the function that creates the interface
140
- create_fn = None
141
- for name, obj in namespace.items():
142
- if inspect.isfunction(obj) and "create" in name.lower():
143
- create_fn = obj
144
- break
145
 
146
- if create_fn:
147
- try:
148
- # Create the demo interface
149
- generated_interface = create_fn()
150
- # Replace the content in the "Generated App" tab
151
- self.generated_demo = gr.update(value=generated_interface)
152
- output += "Generated app created successfully!\n"
153
- except Exception as e:
154
- error = f"Error creating interface: {str(e)}\n{traceback.format_exc()}"
155
  else:
156
- error = "Could not find create_interface function in generated code"
 
157
 
158
  self.current_code = cleaned_code
159
- self.execution_history.append({"code": cleaned_code, "output": output, "status": "success"})
160
 
161
  except Exception as e:
162
  error = traceback.format_exc()
163
- self.error_history.append({"code": code, "error": str(error)})
164
 
165
  return output, error
166
 
@@ -169,7 +140,6 @@ class GradioAgentBuilder:
169
  return code, "Code executed successfully!", None
170
 
171
  try:
172
- # Create a more detailed error context
173
  error_context = f"""
174
  The code generated this error: {error}
175
 
@@ -177,75 +147,67 @@ class GradioAgentBuilder:
177
  {code}
178
 
179
  Please fix the issues and return a complete, working version.
180
- Remember to:
181
- 1. Include all necessary imports
182
- 2. Create a function that returns the Gradio interface
183
- 3. Handle any edge cases that might have caused the error
184
  """
185
 
186
  fixed_code = self.get_completion(None, error_context)
187
  output, new_error = self.execute_code(fixed_code)
188
 
189
  if new_error:
190
- output += "\nStill encountering errors. You may want to try 'Fix & Iterate' again or provide more specific guidance."
191
 
192
  return fixed_code, output, new_error
193
 
194
  except Exception as e:
195
  return code, f"Error during iteration: {str(e)}", str(e)
196
 
 
197
  agent = GradioAgentBuilder()
198
 
199
  with gr.Blocks() as demo:
200
- with gr.Tab("Generator"):
201
- gr.Markdown("# Gradio App Builder Agent")
202
- gr.Markdown("First, enter your OpenAI API key. Then enter a prompt describing the Gradio app you want to create.")
203
-
204
- with gr.Row():
205
- api_key_input = gr.Textbox(
206
- label="OpenAI API Key",
207
- placeholder="Enter your OpenAI API key...",
208
- type="password"
209
- )
210
- api_status = gr.Textbox(
211
- label="API Status",
212
- placeholder="API status will appear here...",
213
- interactive=False
214
- )
215
- set_key_btn = gr.Button("Set API Key")
216
-
217
- with gr.Row():
218
- with gr.Column():
219
- prompt_input = gr.Textbox(
220
- label="What kind of Gradio app would you like to create?",
221
- placeholder="Describe the Gradio app you want...",
222
- lines=3
223
- )
224
- generate_btn = gr.Button("Generate App", interactive=False)
225
- iterate_btn = gr.Button("Fix & Iterate", interactive=False)
226
-
227
- with gr.Column():
228
- code_output = gr.Code(
229
- label="Generated Code",
230
- language="python"
231
- )
232
-
233
- with gr.Row():
234
- execution_output = gr.Textbox(
235
- label="Execution Output",
236
- lines=5,
237
- placeholder="Execution results will appear here..."
238
  )
239
- error_output = gr.Textbox(
240
- label="Error Output",
241
- lines=5,
242
- placeholder="Any errors will appear here..."
 
 
 
243
  )
244
-
245
- with gr.Tab("Generated App"):
246
- gr.Markdown("# Generated Application")
247
- gr.Markdown("Your generated app will appear here after creation.")
248
- generated_app_placeholder = gr.Markdown("No app generated yet.")
 
 
 
 
 
 
 
249
 
250
  def set_api_key(key):
251
  try:
@@ -265,21 +227,12 @@ with gr.Blocks() as demo:
265
  def generate_app(prompt):
266
  initial_code = agent.get_completion(prompt)
267
  output, error = agent.execute_code(initial_code)
268
-
269
- if agent.generated_demo:
270
- demo.update(update_map={generated_app_placeholder: agent.generated_demo})
271
-
272
  return initial_code, output, error
273
 
274
  def iterate_app(code, error):
275
  if not code:
276
  return "", "No code to iterate on", "Please generate code first"
277
-
278
  new_code, output, new_error = agent.iterate_on_code(code, error)
279
-
280
- if agent.generated_demo:
281
- demo.update(update_map={generated_app_placeholder: agent.generated_demo})
282
-
283
  return new_code, output, new_error
284
 
285
  set_key_btn.click(
@@ -301,4 +254,6 @@ with gr.Blocks() as demo:
301
  )
302
 
303
  if __name__ == "__main__":
 
 
304
  demo.queue().launch(server_name="0.0.0.0", server_port=7860)
 
 
1
  import gradio as gr
2
+ import subprocess
3
+ import os
4
  import sys
5
+ import threading
6
+ from openai import OpenAI
 
 
7
  import re
8
+ import traceback
9
+ import signal
 
 
10
 
11
  class GradioAgentBuilder:
12
+ def __init__(self):
13
+ self.api_key = None
14
  self.client = None
15
  self.current_code = ""
16
+ self.generated_process = None
17
+
 
 
 
 
 
 
 
18
  def initialize_client(self, api_key):
19
  self.api_key = api_key
20
  self.client = OpenAI(api_key=api_key)
 
25
  code = re.sub(r'\n```$', '', code)
26
  code = code.strip()
27
  return code
 
 
 
 
 
 
 
 
 
 
28
 
 
 
29
  def get_completion(self, prompt, error_context=None):
30
  if not self.client:
31
  return "Please set your OpenAI API key first!"
32
 
33
  messages = [
34
  {"role": "system", "content": """You are an AI agent specialized in creating Gradio applications.
35
+ Generate complete, working Python code for Gradio apps based on user prompts using Gradio 3.x.
36
 
37
+ CRITICAL REQUIREMENTS:
38
+ 1. The app must run on port 7861
39
+ 2. All imports must be at the top
40
+ 3. The app must be a complete, runnable program
41
+ 4. Must include demo.launch(server_name="0.0.0.0", server_port=7861) at the end
 
42
 
43
+ Example:
44
  import gradio as gr
45
+ import numpy as np
46
 
47
+ with gr.Blocks() as demo:
48
+ gr.Markdown("# Calculator")
49
+
50
+ with gr.Row():
51
+ num1 = gr.Number(label="First Number")
52
+ num2 = gr.Number(label="Second Number")
53
+
54
+ with gr.Row():
55
+ add_btn = gr.Button("Add")
56
+ result = gr.Number(label="Result")
57
+
58
+ def add(a, b):
59
+ return float(a) + float(b)
60
+
61
+ add_btn.click(
62
+ fn=add,
63
+ inputs=[num1, num2],
64
+ outputs=result
65
+ )
66
+
67
+ if __name__ == "__main__":
68
+ demo.launch(server_name="0.0.0.0", server_port=7861)"""}
69
  ]
70
 
71
  if error_context:
72
+ messages.append({"role": "user", "content": f"The previous code generated an error: {error_context}. Please fix the code following the requirements above."})
73
  else:
74
+ messages.append({"role": "user", "content": f"Create a Gradio app that: {prompt}. Follow the requirements above."})
75
 
76
  try:
77
  response = self.client.chat.completions.create(
 
86
  except Exception as e:
87
  return f"Error generating code: {str(e)}"
88
 
89
+ def stop_generated_app(self):
90
+ if self.generated_process:
91
+ try:
92
+ os.killpg(os.getpgid(self.generated_process.pid), signal.SIGTERM)
93
+ self.generated_process = None
94
+ except:
95
+ pass
96
+
97
  def execute_code(self, code):
98
  if not code or isinstance(code, str) and code.startswith("Error"):
99
  return "", "No valid code to execute"
100
+
 
101
  output = ""
102
  error = None
103
 
104
  try:
105
  cleaned_code = self.clean_code(code)
 
 
 
 
 
 
 
 
 
 
106
 
107
+ # Stop any existing generated app
108
+ self.stop_generated_app()
 
 
 
 
109
 
110
+ # Save the code to a temporary file
111
+ with open("generated_app.py", "w") as f:
112
+ f.write(cleaned_code)
113
 
114
+ # Start the generated app in a new process
115
+ self.generated_process = subprocess.Popen(
116
+ [sys.executable, "generated_app.py"],
117
+ preexec_fn=os.setsid,
118
+ stderr=subprocess.PIPE
119
+ )
120
 
121
+ # Check for immediate startup errors
122
+ error_output = self.generated_process.stderr.readline().decode()
123
+ if error_output:
124
+ error = error_output
125
+ self.stop_generated_app()
 
 
 
 
126
  else:
127
+ output = "Generated app is running at: /proxy/7861\n"
128
+ output += "You can access it in a new browser tab."
129
 
130
  self.current_code = cleaned_code
 
131
 
132
  except Exception as e:
133
  error = traceback.format_exc()
134
+ self.stop_generated_app()
135
 
136
  return output, error
137
 
 
140
  return code, "Code executed successfully!", None
141
 
142
  try:
 
143
  error_context = f"""
144
  The code generated this error: {error}
145
 
 
147
  {code}
148
 
149
  Please fix the issues and return a complete, working version.
 
 
 
 
150
  """
151
 
152
  fixed_code = self.get_completion(None, error_context)
153
  output, new_error = self.execute_code(fixed_code)
154
 
155
  if new_error:
156
+ output += "\nStill encountering errors. You may want to try 'Fix & Iterate' again."
157
 
158
  return fixed_code, output, new_error
159
 
160
  except Exception as e:
161
  return code, f"Error during iteration: {str(e)}", str(e)
162
 
163
+ # Create the main interface
164
  agent = GradioAgentBuilder()
165
 
166
  with gr.Blocks() as demo:
167
+ gr.Markdown("# Gradio App Builder Agent")
168
+ gr.Markdown("""Enter your OpenAI API key and describe the Gradio app you want to create.
169
+ The generated app will be available at /proxy/7861 (open in a new tab)""")
170
+
171
+ with gr.Row():
172
+ api_key_input = gr.Textbox(
173
+ label="OpenAI API Key",
174
+ placeholder="Enter your OpenAI API key...",
175
+ type="password"
176
+ )
177
+ api_status = gr.Textbox(
178
+ label="API Status",
179
+ placeholder="API status will appear here...",
180
+ interactive=False
181
+ )
182
+ set_key_btn = gr.Button("Set API Key")
183
+
184
+ with gr.Row():
185
+ with gr.Column():
186
+ prompt_input = gr.Textbox(
187
+ label="What kind of Gradio app would you like to create?",
188
+ placeholder="Describe the Gradio app you want...",
189
+ lines=3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  )
191
+ generate_btn = gr.Button("Generate App", interactive=False)
192
+ iterate_btn = gr.Button("Fix & Iterate", interactive=False)
193
+
194
+ with gr.Column():
195
+ code_output = gr.Code(
196
+ label="Generated Code",
197
+ language="python"
198
  )
199
+
200
+ with gr.Row():
201
+ execution_output = gr.Textbox(
202
+ label="Execution Output",
203
+ lines=5,
204
+ placeholder="Execution results will appear here..."
205
+ )
206
+ error_output = gr.Textbox(
207
+ label="Error Output",
208
+ lines=5,
209
+ placeholder="Any errors will appear here..."
210
+ )
211
 
212
  def set_api_key(key):
213
  try:
 
227
  def generate_app(prompt):
228
  initial_code = agent.get_completion(prompt)
229
  output, error = agent.execute_code(initial_code)
 
 
 
 
230
  return initial_code, output, error
231
 
232
  def iterate_app(code, error):
233
  if not code:
234
  return "", "No code to iterate on", "Please generate code first"
 
235
  new_code, output, new_error = agent.iterate_on_code(code, error)
 
 
 
 
236
  return new_code, output, new_error
237
 
238
  set_key_btn.click(
 
254
  )
255
 
256
  if __name__ == "__main__":
257
+ # Clean up any existing processes on startup
258
+ agent.stop_generated_app()
259
  demo.queue().launch(server_name="0.0.0.0", server_port=7860)