nik77 / app.py
nikwagh's picture
Update app.py
93c31e4 verified
Raw History Blame Contribute Delete
8.22 kB
"""
Gradio app: Titanic dataset automatic load (seaborn or Hugging Face) + interactive visualizations
Save this file as `app.py` for Hugging Face Spaces (Gradio) or run locally.
Requirements (put in requirements.txt):
# requirements.txt
# gradio==3.45.0 # or latest
# pandas
# seaborn
# matplotlib
# datasets
# scikit-learn
# plotly
This app will:
- Auto-load Titanic from seaborn by default. If `datasets` (Hugging Face) titanic is available it will try that first.
- Provide filters (sex, Pclass, embarked, age range)
- Show table, summary stats and multiple plots (survival by class/sex, age vs fare scatter, correlation heatmap)
"""
import io
import math
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from datasets import load_dataset
import gradio as gr
# ---------- Data loading helpers ----------
def load_titanic(source="auto"):
"""Try to load titanic from Hugging Face datasets; fall back to seaborn."""
if source in ("hf", "auto"):
try:
ds = load_dataset("titanic")
# datasets returns a dict with splits; try to concat all splits if present
if isinstance(ds, dict):
# pick the first split and convert; many HF titanic packages have 'train'
first = list(ds.keys())[0]
df = pd.DataFrame(ds[first])
else:
df = pd.DataFrame(ds)
# ensure columns consistent with seaborn's titanic where possible
# rename common columns if found
rename_map = {}
if "survived" in df.columns and "survived" not in df.columns:
pass
# drop any list/struct columns
for c in df.columns:
if df[c].apply(lambda x: isinstance(x, (list, dict))).any():
df[c] = df[c].astype(str)
return df
except Exception:
if source == "hf":
raise
# else fall through to seaborn
# seaborn fallback
try:
df = sns.load_dataset("titanic")
return df
except Exception as e:
raise RuntimeError("Failed to load Titanic dataset from Hugging Face and seaborn: " + str(e))
# ---------- Utility / plotting functions ----------
def filter_df(df, sex, pclass, embarked, age_min, age_max):
d = df.copy()
if sex and sex != "all":
d = d[d["sex"] == sex]
if pclass and pclass != "all":
# some datasets use 'pclass' and some 'class'
if "pclass" in d.columns:
d = d[d["pclass"] == int(pclass)]
elif "class" in d.columns:
# seaborn has classes like 'First', but also numeric 'pclass' in some versions
try:
d = d[d["class"] == int(pclass)]
except Exception:
# try mapping 1->"First" etc
mapping = {1: "First", 2: "Second", 3: "Third"}
d = d[d["class"] == mapping.get(int(pclass), str(pclass))]
if embarked and embarked != "all":
if "embarked" in d.columns:
d = d[d["embarked"] == embarked]
# age filtering - many datasets have NaN ages
if "age" in d.columns:
d = d[d["age"].notna()]
d = d[(d["age"] >= age_min) & (d["age"] <= age_max)]
return d
def plot_survival_by_category(df, category="pclass"):
fig, ax = plt.subplots(figsize=(6,4))
# normalize for percent survived
if category not in df.columns:
return fig
grouped = df.groupby(category)["survived"].mean().sort_index()
grouped.plot(kind="bar", ax=ax)
ax.set_ylabel("Survival rate (fraction)")
ax.set_title(f"Survival rate by {category}")
plt.tight_layout()
return fig
def plot_age_vs_fare(df):
fig, ax = plt.subplots(figsize=(6,4))
if not ("age" in df.columns and "fare" in df.columns):
return fig
scatter = ax.scatter(df["age"], df["fare"], c=df.get("survived", pd.Series([0]*len(df))), alpha=0.6)
ax.set_xlabel("age")
ax.set_ylabel("fare")
ax.set_title("Age vs Fare (color = survived)")
plt.tight_layout()
return fig
def plot_correlation_heatmap(df):
# select numeric cols
num = df.select_dtypes(include=["number"]).dropna(axis=1, how="all")
if num.shape[1] < 2:
fig, ax = plt.subplots()
ax.text(0.5, 0.5, "Not enough numeric columns for correlation", ha="center")
return fig
corr = num.corr()
fig, ax = plt.subplots(figsize=(6,5))
sns.heatmap(corr, annot=True, fmt=".2f", ax=ax)
ax.set_title("Correlation matrix")
plt.tight_layout()
return fig
def get_summary_table(df):
return df.describe(include='all')
# ---------- Gradio app layout & callbacks ----------
# load default dataset at import time so Spaces will cache it
try:
DEFAULT_DF = load_titanic("auto")
except Exception as e:
DEFAULT_DF = pd.DataFrame()
def build_interface():
with gr.Blocks() as demo:
gr.Markdown("# Titanic Explorer — Gradio\nAuto-loads dataset (Hugging Face if available) and provides interactive visualizations.")
with gr.Row():
src = gr.Dropdown(label="Dataset source", choices=["auto","hf","seaborn"], value="auto")
reload_btn = gr.Button("Reload dataset")
with gr.Row():
sex = gr.Dropdown(label="Sex", choices=["all","male","female"], value="all")
pclass = gr.Dropdown(label="Pclass", choices=["all","1","2","3"], value="all")
embarked = gr.Dropdown(label="Embarked", choices=["all","C","Q","S"], value="all")
age_range = gr.Slider(label="Age range", minimum=0, maximum=100, step=1, value=[0,100])
with gr.Tab("Table & Summary"):
data_out = gr.Dataframe(value=DEFAULT_DF.head(20), label="Filtered rows")
summary_out = gr.Dataframe(value=get_summary_table(DEFAULT_DF).reset_index(), label="Summary (describe)")
with gr.Tab("Visualizations"):
surv_class = gr.Plot(label="Survival by Pclass")
surv_sex = gr.Plot(label="Survival by Sex")
age_fare = gr.Plot(label="Age vs Fare")
corr = gr.Plot(label="Correlation heatmap")
def reload_data(source):
df = load_titanic(source)
return df.head(20), get_summary_table(df).reset_index(), df
def update_all(source, sex_val, pclass_val, embarked_val, age_vals):
# load dataset fresh so that changes in source take effect
df = load_titanic(source)
age_min, age_max = age_vals if isinstance(age_vals, (list, tuple)) else (0,100)
filtered = filter_df(df, sex_val, pclass_val, embarked_val, age_min, age_max)
# prepare outputs
table = filtered.head(200)
summary = get_summary_table(filtered).reset_index()
# plots
fig1 = plot_survival_by_category(filtered, category="pclass" if "pclass" in filtered.columns else "class")
fig2 = plot_survival_by_category(filtered, category="sex")
fig3 = plot_age_vs_fare(filtered)
fig4 = plot_correlation_heatmap(filtered)
return table, summary, fig1, fig2, fig3, fig4
reload_btn.click(fn=reload_data, inputs=[src], outputs=[data_out, summary_out, gr.State()])
# main trigger: update outputs when controls change
src.change(fn=update_all, inputs=[src, sex, pclass, embarked, age_range], outputs=[data_out, summary_out, surv_class, surv_sex, age_fare, corr])
sex.change(fn=update_all, inputs=[src, sex, pclass, embarked, age_range], outputs=[data_out, summary_out, surv_class, surv_sex, age_fare, corr])
pclass.change(fn=update_all, inputs=[src, sex, pclass, embarked, age_range], outputs=[data_out, summary_out, surv_class, surv_sex, age_fare, corr])
embarked.change(fn=update_all, inputs=[src, sex, pclass, embarked, age_range], outputs=[data_out, summary_out, surv_class, surv_sex, age_fare, corr])
age_range.change(fn=update_all, inputs=[src, sex, pclass, embarked, age_range], outputs=[data_out, summary_out, surv_class, surv_sex, age_fare, corr])
return demo
def main():
demo = build_interface()
demo.launch()
if __name__ == "__main__":
main()