nakas commited on
Commit
b867a1d
·
verified ·
1 Parent(s): f173463

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +320 -59
app.py CHANGED
@@ -1,82 +1,343 @@
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
2
  import sys
 
 
3
 
4
- # Print version info for debugging
5
- print(f"Python version: {sys.version}")
6
- print(f"Gradio version: {gr.__version__}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- # Hello World function
9
  def greet(name):
10
  return f"Hello, {name}!"
11
 
12
- # Calculator function
13
- def calculate(num1, num2, op):
14
- if op == "Add":
15
- return str(num1 + num2)
16
- elif op == "Subtract":
17
- return str(num1 - num2)
18
- elif op == "Multiply":
19
- return str(num1 * num2)
20
- elif op == "Divide":
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  if num2 == 0:
22
  return "Error: Division by zero"
23
- return str(num1 / num2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- # Text Analysis function
26
  def analyze_text(text):
27
  if not text:
28
  return "Please enter some text"
29
 
30
- num_chars = len(text)
31
- num_words = len(text.split())
32
- num_lines = len(text.splitlines())
33
 
34
- return f"Characters: {num_chars}\nWords: {num_words}\nLines: {num_lines}"
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- # Create a tab-based interface with simple demos
37
- with gr.Blocks() as demo:
38
- gr.Markdown("# 🤖 Simple Gradio Demo Apps")
 
 
 
 
 
39
 
40
- with gr.Tab("Hello World"):
41
- with gr.Row():
42
- name_input = gr.Textbox(label="Your Name", value="World")
43
- greeting_output = gr.Textbox(label="Greeting")
44
-
45
- greet_btn = gr.Button("Say Hello")
46
- greet_btn.click(fn=greet, inputs=name_input, outputs=greeting_output)
 
 
 
47
 
48
- with gr.Tab("Calculator"):
49
- with gr.Row():
50
- num1 = gr.Number(label="First Number", value=5)
51
- num2 = gr.Number(label="Second Number", value=3)
52
 
53
- operation = gr.Radio(
54
- ["Add", "Subtract", "Multiply", "Divide"],
55
- label="Operation",
56
- value="Add"
57
- )
58
 
59
- calc_result = gr.Textbox(label="Result")
60
- calc_btn = gr.Button("Calculate")
61
- calc_btn.click(fn=calculate, inputs=[num1, num2, operation], outputs=calc_result)
62
-
63
- with gr.Tab("Text Analysis"):
64
- text_input = gr.Textbox(label="Enter text to analyze", lines=5)
65
- text_result = gr.Textbox(label="Analysis Result")
66
- analyze_btn = gr.Button("Analyze Text")
67
- analyze_btn.click(fn=analyze_text, inputs=text_input, outputs=text_result)
68
-
69
- gr.Markdown("""
70
- ### About This Demo
71
-
72
- This is a simple demonstration of Gradio functionality with:
73
 
74
- 1. A Hello World text generator
75
- 2. A basic calculator
76
- 3. A text analysis tool
77
 
78
- Use the tabs above to try different demo apps.
79
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- if __name__ == "__main__":
82
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
  import gradio as gr
3
+ import subprocess
4
+ import tempfile
5
+ import os
6
+ import time
7
+ import signal
8
+ import requests
9
+ import re
10
+ import json
11
  import sys
12
+ from pathlib import Path
13
+ import atexit
14
 
15
+ # Print version info
16
+ st.set_page_config(
17
+ page_title="Gradio App Generator",
18
+ page_icon="🤖",
19
+ layout="wide"
20
+ )
21
+
22
+ # Directory to store temporary apps
23
+ TEMP_DIR = Path(tempfile.gettempdir()) / "gradio_apps"
24
+ os.makedirs(TEMP_DIR, exist_ok=True)
25
+
26
+ # Track running processes
27
+ if 'process' not in st.session_state:
28
+ st.session_state.process = None
29
+ st.session_state.app_port = None
30
+ st.session_state.app_path = None
31
+
32
+ # Clean up on exit
33
+ def cleanup():
34
+ if st.session_state.process and st.session_state.process.poll() is None:
35
+ st.session_state.process.terminate()
36
+ try:
37
+ st.session_state.process.wait(timeout=5)
38
+ except subprocess.TimeoutExpired:
39
+ st.session_state.process.kill()
40
+
41
+ # Clean up temp files
42
+ if st.session_state.app_path and os.path.exists(st.session_state.app_path):
43
+ try:
44
+ os.unlink(st.session_state.app_path)
45
+ except:
46
+ pass
47
+
48
+ atexit.register(cleanup)
49
+
50
+ def stop_running_app():
51
+ """Stop the currently running Gradio app"""
52
+ if st.session_state.process and st.session_state.process.poll() is None:
53
+ st.session_state.process.terminate()
54
+ try:
55
+ st.session_state.process.wait(timeout=5)
56
+ except subprocess.TimeoutExpired:
57
+ st.session_state.process.kill()
58
+
59
+ st.session_state.process = None
60
+ st.session_state.app_port = None
61
+
62
+ if st.session_state.app_path and os.path.exists(st.session_state.app_path):
63
+ try:
64
+ os.unlink(st.session_state.app_path)
65
+ except:
66
+ pass
67
+ st.session_state.app_path = None
68
+
69
+ return True
70
+
71
+ return False
72
+
73
+ def get_openai_code(api_key, description):
74
+ """Get code from OpenAI API"""
75
+ prompt = f"""Create a simple Gradio app that {description}.
76
+
77
+ IMPORTANT: The app should:
78
+ 1. Use gr.Interface (not Blocks)
79
+ 2. Have flagging_callback=None to avoid permission issues
80
+ 3. Include demo.launch(server_name="0.0.0.0", server_port=PORT) at the end
81
+ 4. Be self-contained with only standard libraries
82
+
83
+ Provide ONLY Python code with no explanation."""
84
+
85
+ try:
86
+ response = requests.post(
87
+ "https://api.openai.com/v1/chat/completions",
88
+ headers={
89
+ "Content-Type": "application/json",
90
+ "Authorization": f"Bearer {api_key}"
91
+ },
92
+ json={
93
+ "model": "gpt-4o",
94
+ "messages": [
95
+ {"role": "system", "content": "You are a Gradio expert. Provide only Python code without explanations."},
96
+ {"role": "user", "content": prompt}
97
+ ],
98
+ "temperature": 0.2
99
+ },
100
+ timeout=30
101
+ )
102
+
103
+ if response.status_code != 200:
104
+ return None, f"API Error: {response.status_code}"
105
+
106
+ content = response.json()["choices"][0]["message"]["content"]
107
+
108
+ # Extract code blocks if present
109
+ code_pattern = r'```python\s*([\s\S]*?)```'
110
+ code_matches = re.findall(code_pattern, content)
111
+
112
+ if code_matches:
113
+ return code_matches[0], None
114
+
115
+ # If no code blocks found, use the whole content
116
+ return content, None
117
+
118
+ except Exception as e:
119
+ return None, f"Error: {str(e)}"
120
+
121
+ def run_gradio_app(code, port=8050):
122
+ """Run a Gradio app with the given code"""
123
+ # Stop any existing app
124
+ stop_running_app()
125
+
126
+ # Replace PORT in the code with the actual port
127
+ code = code.replace("PORT", str(port))
128
+
129
+ # Make sure flagging is disabled
130
+ if "gr.Interface" in code and "flagging_callback=None" not in code:
131
+ code = code.replace("gr.Interface(", "gr.Interface(flagging_callback=None, ")
132
+
133
+ # Create a temporary file
134
+ fd, path = tempfile.mkstemp(suffix='.py', dir=TEMP_DIR)
135
+ with os.fdopen(fd, 'w') as f:
136
+ f.write(code)
137
+
138
+ st.session_state.app_path = path
139
+
140
+ # Run the app as a subprocess
141
+ try:
142
+ process = subprocess.Popen([sys.executable, path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
143
+ st.session_state.process = process
144
+ st.session_state.app_port = port
145
+
146
+ # Wait a bit for the app to start
147
+ time.sleep(3)
148
+
149
+ # Check if process is still running
150
+ if process.poll() is not None:
151
+ stdout, stderr = process.communicate()
152
+ return False, f"Failed to start app: {stderr.decode('utf-8')}"
153
+
154
+ return True, None
155
+
156
+ except Exception as e:
157
+ return False, f"Error starting app: {str(e)}"
158
+
159
+ # Predefined Gradio app templates
160
+ TEMPLATES = {
161
+ "hello_world": """
162
+ import gradio as gr
163
 
 
164
  def greet(name):
165
  return f"Hello, {name}!"
166
 
167
+ demo = gr.Interface(
168
+ fn=greet,
169
+ inputs=gr.Textbox(label="Name"),
170
+ outputs=gr.Textbox(label="Greeting"),
171
+ title="Hello World App",
172
+ flagging_callback=None
173
+ )
174
+
175
+ demo.launch(server_name="0.0.0.0", server_port=PORT)
176
+ """,
177
+
178
+ "calculator": """
179
+ import gradio as gr
180
+
181
+ def calculate(num1, num2, operation):
182
+ if operation == "Add":
183
+ return num1 + num2
184
+ elif operation == "Subtract":
185
+ return num1 - num2
186
+ elif operation == "Multiply":
187
+ return num1 * num2
188
+ elif operation == "Divide":
189
  if num2 == 0:
190
  return "Error: Division by zero"
191
+ return num1 / num2
192
+
193
+ demo = gr.Interface(
194
+ fn=calculate,
195
+ inputs=[
196
+ gr.Number(label="First Number"),
197
+ gr.Number(label="Second Number"),
198
+ gr.Radio(["Add", "Subtract", "Multiply", "Divide"], label="Operation")
199
+ ],
200
+ outputs=gr.Textbox(label="Result"),
201
+ title="Simple Calculator",
202
+ flagging_callback=None
203
+ )
204
+
205
+ demo.launch(server_name="0.0.0.0", server_port=PORT)
206
+ """,
207
+
208
+ "image_filter": """
209
+ import gradio as gr
210
+ import numpy as np
211
+
212
+ def apply_filter(image, filter_type):
213
+ if image is None:
214
+ return None
215
+
216
+ if filter_type == "Grayscale":
217
+ return np.mean(image, axis=2).astype(np.uint8)
218
+ elif filter_type == "Invert":
219
+ return 255 - image
220
+ elif filter_type == "Sepia":
221
+ sepia = np.array([[0.393, 0.769, 0.189],
222
+ [0.349, 0.686, 0.168],
223
+ [0.272, 0.534, 0.131]])
224
+ sepia_img = image.dot(sepia.T)
225
+ sepia_img[sepia_img > 255] = 255
226
+ return sepia_img.astype(np.uint8)
227
+ return image
228
+
229
+ demo = gr.Interface(
230
+ fn=apply_filter,
231
+ inputs=[
232
+ gr.Image(type="numpy"),
233
+ gr.Radio(["Grayscale", "Invert", "Sepia"], label="Filter")
234
+ ],
235
+ outputs=gr.Image(type="numpy"),
236
+ title="Image Filter App",
237
+ flagging_callback=None
238
+ )
239
+
240
+ demo.launch(server_name="0.0.0.0", server_port=PORT)
241
+ """,
242
+
243
+ "text_analysis": """
244
+ import gradio as gr
245
 
 
246
  def analyze_text(text):
247
  if not text:
248
  return "Please enter some text"
249
 
250
+ char_count = len(text)
251
+ word_count = len(text.split())
252
+ line_count = len(text.splitlines())
253
 
254
+ return f"Characters: {char_count}\\nWords: {word_count}\\nLines: {line_count}"
255
+
256
+ demo = gr.Interface(
257
+ fn=analyze_text,
258
+ inputs=gr.Textbox(label="Enter Text", lines=5),
259
+ outputs=gr.Textbox(label="Analysis"),
260
+ title="Text Analysis Tool",
261
+ flagging_callback=None
262
+ )
263
+
264
+ demo.launch(server_name="0.0.0.0", server_port=PORT)
265
+ """
266
+ }
267
 
268
+ # Streamlit UI
269
+ st.title("🤖 Gradio App Generator")
270
+
271
+ tab1, tab2 = st.tabs(["Built-in Templates", "Custom Generator"])
272
+
273
+ # Built-in templates tab
274
+ with tab1:
275
+ st.header("Generate from Templates")
276
 
277
+ template_choice = st.selectbox(
278
+ "Select a template",
279
+ ["hello_world", "calculator", "image_filter", "text_analysis"],
280
+ format_func=lambda x: {
281
+ "hello_world": "Hello World",
282
+ "calculator": "Simple Calculator",
283
+ "image_filter": "Image Filter",
284
+ "text_analysis": "Text Analysis"
285
+ }[x]
286
+ )
287
 
288
+ if st.button("Generate from Template"):
289
+ code = TEMPLATES[template_choice]
290
+ success, error = run_gradio_app(code)
 
291
 
292
+ if success:
293
+ st.success("App started successfully!")
294
+ else:
295
+ st.error(f"Failed to start app: {error}")
 
296
 
297
+ st.code(code, language="python")
298
+
299
+ # Custom generator tab
300
+ with tab2:
301
+ st.header("Generate Custom App")
 
 
 
 
 
 
 
 
 
302
 
303
+ api_key = st.text_input("OpenAI API Key", type="password", help="Your OpenAI API key")
304
+ app_description = st.text_area("Describe the app you want", height=100)
 
305
 
306
+ if st.button("Generate Custom App"):
307
+ if not api_key or len(api_key) < 20:
308
+ st.error("Please enter a valid OpenAI API key")
309
+ elif not app_description:
310
+ st.error("Please enter a description for your app")
311
+ else:
312
+ with st.spinner("Generating app..."):
313
+ code, error = get_openai_code(api_key, app_description)
314
+
315
+ if error:
316
+ st.error(f"Error generating code: {error}")
317
+ else:
318
+ success, run_error = run_gradio_app(code)
319
+
320
+ if success:
321
+ st.success("App started successfully!")
322
+ else:
323
+ st.error(f"Failed to start app: {run_error}")
324
+
325
+ st.code(code, language="python")
326
+
327
+ # Display the currently running app
328
+ st.header("Running App")
329
 
330
+ if st.session_state.app_port:
331
+ # Create an iframe to display the app
332
+ st.components.v1.iframe(
333
+ src=f"http://localhost:{st.session_state.app_port}",
334
+ height=600,
335
+ scrolling=True
336
+ )
337
+
338
+ if st.button("Stop App"):
339
+ if stop_running_app():
340
+ st.success("App stopped successfully")
341
+ st.experimental_rerun()
342
+ else:
343
+ st.info("No app is currently running. Generate an app first.")