nakas commited on
Commit
e1c280b
·
verified ·
1 Parent(s): a6f1b11

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -265
app.py CHANGED
@@ -1,41 +1,19 @@
1
- import streamlit as st
2
  import gradio as gr
3
  import importlib.util
4
  import sys
5
- import tempfile
6
  import os
 
7
  from pathlib import Path
8
- import inspect
9
- import types
10
- import shutil
11
- import uuid
12
 
13
- # Configure the Streamlit page
14
- st.set_page_config(
15
- page_title="Gradio Examples Hub",
16
- page_icon="🧩",
17
- layout="wide"
18
- )
19
-
20
- # Directory structure
21
- EXAMPLES_DIR = Path("gradio_examples")
22
  EXAMPLES_DIR.mkdir(exist_ok=True)
23
 
24
- # Make sure we have a __init__.py file in the examples directory
25
- init_file = EXAMPLES_DIR / "__init__.py"
26
- if not init_file.exists():
27
- init_file.touch()
28
-
29
- # Ensure the examples directory is in the Python path
30
  if str(EXAMPLES_DIR.absolute()) not in sys.path:
 
31
  sys.path.insert(0, str(EXAMPLES_DIR.absolute()))
32
 
33
- # Create session state for tracking the current app
34
- if 'current_app' not in st.session_state:
35
- st.session_state.current_app = None
36
- st.session_state.current_app_module = None
37
- st.session_state.app_interface = None
38
-
39
  # Example Gradio apps as Python code
