File size: 8,860 Bytes
20706fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import gradio as gr
import pandas as pd
import numpy as np

# Simple Gradio examples
def simple_greet(name):
    return f"Hello {name}!"

def simple_calculator(x, y, operation):
    if operation == "add":
        return x + y
    elif operation == "subtract":
        return x - y
    elif operation == "multiply":
        return x * y
    elif operation == "divide":
        return x / y if y != 0 else "Cannot divide by zero"

# Simple interface examples (uncomment to use)
# demo1 = gr.Interface(
#     fn=simple_greet,
#     inputs="text",
#     outputs="text",
#     title="Simple Greeter"
# )

# demo2 = gr.Interface(
#     fn=simple_calculator,
#     inputs=[
#         gr.Number(label="First Number"),
#         gr.Number(label="Second Number"), 
#         gr.Radio(["add", "subtract", "multiply", "divide"], label="Operation")
#     ],
#     outputs="text",
#     title="Calculator"
# )

def analyze_data(csv_file, chart_type):
    """Analyze uploaded CSV and return info"""
    if csv_file is None:
        return "Please upload a CSV file"
    
    try:
        # Read the CSV file
        df = pd.read_csv(csv_file.name)
        
        # Get basic info
        info = f"""๐Ÿ“Š Dataset Analysis:
        
๐Ÿ”ข Shape: {df.shape[0]} rows ร— {df.shape[1]} columns
๐Ÿ“ Columns: {', '.join(df.columns.tolist())}
โŒ Missing values: {df.isnull().sum().sum()}

๐Ÿ“ˆ Numeric columns: {len(df.select_dtypes(include=['number']).columns)}
๐Ÿ“‹ Text columns: {len(df.select_dtypes(include=['object']).columns)}

๐Ÿ’ก Chart type selected: {chart_type}

๐Ÿ“‹ First 5 rows preview:
{df.head().to_string()}

๐Ÿ“Š Summary statistics:
{df.describe().to_string() if len(df.select_dtypes(include=['number']).columns) > 0 else 'No numeric data for statistics'}
        """
        return info
        
    except Exception as e:
        return f"Error reading file: {str(e)}"

def greet(name, enthusiasm):
    """Simple greeting function"""
    excitement = "!" * int(enthusiasm)
    return f"Hello {name}{excitement}"

def calculator(num1, operation, num2):
    """Simple calculator"""
    if operation == "Add":
        return num1 + num2
    elif operation == "Subtract":
        return num1 - num2
    elif operation == "Multiply":
        return num1 * num2
    elif operation == "Divide":
        return num1 / num2 if num2 != 0 else "Cannot divide by zero!"

