nakas commited on
Commit
b54eb41
·
verified ·
1 Parent(s): d3a1cdc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -136
app.py CHANGED
@@ -1,22 +1,19 @@
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": """
 
 
 
20
  import gradio as gr
21
 
22
  def greet(name):
@@ -24,17 +21,19 @@ def greet(name):
24
 
25
  demo = gr.Interface(
26
  fn=greet,
27
- inputs=gr.Textbox(label="Your Name", placeholder="Enter your name"),
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
-
35
- "calculator": """
 
 
 
 
36
  import gradio as gr
37
- import numpy as np
38
 
39
  def calculate(num1, num2, operation):
40
  if operation == "Add":
@@ -57,17 +56,15 @@ demo = gr.Interface(
57
  ],
58
  outputs=gr.Textbox(label="Result"),
59
  title="Simple Calculator",
60
- description="Perform basic arithmetic operations",
61
- examples=[
62
- [5, 3, "Add"],
63
- [10, 4, "Subtract"],
64
- [6, 7, "Multiply"],
65
- [20, 4, "Divide"]
66
- ]
67
  )
68
- """,
69
-
70
- "image_filter": """
 
 
 
 
71
  import gradio as gr
72
  import numpy as np
73
  from PIL import Image
@@ -100,127 +97,82 @@ demo = gr.Interface(
100
  gr.Radio(["Grayscale", "Invert", "Sepia"], label="Filter")
101
  ],
102
  outputs=gr.Image(type="pil"),
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)
 
 
 
 
1
  import gradio as gr
 
 
2
  import os
3
+ import sys
4
  from pathlib import Path
5
+ import importlib.util
6
 
7
+ # Create examples directory
8
  EXAMPLES_DIR = Path("examples")
9
  EXAMPLES_DIR.mkdir(exist_ok=True)
10
 
11
+ # Pre-defined Gradio examples
 
 
 
 
 
12
  EXAMPLES = {
13
+ "hello_world": {
14
+ "title": "Hello World Greeter",
15
+ "description": "A simple app that greets you by name",
16
+ "code": """
17
  import gradio as gr
18
 
19
  def greet(name):
 
21
 
22
  demo = gr.Interface(
23
  fn=greet,
24
+ inputs=gr.Textbox(label="Your Name"),
25
  outputs=gr.Textbox(label="Greeting"),
26
+ title="Hello World Greeter",
27
+ description="A simple app that greets you by name"
 
28
  )
29
+ """
30
+ },
31
+
32
+ "calculator": {
33
+ "title": "Simple Calculator",
34
+ "description": "Perform basic arithmetic operations",
35
+ "code": """
36
  import gradio as gr
 
37
 
38
  def calculate(num1, num2, operation):
39
  if operation == "Add":
 
56
  ],
57
  outputs=gr.Textbox(label="Result"),
58
  title="Simple Calculator",
59
+ description="Perform basic arithmetic operations"
 
 
 
 
 
 
60
  )
61
+ """
62
+ },
63
+
64
+ "image_filter": {
65
+ "title": "Image Filter",
66
+ "description": "Apply various filters to your images",
67
+ "code": """
68
  import gradio as gr
69
  import numpy as np
70
  from PIL import Image
 
97
  gr.Radio(["Grayscale", "Invert", "Sepia"], label="Filter")
98
  ],
99
  outputs=gr.Image(type="pil"),
100
+ title="Image Filter",
101
  description="Apply various filters to your images"
102
  )
103
  """
104
+ }
105
  }
106
 
107
+ # Function to load and run a specific example
108
+ def run_example(example_name):
109
+ example = EXAMPLES.get(example_name)
110
+ if not example:
111
+ return None
112
 
113
+ # Create module file
114
+ module_path = EXAMPLES_DIR / f"{example_name}.py"
115
  with open(module_path, "w") as f:
116
+ f.write(example["code"])
 
 
 
 
 
117
 
118
+ try:
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
+ sys.modules[f"examples.{example_name}"] = module
123
+ spec.loader.exec_module(module)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
+ if hasattr(module, 'demo'):
126
+ return module.demo
127
+ except Exception as e:
128
+ print(f"Error loading example {example_name}: {e}")
 
 
129
 
130
+ return None
131
 
132
+ # Main selector interface
133
+ def example_selector():
134
+ """Create a simple selector interface"""
 
135
 
136
+ def select_example(example_name):
137
+ """Callback when an example is selected"""
138
+ demo = run_example(example_name)
139
+ if demo:
140
+ demo.launch(server_name="0.0.0.0", server_port=7860)
141
+ return f"Selected {example_name}, please restart the server to see it."
 
142
 
143
+ demo = gr.Interface(
144
+ fn=select_example,
145
+ inputs=gr.Radio(
146
+ choices=list(EXAMPLES.keys()),
147
+ label="Select an example to run",
148
+ info="Choose one of the examples below"
149
+ ),
150
+ outputs=gr.Textbox(label="Status"),
151
+ title="Gradio Examples Selector",
152
+ description="Select an example from the list to run it.",
153
+ allow_flagging=False
154
+ )
155
 
156
+ return demo
 
 
 
 
 
157
 
158
+ # Get example from environment variables if set
159
+ def get_example_from_env():
160
+ """Check if an example is specified in the environment"""
161
+ return os.environ.get("GRADIO_EXAMPLE", None)
162
 
163
+ # Main application logic
164
+ if __name__ == "__main__":
165
+ # Check if we should load a specific example
166
+ example_name = get_example_from_env()
 
167
 
168
+ if example_name in EXAMPLES:
169
+ demo = run_example(example_name)
170
+ if demo:
171
+ print(f"Running example: {example_name}")
172
+ demo.launch(server_name="0.0.0.0", server_port=7860)
173
+ else:
174
+ print(f"Failed to load example: {example_name}, falling back to selector")
175
+ example_selector().launch(server_name="0.0.0.0", server_port=7860)
176
+ else:
177
+ # Run the selector interface
178
+ example_selector().launch(server_name="0.0.0.0", server_port=7860)