File size: 7,204 Bytes
3304a86 3ebbef2 3304a86 3ebbef2 3304a86 3ebbef2 3304a86 3ebbef2 3304a86 3ebbef2 3304a86 | 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 | import gradio as gr
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import io
def create_dashboard(file, chart_type, x_column, y_column, color_column):
"""Create dashboard based on uploaded dataset"""
if file is None:
return None, "Please upload a CSV file"
try:
# Read the uploaded file
if file.name.endswith('.csv'):
df = pd.read_csv(file.name)
elif file.name.endswith('.xlsx'):
df = pd.read_excel(file.name)
else:
return None, "Please upload a CSV or Excel file"
# Data info
info = f"""
Dataset Info:
- Shape: {df.shape[0]} rows × {df.shape[1]} columns
- Columns: {', '.join(df.columns.tolist())}
- Memory usage: {df.memory_usage().sum()} bytes
"""
# Validate columns exist
if x_column not in df.columns or y_column not in df.columns:
return None, f"Columns not found. Available: {list(df.columns)}"
# Create the chart based on type
if chart_type == "Bar Chart":
fig = px.bar(df, x=x_column, y=y_column,
color=color_column if color_column in df.columns else None,
title=f"{chart_type}: {y_column} by {x_column}")
elif chart_type == "Line Chart":
fig = px.line(df, x=x_column, y=y_column,
color=color_column if color_column in df.columns else None,
title=f"{chart_type}: {y_column} vs {x_column}")
elif chart_type == "Scatter Plot":
fig = px.scatter(df, x=x_column, y=y_column,
color=color_column if color_column in df.columns else None,
title=f"{chart_type}: {y_column} vs {x_column}")
elif chart_type == "Histogram":
fig = px.histogram(df, x=x_column,
color=color_column if color_column in df.columns else None,
title=f"{chart_type}: Distribution of {x_column}")
elif chart_type == "Box Plot":
fig = px.box(df, x=x_column, y=y_column,
color=color_column if color_column in df.columns else None,
title=f"{chart_type}: {y_column} by {x_column}")
elif chart_type == "Multi-Chart Dashboard":
# Create a comprehensive dashboard
fig = make_subplots(
rows=2, cols=2,
subplot_titles=(f'{y_column} by {x_column}',
f'Distribution of {x_column}',
f'Correlation Plot',
'Summary Statistics'),
specs=[[{"type": "bar"}, {"type": "histogram"}],
[{"type": "scatter"}, {"type": "table"}]]
)
# Bar chart
fig.add_trace(
go.Bar(x=df[x_column], y=df[y_column], name="Bar"),
row=1, col=1
)
# Histogram
fig.add_trace(
go.Histogram(x=df[x_column], name="Distribution"),
row=1, col=2
)
# Scatter plot if we have numeric columns
numeric_cols = df.select_dtypes(include=['number']).columns
if len(numeric_cols) >= 2:
fig.add_trace(
go.Scatter(x=df[numeric_cols[0]], y=df[numeric_cols[1]],
mode='markers', name="Correlation"),
row=2, col=1
)
# Summary table
summary_df = df.describe()
fig.add_trace(
go.Table(
header=dict(values=['Statistic'] + list(summary_df.columns)),
cells=dict(values=[summary_df.index] +
[summary_df[col] for col in summary_df.columns])
),
row=2, col=2
)
fig.update_layout(height=800, title="Comprehensive Dashboard")
else:
return None, "Chart type not supported"
# Update layout
fig.update_layout(
template="plotly_white",
width=800,
height=600
)
return fig, info
except Exception as e:
return None, f"Error processing file: {str(e)}"
def get_columns(file):
"""Extract column names from uploaded file"""
if file is None:
return gr.Dropdown(choices=[])
try:
if file.name.endswith('.csv'):
df = pd.read_csv(file.name)
elif file.name.endswith('.xlsx'):
df = pd.read_excel(file.name)
else:
return gr.Dropdown(choices=[])
columns = df.columns.tolist()
return (gr.Dropdown(choices=columns, value=columns[0] if columns else None),
gr.Dropdown(choices=columns, value=columns[1] if len(columns) > 1 else columns[0]),
gr.Dropdown(choices=['None'] + columns, value='None'))
except:
return (gr.Dropdown(choices=[]), gr.Dropdown(choices=[]), gr.Dropdown(choices=[]))
# Create Gradio interface
with gr.Blocks(title="Dynamic Dashboard Creator") as demo:
gr.Markdown("# 📊 Dynamic Dashboard Creator")
gr.Markdown("Upload any CSV/Excel file and create interactive dashboards!")
with gr.Row():
with gr.Column(scale=1):
file_upload = gr.File(
label="Upload Dataset (CSV or Excel)",
file_types=[".csv", ".xlsx"]
)
chart_type = gr.Dropdown(
choices=["Bar Chart", "Line Chart", "Scatter Plot",
"Histogram", "Box Plot", "Multi-Chart Dashboard"],
label="Chart Type",
value="Bar Chart"
)
x_column = gr.Dropdown(
label="X-axis Column",
choices=[]
)
y_column = gr.Dropdown(
label="Y-axis Column",
choices=[]
)
color_column = gr.Dropdown(
label="Color Column (Optional)",
choices=[]
)
create_btn = gr.Button("Create Dashboard", variant="primary")
with gr.Column(scale=2):
plot_output = gr.Plot(label="Dashboard")
info_output = gr.Textbox(label="Dataset Info", lines=5)
# Update column dropdowns when file is uploaded
file_upload.change(
fn=get_columns,
inputs=[file_upload],
outputs=[x_column, y_column, color_column]
)
# Create dashboard when button is clicked
create_btn.click(
fn=create_dashboard,
inputs=[file_upload, chart_type, x_column, y_column, color_column],
outputs=[plot_output, info_output]
)
if __name__ == "__main__":
demo.launch(share=True) |