# Create Gradio interface with tabs
with gr.Blocks(title="Gradio Demo App") as demo:
    gr.Markdown("# ๐Ÿš€ Gradio Demo Application")
    gr.Markdown("This demo showcases various Gradio components and functionalities.")
    
    with gr.Tab("๐Ÿ“Š Data Analysis"):
        gr.Markdown("## Upload CSV and Create Visualizations")
        
        with gr.Row():
            with gr.Column():
                csv_input = gr.File(label="Upload CSV File", file_types=[".csv"])
                chart_dropdown = gr.Dropdown(
                    choices=["Histogram", "Scatter Plot"], 
                    label="Chart Type",
                    value="Histogram"
                )
                analyze_btn = gr.Button("Analyze Data", variant="primary")
            
            with gr.Column():
                info_output = gr.Textbox(label="Dataset Info", lines=15, max_lines=20)
        
        analyze_btn.click(
            fn=analyze_data,
            inputs=[csv_input, chart_dropdown],
            outputs=info_output
        )
    
    with gr.Tab("๐Ÿ‘‹ Greeting"):
        gr.Markdown("## Personal Greeting Generator")
        
        with gr.Row():
            name_input = gr.Textbox(label="Your Name", placeholder="Enter your name")
            enthusiasm_slider = gr.Slider(1, 10, value=3, label="Enthusiasm Level")
        
        greet_output = gr.Textbox(label="Greeting")
        greet_btn = gr.Button("Generate Greeting")
        
        greet_btn.click(
            fn=greet,
            inputs=[name_input, enthusiasm_slider],
            outputs=greet_output
        )
    
    with gr.Tab("๐Ÿงฎ Calculator"):
        gr.Markdown("## Simple Calculator")
        
        with gr.Row():
            num1_input = gr.Number(label="First Number", value=0)
            operation_radio = gr.Radio(
                choices=["Add", "Subtract", "Multiply", "Divide"],
                label="Operation",
                value="Add"
            )
            num2_input = gr.Number(label="Second Number", value=0)
        
        calc_output = gr.Number(label="Result")
        calc_btn = gr.Button("Calculate", variant="secondary")
        
        calc_btn.click(
            fn=calculator,
            inputs=[num1_input, operation_radio, num2_input],
            outputs=calc_output
        )
    
    with gr.Tab("๐ŸŽจ Interactive Demo"):
        gr.Markdown("## Real-time Updates")
        
        with gr.Row():
            slider_input = gr.Slider(0, 100, value=50, label="Value")
            checkbox_input = gr.Checkbox(label="Enable Processing", value=True)
        
        with gr.Row():
            text_output = gr.Textbox(label="Live Output")
            number_output = gr.Number(label="Processed Value")
        
        def process_inputs(value, enabled):
            if enabled:
                processed = value * 1.5
                message = f"Processing enabled: {value} โ†’ {processed}"
                return message, processed
            else:
                return "Processing disabled", value
        
        # Real-time updates
        slider_input.change(
            fn=process_inputs,
            inputs=[slider_input, checkbox_input],
            outputs=[text_output, number_output]
        )
        checkbox_input.change(
            fn=process_inputs,
            inputs=[slider_input, checkbox_input],
            outputs=[text_output, number_output]
        )
    
    with gr.Tab("๐Ÿ“ Basic Examples"):
        gr.Markdown("## Simple Gradio Code Examples")
        
        gr.Markdown("""
        ### Example 1: Simple Greeter
        ```python
        def greet(name):
            return f"Hello {name}!"
        
        demo = gr.Interface(
            fn=greet,
            inputs="text",
            outputs="text"
        )
        ```
        """)
        
        with gr.Row():
            simple_name = gr.Textbox(label="Your Name", placeholder="Enter name")
            simple_greet_output = gr.Textbox(label="Greeting")
        
        simple_greet_btn = gr.Button("Greet Me!")
        simple_greet_btn.click(
            fn=simple_greet,
            inputs=simple_name,
            outputs=simple_greet_output
        )
        
        gr.Markdown("""
        ### Example 2: Calculator with Interface
        ```python
        def calculator(x, y, operation):
            if operation == "add":
                return x + y
            # ... other operations
        
        demo = gr.Interface(
            fn=calculator,
            inputs=[
                gr.Number(label="First Number"),
                gr.Number(label="Second Number"), 
                gr.Radio(["add", "subtract", "multiply", "divide"])
            ],
            outputs="text"
        )
        ```
        """)
        
        with gr.Row():
            calc_x = gr.Number(label="X", value=0)
            calc_y = gr.Number(label="Y", value=0)
            calc_op = gr.Radio(["add", "subtract", "multiply", "divide"], 
                              label="Operation", value="add")
        
        calc_result = gr.Textbox(label="Result")
        calc_btn = gr.Button("Calculate")
        
        calc_btn.click(
            fn=simple_calculator,
            inputs=[calc_x, calc_y, calc_op],
            outputs=calc_result
        )
        
        gr.Markdown("""
        ### Example 3: Custom Layout with Blocks
        ```python
        with gr.Blocks() as demo:
            gr.Markdown("# My App")
            
            with gr.Row():
                input1 = gr.Textbox()
                input2 = gr.Slider()
            
            output = gr.Textbox()
            btn = gr.Button("Process")
            
            btn.click(fn=my_function, inputs=[input1, input2], outputs=output)
        
        demo.launch()
        ```
        """)
        
        gr.Markdown("**Key Components:**")
        gr.Markdown("- `gr.Interface()` - Simple wrapper")
        gr.Markdown("- `gr.Blocks()` - Custom layouts")
        gr.Markdown("- `gr.Row()`, `gr.Column()` - Layout containers")
        gr.Markdown("- `gr.Textbox()`, `gr.Number()`, `gr.Slider()` - Input components")
        gr.Markdown("- `demo.launch()` - Start the server")

# Launch the app
if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",  # Allow external access
        server_port=7861,       # Different port from Dash app
        share=False,           # Set to True to create public link
        debug=True             # Enable debug mode
    )