nik88 / app.py
nikwagh's picture
Update app.py
547b137 verified
Raw History Blame Contribute Delete
4.1 kB
"""
CSV Explorer - Gradio App
Loads CSV files from the Datablist GitHub repository and provides interactive visualizations.
"""
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import gradio as gr
import io
import requests
# --- Base path for Datablist CSV files ---
BASE_URL = "https://raw.githubusercontent.com/datablist/sample-csv-files/main/files/"
# --- Available sample files ---
CSV_FILES = {
"People (100 rows)": "people-100.csv",
"Companies (500 rows)": "companies-500.csv",
"Addresses (1000 rows)": "addresses-1000.csv",
"Products (1000 rows)": "products-1000.csv",
"Customers (100 rows)": "customers-100.csv",
"US States (50 rows)": "us-states.csv",
}
# --- Load CSV from URL ---
def load_csv(file_name):
"""Load CSV from Datablist GitHub raw link."""
url = BASE_URL + file_name
try:
response = requests.get(url)
response.raise_for_status()
df = pd.read_csv(io.StringIO(response.text))
return df
except Exception as e:
raise ValueError(f"Error loading CSV: {e}")
# --- Visualization helpers ---
def plot_categorical(df):
"""Plot frequency of the first categorical column."""
cat_cols = df.select_dtypes("object").columns
fig, ax = plt.subplots(figsize=(5, 3))
if len(cat_cols) == 0:
ax.text(0.5, 0.5, "No categorical columns", ha="center")
return fig
col = cat_cols[0]
df[col].value_counts().head(10).plot(kind="bar", ax=ax)
ax.set_title(f"Top 10 Values in '{col}'")
plt.tight_layout()
return fig
def plot_numeric_corr(df):
"""Plot correlation heatmap for numeric columns."""
fig, ax = plt.subplots(figsize=(5, 4))
num = df.select_dtypes("number")
if num.empty:
ax.text(0.5, 0.5, "No numeric columns", ha="center")
return fig
sns.heatmap(num.corr(), annot=True, fmt=".2f", ax=ax)
ax.set_title("Numeric Correlation Heatmap")
plt.tight_layout()
return fig
def plot_pair(df):
"""Pairplot for numeric columns (limited to 4 to avoid heavy rendering)."""
num = df.select_dtypes("number")
if num.shape[1] > 4:
num = num.iloc[:, :4]
if num.empty:
fig, ax = plt.subplots()
ax.text(0.5, 0.5, "No numeric columns for pairplot", ha="center")
return fig
sns.pairplot(num)
plt.tight_layout()
return plt.gcf()
# --- Gradio App ---
def build_app():
with gr.Blocks(title="CSV Explorer - Datablist") as demo:
gr.Markdown(
"""
# πŸ“Š CSV Explorer (Datablist Edition)
Explore and visualize sample CSV files from the Datablist GitHub repository.
Select a dataset below to load it automatically and view:
- 🧾 Data preview
- πŸ“ˆ Summary statistics
- πŸ” Auto-generated visualizations
"""
)
with gr.Row():
file_choice = gr.Dropdown(
choices=list(CSV_FILES.keys()),
value="People (100 rows)",
label="Choose Sample CSV File",
)
load_btn = gr.Button("πŸ”„ Load & Visualize")
with gr.Tab("Table & Summary"):
table = gr.Dataframe(label="Data Preview")
summary = gr.Dataframe(label="Summary Statistics")
with gr.Tab("Visualizations"):
fig1 = gr.Plot(label="Categorical Distribution")
fig2 = gr.Plot(label="Correlation Heatmap")
fig3 = gr.Plot(label="Pair Plot")
def update(choice):
df = load_csv(CSV_FILES[choice])
summary_df = df.describe(include="all").transpose().reset_index()
return (
df.head(50),
summary_df,
plot_categorical(df),
plot_numeric_corr(df),
plot_pair(df),
)
load_btn.click(fn=update, inputs=[file_choice], outputs=[table, summary, fig1, fig2, fig3])
return demo
if __name__ == "__main__":
app = build_app()
app.launch(server_name="0.0.0.0", server_port=7860)