nakas commited on
Commit
07aeb52
·
verified ·
1 Parent(s): 018aa15

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -13
app.py CHANGED
@@ -37,11 +37,15 @@ def get_app_code(api_key, description):
37
  """Get app code from the OpenAI API"""
38
  prompt = f"""Create a simple Gradio app that {description}.
39
 
 
 
 
40
  The app should:
41
- 1. Use ONLY gr.Interface (not Blocks)
42
  2. Be self-contained and not use any external dependencies
43
  3. Use only Python standard library and NumPy/Pandas if needed
44
  4. Include demo.launch(server_name="0.0.0.0", server_port=7861) at the end
 
45
 
46
  Provide ONLY Python code with no explanation or markdown."""
47
 
@@ -80,6 +84,15 @@ def get_app_code(api_key, description):
80
  except Exception as e:
81
  return None, f"Error: {str(e)}"
82
 
 
 
 
 
 
 
 
 
 
83
  def run_gradio_app(code):
84
  """Save the code to a temp file and run it as a subprocess"""
85
  global app_process, temp_file_path
@@ -102,31 +115,127 @@ def run_gradio_app(code):
102
  fd, temp_file_path = tempfile.mkstemp(suffix='.py')
103
  os.close(fd)
104
 
 
 
 
105
  # Write code to file
106
  with open(temp_file_path, 'w') as f:
107
- f.write(code)
108
 
109
  # Run the app as a subprocess
110
- app_process = subprocess.Popen([sys.executable, temp_file_path])
111
-
112
- # Wait a moment for the app to start
113
- time.sleep(3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
- # Check if process is still running
116
- if app_process.poll() is not None:
117
- return False, f"App failed to start (exit code: {app_process.returncode})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
- return True, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
  # Create a very simple Gradio interface
122
  with gr.Blocks() as demo:
123
  gr.Markdown("# 🤖 Simple Gradio App Generator")
124
 
125
- api_key = gr.Textbox(label="OpenAI API Key", placeholder="sk-...", type="password")
126
- description = gr.Textbox(label="Describe the app you want", lines=3)
 
 
 
 
 
 
 
 
 
 
127
 
128
  with gr.Row():
129
- generate_btn = gr.Button("Generate & Run App")
130
  stop_btn = gr.Button("Stop Running App", visible=False)
131
 
132
  code_display = gr.Code(label="Generated Code", language="python")
@@ -158,6 +267,22 @@ with gr.Blocks() as demo:
158
 
159
  return code, "✅ App is running! View it below:", iframe, gr.update(visible=True)
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  def stop_app():
162
  global app_process
163
 
@@ -175,6 +300,12 @@ with gr.Blocks() as demo:
175
  outputs=[code_display, status, app_display, stop_btn]
176
  )
177
 
 
 
 
 
 
 
