Upload app.py with huggingface_hub
Browse files
app.py
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
import pandas as pd
|
4 |
+
import numpy as np
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
from PIL import Image
|
7 |
+
import torch
|
8 |
+
import random
|
9 |
+
from datetime import datetime
|
10 |
+
# Set seed for reproducibility
|
11 |
+
random.seed(42)
|
12 |
+
np.random.seed(42)
|
13 |
+
torch.manual_seed(42)
|
14 |
+
# Data generation functions
|
15 |
+
def generate_sample_data():
|
16 |
+
dates = pd.date_range(start='2023-01-01', end='2023-12-31', freq='D')
|
17 |
+
values = np.random.normal(100, 15, len(dates)) + np.sin(np.arange(len(dates)) * 0.1) * 30
|
18 |
+
return pd.DataFrame({
|
19 |
+
'date': dates,
|
20 |
+
'value': values,
|
21 |
+
'category': np.random.choice(['A', 'B', 'C'], len(dates))
|
22 |
+
})
|
23 |
+
def generate_line_chart(df, title="Time Series Data"):
|
24 |
+
fig, ax = plt.subplots(figsize=(12, 6))
|
25 |
+
ax.plot(df['date'], df['value'], marker='', linewidth=2, color='#3366CC')
|
26 |
+
ax.set_title(title, fontsize=16)
|
27 |
+
ax.set_xlabel('Date', fontsize=12)
|
28 |
+
ax.set_ylabel('Value', fontsize=12)
|
29 |
+
ax.grid(True, alpha=0.3)
|
30 |
+
fig.tight_layout()
|
31 |
+
return fig
|
32 |
+
def generate_pie_chart(df, title="Category Distribution"):
|
33 |
+
category_counts = df['category'].value_counts()
|
34 |
+
fig, ax = plt.subplots(figsize=(8, 8))
|
35 |
+
ax.pie(category_counts, labels=category_counts.index, autopct='%1.1f%%',
|
36 |
+
colors=['#3366CC', '#DC3912', '#FF9900'], startangle=90)
|
37 |
+
ax.set_title(title, fontsize=16)
|
38 |
+
fig.tight_layout()
|
39 |
+
return fig
|
40 |
+
def generate_bar_chart(df, title="Monthly Averages"):
|
41 |
+
df['month'] = df['date'].dt.month_name()
|
42 |
+
monthly_avg = df.groupby('month')['value'].mean().reindex([
|
43 |
+
'January', 'February', 'March', 'April', 'May', 'June',
|
44 |
+
'July', 'August', 'September', 'October', 'November', 'December'
|
45 |
+
])
|
46 |
+
fig, ax = plt.subplots(figsize=(12, 6))
|
47 |
+
bars = ax.bar(monthly_avg.index, monthly_avg.values, color='#3366CC')
|
48 |
+
# Add value labels on top of each bar
|
49 |
+
for bar in bars:
|
50 |
+
height = bar.get_height()
|
51 |
+
ax.text(bar.get_x() + bar.get_width()/2., height + 1,
|
52 |
+
f'{height:.1f}', ha='center', va='bottom', fontsize=9)
|
53 |
+
ax.set_title(title, fontsize=16)
|
54 |
+
ax.set_xlabel('Month', fontsize=12)
|
55 |
+
ax.set_ylabel('Average Value', fontsize=12)
|
56 |
+
plt.xticks(rotation=45, ha='right')
|
57 |
+
fig.tight_layout()
|
58 |
+
return fig
|
59 |
+
# Image processing functions
|
60 |
+
def apply_filter(image, filter_type):
|
61 |
+
img = np.array(image)
|
62 |
+
if filter_type == "Grayscale":
|
63 |
+
# Convert to grayscale
|
64 |
+
if len(img.shape) == 3 and img.shape[2] == 3: # Ensure it's an RGB image
|
65 |
+
return Image.fromarray(np.dot(img[...,:3], [0.2989, 0.5870, 0.1140]).astype(np.uint8))
|
66 |
+
return image
|
67 |
+
elif filter_type == "Sepia":
|
68 |
+
# Apply sepia filter
|
69 |
+
if len(img.shape) == 3 and img.shape[2] == 3: # Ensure it's an RGB image
|
70 |
+
sepia_filter = np.array([
|
71 |
+
[0.393, 0.769, 0.189],
|
72 |
+
[0.349, 0.686, 0.168],
|
73 |
+
[0.272, 0.534, 0.131]
|
74 |
+
])
|
75 |
+
sepia_img = np.clip(np.dot(img[...,:3], sepia_filter.T), 0, 255).astype(np.uint8)
|
76 |
+
return Image.fromarray(sepia_img)
|
77 |
+
return image
|
78 |
+
elif filter_type == "Negative":
|
79 |
+
# Create negative
|
80 |
+
return Image.fromarray(255 - img)
|
81 |
+
elif filter_type == "Blur":
|
82 |
+
# Simple blur using PIL
|
83 |
+
from PIL import ImageFilter
|
84 |
+
return image.filter(ImageFilter.GaussianBlur(radius=3))
|
85 |
+
else:
|
86 |
+
return image
|
87 |
+
# Define theme
|
88 |
+
theme = gr.themes.Soft(
|
89 |
+
primary_hue="indigo",
|
90 |
+
secondary_hue="blue",
|
91 |
+
neutral_hue="gray"
|
92 |
+
)
|
93 |
+
# Main application
|
94 |
+
def create_dashboard():
|
95 |
+
sample_data = generate_sample_data()
|
96 |
+
with gr.Blocks(theme=theme) as app:
|
97 |
+
gr.Markdown("# Interactive Data Visualization & Image Processing Dashboard")
|
98 |
+
with gr.Tab("Data Visualization"):
|
99 |
+
gr.Markdown("### Explore sample time series data with various visualizations")
|
100 |
+
with gr.Row():
|
101 |
+
with gr.Column(scale=1):
|
102 |
+
refresh_btn = gr.Button("Generate New Data")
|
103 |
+
custom_title = gr.Textbox(label="Chart Title", value="Time Series Analysis")
|
104 |
+
with gr.Column(scale=3):
|
105 |
+
with gr.Tabs():
|
106 |
+
with gr.TabItem("Line Chart"):
|
107 |
+
line_chart = gr.Plot(label="Time Series Line Chart")
|
108 |
+
with gr.TabItem("Bar Chart"):
|
109 |
+
bar_chart = gr.Plot(label="Monthly Average Bar Chart")
|
110 |
+
with gr.TabItem("Pie Chart"):
|
111 |
+
pie_chart = gr.Plot(label="Category Distribution")
|
112 |
+
def update_charts(title):
|
113 |
+
data = generate_sample_data()
|
114 |
+
return {
|
115 |
+
line_chart: generate_line_chart(data, title if title else "Time Series Data"),
|
116 |
+
bar_chart: generate_bar_chart(data, title if title else "Monthly Averages"),
|
117 |
+
pie_chart: generate_pie_chart(data, title if title else "Category Distribution")
|
118 |
+
}
|
119 |
+
refresh_btn.click(fn=update_charts, inputs=[custom_title], outputs=[line_chart, bar_chart, pie_chart])
|
120 |
+
custom_title.change(fn=update_charts, inputs=[custom_title], outputs=[line_chart, bar_chart, pie_chart])
|
121 |
+
with gr.Tab("Image Processing"):
|
122 |
+
gr.Markdown("### Apply filters to your images")
|
123 |
+
with gr.Row():
|
124 |
+
with gr.Column():
|
125 |
+
input_image = gr.Image(label="Upload Image", type="pil")
|
126 |
+
filter_type = gr.Radio(
|
127 |
+
["Original", "Grayscale", "Sepia", "Negative", "Blur"],
|
128 |
+
label="Select Filter",
|
129 |
+
value="Original"
|
130 |
+
)
|
131 |
+
apply_btn = gr.Button("Apply Filter")
|
132 |
+
with gr.Column():
|
133 |
+
output_image = gr.Image(label="Filtered Image", type="pil")
|
134 |
+
def process_image(image, filter_choice):
|
135 |
+
if image is None:
|
136 |
+
return None
|
137 |
+
if filter_choice == "Original":
|
138 |
+
return image
|
139 |
+
return apply_filter(image, filter_choice)
|
140 |
+
apply_btn.click(fn=process_image, inputs=[input_image, filter_type], outputs=output_image)
|
141 |
+
filter_type.change(fn=process_image, inputs=[input_image, filter_type], outputs=output_image)
|
142 |
+
with gr.Tab("About"):
|
143 |
+
gr.Markdown(f"""
|
144 |
+
## About this Application
|
145 |
+
This is a demo dashboard showcasing Gradio's capabilities for creating interactive data visualization and image processing applications.
|
146 |
+
### Features:
|
147 |
+
- **Data Visualization**: Generate and explore random time series data with line charts, bar charts, and pie charts
|
148 |
+
- **Image Processing**: Apply various filters to your images
|
149 |
+
### Technologies:
|
150 |
+
- Built with Python and Gradio
|
151 |
+
- Uses Matplotlib for data visualization
|
152 |
+
- PIL for image processing
|
153 |
+
Created on: {datetime.now().strftime("%B %d, %Y")}
|
154 |
+
""")
|
155 |
+
# Initialize charts on page load
|
156 |
+
app.load(
|
157 |
+
fn=update_charts,
|
158 |
+
inputs=[custom_title],
|
159 |
+
outputs=[line_chart, bar_chart, pie_chart],
|
160 |
+
)
|
161 |
+
return app
|
162 |
+
if __name__ == '__main__':
|
163 |
+
dashboard = create_dashboard()
|
164 |
+
dashboard.launch()
|
165 |
+
|
166 |
+
if __name__ == '__main__':
|
167 |
+
demo.launch()
|