nakas commited on
Commit
46e69b0
·
verified ·
1 Parent(s): ad801de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -135
app.py CHANGED
@@ -1,40 +1,16 @@
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):
20
  return f"Hello, {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":
40
  return num1 + num2
@@ -47,28 +23,7 @@ def calculate(num1, num2, operation):
47
  return "Error: Division by zero"
48
  return num1 / num2
49
 
50
- demo = gr.Interface(
51
- fn=calculate,
52
- inputs=[
53
- gr.Number(label="First Number"),
54
- gr.Number(label="Second Number"),
55
- gr.Radio(["Add", "Subtract", "Multiply", "Divide"], label="Operation")
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
71
-
72
  def apply_filter(image, filter_type):
73
  if image is None:
74
  return None
@@ -90,89 +45,57 @@ def apply_filter(image, filter_type):
90
  return Image.fromarray(sepia_img.astype(np.uint8))
91
  return image
92
 
93
- demo = gr.Interface(
94
- fn=apply_filter,
95
- inputs=[
96
- gr.Image(type="pil"),
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)
 
1
  import gradio as gr
2
+ import numpy as np
3
+ from PIL import Image
 
 
 
 
 
 
4
 
5
+ # Simple function to set matplotlib config dir
6
+ import os
7
+ os.environ['MPLCONFIGDIR'] = '/tmp'
 
 
 
 
8
 
9
+ # Hello World example function
10
  def greet(name):
11
  return f"Hello, {name}!"
12
 
13
+ # Calculator example function
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def calculate(num1, num2, operation):
15
  if operation == "Add":
16
  return num1 + num2
 
23
  return "Error: Division by zero"
24
  return num1 / num2
25
 
26
+ # Image filter example function
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  def apply_filter(image, filter_type):
28
  if image is None:
29
  return None
 
45
  return Image.fromarray(sepia_img.astype(np.uint8))
46
  return image
47
 
48
+ # Create a Gradio app with all examples presented side by side
49
+ with gr.Blocks(title="Gradio Examples") as demo:
50
+ gr.Markdown("# Gradio Examples")
51
+ gr.Markdown("This app demonstrates three simple Gradio examples: Hello World, Calculator, and Image Filter.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
+ # Layout the examples in a grid
54
+ with gr.Tabs():
55
+ with gr.Tab("Hello World"):
56
+ with gr.Box():
57
+ gr.Markdown("## Hello World Example")
58
+ gr.Markdown("A simple app that greets you by name.")
59
+
60
+ name_input = gr.Textbox(label="Your Name", value="World")
61
+ greet_btn = gr.Button("Say Hello")
62
+ greeting_output = gr.Textbox(label="Greeting")
63
+
64
+ greet_btn.click(fn=greet, inputs=name_input, outputs=greeting_output)
65
 
66
+ with gr.Tab("Calculator"):
67
+ with gr.Box():
68
+ gr.Markdown("## Simple Calculator")
69
+ gr.Markdown("Perform basic arithmetic operations between two numbers.")
70
+
71
+ num1 = gr.Number(label="First Number", value=5)
72
+ num2 = gr.Number(label="Second Number", value=3)
73
+ operation = gr.Radio(
74
+ ["Add", "Subtract", "Multiply", "Divide"],
75
+ label="Operation",
76
+ value="Add"
77
+ )
78
+ calc_btn = gr.Button("Calculate")
79
+ result = gr.Textbox(label="Result")
80
+
81
+ calc_btn.click(fn=calculate, inputs=[num1, num2, operation], outputs=result)
82
+
83
+ with gr.Tab("Image Filter"):
84
+ with gr.Box():
85
+ gr.Markdown("## Image Filter")
86
+ gr.Markdown("Apply various filters to images.")
87
+
88
+ image_input = gr.Image(type="pil", label="Input Image")
89
+ filter_type = gr.Radio(
90
+ ["Grayscale", "Invert", "Sepia"],
91
+ label="Filter Type",
92
+ value="Grayscale"
93
+ )
94
+ filter_btn = gr.Button("Apply Filter")
95
+ filtered_image = gr.Image(label="Filtered Image")
96
+
97
+ filter_btn.click(fn=apply_filter, inputs=[image_input, filter_type], outputs=filtered_image)
 
 
 
 
 
98
 
99
+ # Launch the app
100
  if __name__ == "__main__":
101
+ demo.launch(server_name="0.0.0.0", server_port=7860)