178
  stop_btn.click(
179
  stop_app,
180
  inputs=[],
 
37
  """Get app code from the OpenAI API"""
38
  prompt = f"""Create a simple Gradio app that {description}.
39
 
40
+ VERY IMPORTANT: You MUST include this to disable flagging which creates permission errors:
41
+ gr.Interface(..., flagging_callback=None)
42
+
43
  The app should:
44
+ 1. Use gr.Interface with flagging_callback=None
45
  2. Be self-contained and not use any external dependencies
46
  3. Use only Python standard library and NumPy/Pandas if needed
47
  4. Include demo.launch(server_name="0.0.0.0", server_port=7861) at the end
48
+ 5. Do NOT create any directories or write any files
49
 
50
  Provide ONLY Python code with no explanation or markdown."""
51
 
 
84
  except Exception as e:
85
  return None, f"Error: {str(e)}"
86
 
87
+ def ensure_flagging_disabled(code):
88
+ """Ensure flagging is disabled in the code"""
89
+ # Check if flagging_callback=None is present in Interface creation
90
+ if 'Interface(' in code and 'flagging_callback=None' not in code:
91
+ # Insert flagging_callback=None in the Interface parameters
92
+ code = code.replace('Interface(', 'Interface(flagging_callback=None, ')
93
+
94
+ return code
95
+
96
  def run_gradio_app(code):
97
  """Save the code to a temp file and run it as a subprocess"""
98
  global app_process, temp_file_path
 
115
  fd, temp_file_path = tempfile.mkstemp(suffix='.py')
116
  os.close(fd)
117
 
118
+ # Ensure flagging is disabled
119
+ modified_code = ensure_flagging_disabled(code)
120
+
121
  # Write code to file
122
  with open(temp_file_path, 'w') as f:
123
+ f.write(modified_code)
124
 
125
  # Run the app as a subprocess
126
+ try:
127
+ app_process = subprocess.Popen(
128
+ [sys.executable, temp_file_path],
129
+ stdout=subprocess.PIPE,
130
+ stderr=subprocess.PIPE
131
+ )
132
+
133
+ # Wait a moment for the app to start
134
+ time.sleep(3)
135
+
136
+ # Check if process is still running
137
+ if app_process.poll() is not None:
138
+ # Get error output
139
+ _, stderr = app_process.communicate()
140
+ error_msg = stderr.decode('utf-8')
141
+ return False, f"App failed to start:\n{error_msg}"
142
+
143
+ return True, None
144
+ except Exception as e:
145
+ return False, f"Error launching app: {str(e)}"
146
+
147
+ # Create demo app for direct usage
148
+ def make_demo_app(app_type):
149
+ """Create a simple demo app based on type"""
150
+ if app_type == "calculator":
151
+ return """
152
+ import gradio as gr
153
+ import numpy as np
154
+
155
+ def calculate(num1, num2, operation):
156
+ if operation == "Add":
157
+ return num1 + num2
158
+ elif operation == "Subtract":
159
+ return num1 - num2
160
+ elif operation == "Multiply":
161
+ return num1 * num2
162
+ elif operation == "Divide":
163
+ return num1 / num2 if num2 != 0 else "Error: Division by zero"
164
+ else:
165
+ return "Invalid operation"
166
+
167
+ demo = gr.Interface(
168
+ fn=calculate,
169
+ inputs=[
170
+ gr.Number(label="First Number"),
171
+ gr.Number(label="Second Number"),
172
+ gr.Radio(["Add", "Subtract", "Multiply", "Divide"], label="Operation")
173
+ ],
174
+ outputs=gr.Textbox(label="Result"),
175
+ title="Simple Calculator",
176
+ flagging_callback=None
177
+ )
178
+
179
+ demo.launch(server_name="0.0.0.0", server_port=7861)
180
+ """
181
 
182
+ elif app_type == "image":
183
+ return """
184
+ import gradio as gr
185
+ import numpy as np
186
+ from PIL import Image
187
+
188
+ def grayscale(img):
189
+ gray_img = np.mean(img, axis=2).astype(np.uint8)
190
+ return gray_img
191
+
192
+ demo = gr.Interface(
193
+ fn=grayscale,
194
+ inputs=gr.Image(type="numpy"),
195
+ outputs=gr.Image(type="numpy"),
196
+ title="Image Grayscale Converter",
197
+ flagging_callback=None
198
+ )
199
+
200
+ demo.launch(server_name="0.0.0.0", server_port=7861)
201
+ """
202
 
203
+ else: # Default hello world
204
+ return """
205
+ import gradio as gr
206
+
207
+ def greet(name):
208
+ return f"Hello, {name}!"
209
+
210
+ demo = gr.Interface(
211
+ fn=greet,
212
+ inputs=gr.Textbox(label="Your Name"),
213
+ outputs=gr.Textbox(label="Greeting"),
214
+ title="Hello World App",
215
+ flagging_callback=None
216
+ )
217
+
218
+ demo.launch(server_name="0.0.0.0", server_port=7861)
219
+ """
220
 
221
  # Create a very simple Gradio interface
222
  with gr.Blocks() as demo:
223
  gr.Markdown("# 🤖 Simple Gradio App Generator")
224
 
225
+ with gr.Tab("Generate Custom App"):
226
+ api_key = gr.Textbox(label="OpenAI API Key", placeholder="sk-...", type="password")
227
+ description = gr.Textbox(label="Describe the app you want", lines=3)
228
+ generate_btn = gr.Button("Generate & Run App")
229
+
230
+ with gr.Tab("Quick Demo Apps"):
231
+ demo_type = gr.Radio(
232
+ ["hello", "calculator", "image"],
233
+ label="Select Demo App",
234
+ value="hello"
235
+ )
236
+ demo_btn = gr.Button("Run Demo App")
237
 
238
  with gr.Row():
 
239
  stop_btn = gr.Button("Stop Running App", visible=False)
240
 
241
  code_display = gr.Code(label="Generated Code", language="python")
 
267
 
268
  return code, "✅ App is running! View it below:", iframe, gr.update(visible=True)
269
 
270
+ def run_demo(app_type):
271
+ code = make_demo_app(app_type)
272
+ success, run_error = run_gradio_app(code)
273
+
274
+ if not success:
275
+ return code, f"Error running demo: {run_error}", gr.update(visible=False), gr.update(visible=False)
276
+
277
+ # Create iframe to show the app
278
+ iframe = f"""
279
+ <div style="border:1px solid #ddd; border-radius:5px; height:500px; margin-top:10px;">
280
+ <iframe src="http://localhost:7861" width="100%" height="100%" frameborder="0"></iframe>
281
+ </div>
282
+ """
283
+
284
+ return code, "✅ Demo app is running! View it below:", iframe, gr.update(visible=True)
285
+
286
  def stop_app():
287
  global app_process
288
 
 
300
  outputs=[code_display, status, app_display, stop_btn]
301
  )
302
 
303
+ demo_btn.click(
304
+ run_demo,
305
+ inputs=[demo_type],
306
+ outputs=[code_display, status, app_display, stop_btn]
307
+ )
308
+
309
  stop_btn.click(
310
  stop_app,
311
  inputs=[],