40
  EXAMPLES = {
41
  "hello_world": """
@@ -50,7 +28,7 @@ demo = gr.Interface(
50
  outputs=gr.Textbox(label="Greeting"),
51
  title="Hello World App",
52
  description="A simple app that greets you by name",
53
- examples=[["World"], ["Gradio"], ["Streamlit"]]
54
  )
55
  """,
56
 
@@ -125,259 +103,124 @@ demo = gr.Interface(
125
  title="Image Filter App",
126
  description="Apply various filters to your images"
127
  )
128
- """,
129
-
130
- "text_analysis": """
131
- import gradio as gr
132
-
133
- def analyze_text(text):
134
- if not text:
135
- return "Please enter some text"
136
-
137
- char_count = len(text)
138
- word_count = len(text.split())
139
- line_count = len(text.splitlines())
140
-
141
- return f"Characters: {char_count}\\nWords: {word_count}\\nLines: {line_count}"
142
-
143
- demo = gr.Interface(
144
- fn=analyze_text,
145
- inputs=gr.Textbox(label="Enter Text", lines=5),
146
- outputs=gr.Textbox(label="Analysis"),
147
- title="Text Analysis Tool",
148
- description="Count characters, words, and lines in text",
149
- examples=[
150
- ["Hello, world!"],
151
- ["This is an example.\\nIt has multiple lines.\\nThree lines in total."],
152
- ["The quick brown fox jumps over the lazy dog."]
153
- ]
154
- )
155
- """,
156
-
157
- "chatbot": """
158
- import gradio as gr
159
-
160
- def respond(message, history):
161
- # Simple echo bot for demonstration
162
- return f"You said: {message}"
163
-
164
- demo = gr.ChatInterface(
165
- fn=respond,
166
- title="Echo Bot",
167
- description="A simple chatbot that echoes your messages",
168
- examples=["Hello", "What's your name?", "Tell me a joke"]
169
- )
170
- """,
171
-
172
- "audio_player": """
173
- import gradio as gr
174
- import numpy as np
175
-
176
- def generate_tone(frequency, duration):
177
- sr = 44100 # Sample rate
178
- t = np.linspace(0, duration, int(sr * duration), False)
179
- tone = 0.5 * np.sin(2 * np.pi * frequency * t)
180
- return sr, tone
181
-
182
- demo = gr.Interface(
183
- fn=generate_tone,
184
- inputs=[
185
- gr.Slider(110, 880, 440, label="Frequency (Hz)"),
186
- gr.Slider(0.1, 5, 1, label="Duration (seconds)")
187
- ],
188
- outputs=gr.Audio(type="numpy"),
189
- title="Tone Generator",
190
- description="Generate a sine wave tone with the specified frequency and duration"
191
- )
192
  """
193
  }
194
 
 
195
  def load_example(example_name):
196
- """Load a Gradio example from the examples directory or create it if it doesn't exist"""
197
- # Generate a unique module name to avoid caching issues
198
- module_name = f"gradio_examples.{example_name}_{uuid.uuid4().hex[:8]}"
199
- file_path = EXAMPLES_DIR / f"{module_name.split('.')[-1]}.py"
200
 
201
- # Write the example code to a file
202
- with open(file_path, "w") as f:
203
  f.write(EXAMPLES[example_name])
204
 
205
  # Import the module
206
- spec = importlib.util.spec_from_file_location(module_name, file_path)
207
  module = importlib.util.module_from_spec(spec)
208
- sys.modules[module_name] = module
209
  spec.loader.exec_module(module)
210
 
211
- # Return the module and Gradio demo
212
- return module, module.demo
213
 
214
- def create_custom_example(code):
215
- """Create a custom Gradio example from code"""
216
- # Generate a unique module name
217
- module_name = f"gradio_examples.custom_{uuid.uuid4().hex[:8]}"
218
- file_path = EXAMPLES_DIR / f"{module_name.split('.')[-1]}.py"
219
-
220
- # Write the code to a file
221
- with open(file_path, "w") as f:
222
- f.write(code)
223
-
224
- # Import the module
225
- try:
226
- spec = importlib.util.spec_from_file_location(module_name, file_path)
227
- module = importlib.util.module_from_spec(spec)
228
- sys.modules[module_name] = module
229
- spec.loader.exec_module(module)
230
 
231
- # Check if the module has a demo attribute
232
- if hasattr(module, 'demo'):
233
- return module, module.demo, None
234
- else:
235
- return None, None, "No 'demo' variable found in the code"
236
- except Exception as e:
237
- return None, None, f"Error loading code: {str(e)}"
238
-
239
- def stop_current_app():
240
- """Stop the currently running Gradio app"""
241
- if st.session_state.app_interface:
242
- # Close the Gradio interface
243
- try:
244
- st.session_state.app_interface.close()
245
- except:
246
- pass
247
-
248
- # Clear the current app from session state
249
- st.session_state.current_app = None
250
- st.session_state.current_app_module = None
251
- st.session_state.app_interface = None
252
-
253
- # Create the Streamlit UI
254
- st.title("🧩 Gradio Examples Hub")
255
- st.write("Discover and run various Gradio examples directly in this app.")
256
-
257
- # Create tabs for different sections
258
- tab_examples, tab_custom = st.tabs(["Built-in Examples", "Custom Code"])
259
-
260
- # Built-in Examples tab
261
- with tab_examples:
262
- st.header("Built-in Examples")
263
-
264
- # Example selection
265
- example_options = list(EXAMPLES.keys())
266
- example_names = {
267
- "hello_world": "Hello World",
268
- "calculator": "Simple Calculator",
269
- "image_filter": "Image Filter",
270
- "text_analysis": "Text Analysis",
271
- "chatbot": "Simple Chatbot",
272
- "audio_player": "Audio Tone Generator"
273
- }
274
-
275
- selected_example = st.selectbox(
276
- "Select an example",
277
- example_options,
278
- format_func=lambda x: example_names.get(x, x)
279
- )
280
-
281
- # Show description
282
- example_descriptions = {
283
- "hello_world": "A simple app that greets you by name.",
284
- "calculator": "Perform basic arithmetic operations between two numbers.",
285
- "image_filter": "Apply various filters to images (grayscale, invert, sepia).",
286
- "text_analysis": "Count characters, words, and lines in text.",
287
- "chatbot": "A simple echo chatbot example.",
288
- "audio_player": "Generate audio tones with adjustable frequency and duration."
289
- }
290
-
291
- st.write(example_descriptions.get(selected_example, ""))
292
-
293
- # Show code
294
- with st.expander("View Code"):
295
- st.code(EXAMPLES[selected_example], language="python")
296
-
297
- # Run example button
298
- if st.button("Run Example", key="run_example"):
299
- stop_current_app() # Stop any running app
300
 
301
- with st.spinner("Loading example..."):
302
- # Load the example
303
- module, demo = load_example(selected_example)
304
-
305
- # Update session state
306
- st.session_state.current_app = selected_example
307
- st.session_state.current_app_module = module
308
- st.session_state.app_interface = demo
309
-
310
- # Rerun the app to refresh the UI
311
- st.experimental_rerun()
312
-
313
- # Custom Code tab
314
- with tab_custom:
315
- st.header("Custom Gradio Code")
316
- st.write("Write or paste your own Gradio code here.")
317
-
318
- # Code editor
319
- custom_code = st.text_area(
320
- "Gradio Code",
321
- height=300,
322
- placeholder="# Paste your Gradio code here\nimport gradio as gr\n\n# Define your functions\ndef my_function(input):\n return input\n\n# Create the interface\ndemo = gr.Interface(...)"
323
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
 
325
- # Run custom code button
326
- if st.button("Run Custom Code", key="run_custom"):
327
- if not custom_code.strip():
328
- st.error("Please enter some code")
329
- else:
330
- stop_current_app() # Stop any running app
331
-
332
- with st.spinner("Loading custom code..."):
333
- # Create the custom example
334
- module, demo, error = create_custom_example(custom_code)
335
-
336
- if error:
337
- st.error(error)
338
- else:
339
- # Update session state
340
- st.session_state.current_app = "custom"
341
- st.session_state.current_app_module = module
342
- st.session_state.app_interface = demo
343
-
344
- # Rerun the app to refresh the UI
345
- st.experimental_rerun()
346
 
347
- # Display the current app if there is one
348
- st.header("Current App")
349
-
350
- if st.session_state.current_app:
351
- app_name = st.session_state.current_app
352
- demo = st.session_state.app_interface
353
-
354
- # Create a container for the app
355
- app_container = st.container()
356
- app_container.write(f"Running: {example_names.get(app_name, 'Custom App')}")
357
 
358
- # Create a unique key for the app
359
- app_key = f"app_{app_name}_{uuid.uuid4().hex[:8]}"
 
 
 
 
 
360
 
361
- # Render the Gradio interface directly in Streamlit
362
- with app_container:
363
- gr.Interface.load(
364
- fn=demo,
365
- title=demo._title,
366
- description=getattr(demo, "_description", ""),
367
- ).render()
368
 
369
- # Stop button
370
- if st.button("Stop App", key="stop_app"):
371
- stop_current_app()
372
- st.experimental_rerun()
373
- else:
374
- st.info("No app is currently running. Select an example or create a custom app to get started.")
375
-
376
- # Footer
377
- st.markdown("---")
378
- st.markdown("### About this App")
379
- st.write(
380
- "This Streamlit app demonstrates how to dynamically load and run Gradio interfaces. "
381
- "It showcases integration between Streamlit for the main application UI and Gradio for "
382
- "interactive demos."
383
- )
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import importlib.util
3
  import sys
 
4
  import os
5
+ import tempfile
6
  from pathlib import Path
 
 
 
 
7
 
8
+ # Create directory for examples
9
+ EXAMPLES_DIR = Path("examples")
 
 
 
 
 
 
 
10
  EXAMPLES_DIR.mkdir(exist_ok=True)
11
 
12
+ # Ensure examples directory is in Python path
 
 
 
 
 
13
  if str(EXAMPLES_DIR.absolute()) not in sys.path:
14
+ sys.modules["examples"] = type(sys)("examples")
15
  sys.path.insert(0, str(EXAMPLES_DIR.absolute()))
16
 
 
 
 
 
 
 
17
  # Example Gradio apps as Python code
18
  EXAMPLES = {
19
  "hello_world": """
 
28
  outputs=gr.Textbox(label="Greeting"),
29
  title="Hello World App",
30
  description="A simple app that greets you by name",
31
+ examples=[["World"], ["Gradio"], ["User"]]
32
  )
33
  """,
34
 
 
103
  title="Image Filter App",
104
  description="Apply various filters to your images"
105
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  """
107
  }
108
 
109
+ # Function to dynamically load a Gradio example
110
  def load_example(example_name):
111
+ """Load a example module and return the demo instance"""
112
+ # Create a module file
113
+ module_path = EXAMPLES_DIR / f"{example_name}.py"
 
114
 
115
+ # Write the example code to the file
116
+ with open(module_path, "w") as f:
117
  f.write(EXAMPLES[example_name])
118
 
119
  # Import the module
120
+ spec = importlib.util.spec_from_file_location(f"examples.{example_name}", module_path)
121
  module = importlib.util.module_from_spec(spec)
 
122
  spec.loader.exec_module(module)
123
 
124
+ # Return the demo object
125
+ return module.demo
126
 
127
+ # Main selector app
128
+ def selector_app():
129
+ with gr.Blocks(title="Gradio Examples Selector") as selector:
130
+ with gr.Row():
131
+ gr.Markdown("# Gradio Examples Hub")
 
 
 
 
 
 
 
 
 
 
 
132
 
133
+ with gr.Row():
134
+ gr.Markdown("Select an example to run:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
+ example_names = {
137
+ "hello_world": "Hello World Greeter",
138
+ "calculator": "Simple Calculator",
139
+ "image_filter": "Image Filter"
140
+ }
141
+
142
+ with gr.Row():
143
+ example_dropdown = gr.Dropdown(
144
+ choices=list(EXAMPLES.keys()),
145
+ value="hello_world",
146
+ label="Select Example",
147
+ format_func=lambda x: example_names.get(x, x)
148
+ )
149
+
150
+ with gr.Row():
151
+ load_btn = gr.Button("Load Example", variant="primary")
152
+
153
+ # Info area for example descriptions
154
+ example_descriptions = {
155
+ "hello_world": "A simple app that greets you by name.",
156
+ "calculator": "Perform basic arithmetic operations between two numbers.",
157
+ "image_filter": "Apply various filters (grayscale, invert, sepia) to images."
158
+ }
159
+
160
+ info_box = gr.Markdown(f"**{example_names['hello_world']}**: {example_descriptions['hello_world']}")
161
+
162
+ # Update description when dropdown changes
163
+ def update_description(example):
164
+ return f"**{example_names[example]}**: {example_descriptions[example]}"
165
+
166
+ example_dropdown.change(
167
+ update_description,
168
+ inputs=[example_dropdown],
169
+ outputs=[info_box]
170
+ )
171
+
172
+ # Function to load the selected example
173
+ def load_selected_example(example_name):
174
+ # Return the app name to be loaded
175
+ return example_name
176
+
177
+ # Connect the load button
178
+ load_btn.click(
179
+ load_selected_example,
180
+ inputs=[example_dropdown],
181
+ outputs=[gr.Textbox(visible=False)]
182
+ )
183
 
184
+ return selector
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
+ # Create a function to determine which app to launch
187
+ def get_current_app():
188
+ # Check if an example was requested in the URL
189
+ example_name = None
 
 
 
 
 
 
190
 
191
+ # Get query parameters from URL
192
+ try:
193
+ import urllib.parse
194
+ query_params = dict(urllib.parse.parse_qsl(os.environ.get('QUERY_STRING', '')))
195
+ example_name = query_params.get('example', None)
196
+ except:
197
+ pass
198
 
199
+ # If no example specified, return the selector app
200
+ if not example_name or example_name not in EXAMPLES:
201
+ return selector_app()
 
 
 
 
202
 
203
+ # Otherwise, load the requested example
204
+ try:
205
+ return load_example(example_name)
206
+ except Exception as e:
207
+ print(f"Error loading example {example_name}: {str(e)}")
208
+ return selector_app()
209
+
210
+ # Launch the app based on URL parameters
211
+ app = get_current_app()
212
+
213
+ # When an example is selected, redirect to load it
214
+ if isinstance(app, gr.Blocks) and app.title == "Gradio Examples Selector":
215
+ @app.load(api_name=False)
216
+ def on_load():
217
+ pass
218
+
219
+ # Handle example selection
220
+ @app.callback(inputs=[gr.Textbox(visible=False)], outputs=None)
221
+ def on_example_selected(example_name):
222
+ if example_name:
223
+ gr.Blocks.redirect(f"?example={example_name}")
224
+
225
+ # Launch the appropriate app
226
+ app.launch(server_name="0.0.0.0", server_port=7860)