|
import os |
|
import gradio as gr |
|
import pandas as pd |
|
import numpy as np |
|
import matplotlib.pyplot as plt |
|
from PIL import Image |
|
import torch |
|
import random |
|
from datetime import datetime |
|
|
|
random.seed(42) |
|
np.random.seed(42) |
|
torch.manual_seed(42) |
|
|
|
def generate_sample_data(): |
|
dates = pd.date_range(start='2023-01-01', end='2023-12-31', freq='D') |
|
values = np.random.normal(100, 15, len(dates)) + np.sin(np.arange(len(dates)) * 0.1) * 30 |
|
return pd.DataFrame({ |
|
'date': dates, |
|
'value': values, |
|
'category': np.random.choice(['A', 'B', 'C'], len(dates)) |
|
}) |
|
def generate_line_chart(df, title="Time Series Data"): |
|
fig, ax = plt.subplots(figsize=(12, 6)) |
|
ax.plot(df['date'], df['value'], marker='', linewidth=2, color='#3366CC') |
|
ax.set_title(title, fontsize=16) |
|
ax.set_xlabel('Date', fontsize=12) |
|
ax.set_ylabel('Value', fontsize=12) |
|
ax.grid(True, alpha=0.3) |
|
fig.tight_layout() |
|
return fig |
|
def generate_pie_chart(df, title="Category Distribution"): |
|
category_counts = df['category'].value_counts() |
|
fig, ax = plt.subplots(figsize=(8, 8)) |
|
ax.pie(category_counts, labels=category_counts.index, autopct='%1.1f%%', |
|
colors=['#3366CC', '#DC3912', '#FF9900'], startangle=90) |
|
ax.set_title(title, fontsize=16) |
|
fig.tight_layout() |
|
return fig |
|
def generate_bar_chart(df, title="Monthly Averages"): |
|
df['month'] = df['date'].dt.month_name() |
|
monthly_avg = df.groupby('month')['value'].mean().reindex([ |
|
'January', 'February', 'March', 'April', 'May', 'June', |
|
'July', 'August', 'September', 'October', 'November', 'December' |
|
]) |
|
fig, ax = plt.subplots(figsize=(12, 6)) |
|
bars = ax.bar(monthly_avg.index, monthly_avg.values, color='#3366CC') |
|
|
|
for bar in bars: |
|
height = bar.get_height() |
|
ax.text(bar.get_x() + bar.get_width()/2., height + 1, |
|
f'{height:.1f}', ha='center', va='bottom', fontsize=9) |
|
ax.set_title(title, fontsize=16) |
|
ax.set_xlabel('Month', fontsize=12) |
|
ax.set_ylabel('Average Value', fontsize=12) |
|
plt.xticks(rotation=45, ha='right') |
|
fig.tight_layout() |
|
return fig |
|
|
|
def apply_filter(image, filter_type): |
|
img = np.array(image) |
|
if filter_type == "Grayscale": |
|
|
|
if len(img.shape) == 3 and img.shape[2] == 3: |
|
return Image.fromarray(np.dot(img[...,:3], [0.2989, 0.5870, 0.1140]).astype(np.uint8)) |
|
return image |
|
elif filter_type == "Sepia": |
|
|
|
if len(img.shape) == 3 and img.shape[2] == 3: |
|
sepia_filter = np.array([ |
|
[0.393, 0.769, 0.189], |
|
[0.349, 0.686, 0.168], |
|
[0.272, 0.534, 0.131] |
|
]) |
|
sepia_img = np.clip(np.dot(img[...,:3], sepia_filter.T), 0, 255).astype(np.uint8) |
|
return Image.fromarray(sepia_img) |
|
return image |
|
elif filter_type == "Negative": |
|
|
|
return Image.fromarray(255 - img) |
|
elif filter_type == "Blur": |
|
|
|
from PIL import ImageFilter |
|
return image.filter(ImageFilter.GaussianBlur(radius=3)) |
|
else: |
|
return image |
|
|
|
theme = gr.themes.Soft( |
|
primary_hue="indigo", |
|
secondary_hue="blue", |
|
neutral_hue="gray" |
|
) |
|
|
|
def create_dashboard(): |
|
sample_data = generate_sample_data() |
|
with gr.Blocks(theme=theme) as app: |
|
gr.Markdown("# Interactive Data Visualization & Image Processing Dashboard") |
|
with gr.Tab("Data Visualization"): |
|
gr.Markdown("### Explore sample time series data with various visualizations") |
|
with gr.Row(): |
|
with gr.Column(scale=1): |
|
refresh_btn = gr.Button("Generate New Data") |
|
custom_title = gr.Textbox(label="Chart Title", value="Time Series Analysis") |
|
with gr.Column(scale=3): |
|
with gr.Tabs(): |
|
with gr.TabItem("Line Chart"): |
|
line_chart = gr.Plot(label="Time Series Line Chart") |
|
with gr.TabItem("Bar Chart"): |
|
bar_chart = gr.Plot(label="Monthly Average Bar Chart") |
|
with gr.TabItem("Pie Chart"): |
|
pie_chart = gr.Plot(label="Category Distribution") |
|
def update_charts(title): |
|
data = generate_sample_data() |
|
return { |
|
line_chart: generate_line_chart(data, title if title else "Time Series Data"), |
|
bar_chart: generate_bar_chart(data, title if title else "Monthly Averages"), |
|
pie_chart: generate_pie_chart(data, title if title else "Category Distribution") |
|
} |
|
refresh_btn.click(fn=update_charts, inputs=[custom_title], outputs=[line_chart, bar_chart, pie_chart]) |
|
custom_title.change(fn=update_charts, inputs=[custom_title], outputs=[line_chart, bar_chart, pie_chart]) |
|
with gr.Tab("Image Processing"): |
|
gr.Markdown("### Apply filters to your images") |
|
with gr.Row(): |
|
with gr.Column(): |
|
input_image = gr.Image(label="Upload Image", type="pil") |
|
filter_type = gr.Radio( |
|
["Original", "Grayscale", "Sepia", "Negative", "Blur"], |
|
label="Select Filter", |
|
value="Original" |
|
) |
|
apply_btn = gr.Button("Apply Filter") |
|
with gr.Column(): |
|
output_image = gr.Image(label="Filtered Image", type="pil") |
|
def process_image(image, filter_choice): |
|
if image is None: |
|
return None |
|
if filter_choice == "Original": |
|
return image |
|
return apply_filter(image, filter_choice) |
|
apply_btn.click(fn=process_image, inputs=[input_image, filter_type], outputs=output_image) |
|
filter_type.change(fn=process_image, inputs=[input_image, filter_type], outputs=output_image) |
|
with gr.Tab("About"): |
|
gr.Markdown(f""" |
|
## About this Application |
|
This is a demo dashboard showcasing Gradio's capabilities for creating interactive data visualization and image processing applications. |
|
### Features: |
|
- **Data Visualization**: Generate and explore random time series data with line charts, bar charts, and pie charts |
|
- **Image Processing**: Apply various filters to your images |
|
### Technologies: |
|
- Built with Python and Gradio |
|
- Uses Matplotlib for data visualization |
|
- PIL for image processing |
|
Created on: {datetime.now().strftime("%B %d, %Y")} |
|
""") |
|
|
|
app.load( |
|
fn=update_charts, |
|
inputs=[custom_title], |
|
outputs=[line_chart, bar_chart, pie_chart], |
|
) |
|
return app |
|
if __name__ == '__main__': |
|
dashboard = create_dashboard() |
|
dashboard.launch() |
|
|
|
if __name__ == '__main__': |
|
demo.launch() |