nik09 / app.py
nikwagh's picture
Update app.py
7fbbe3a verified
Raw History Blame Contribute Delete
3.54 kB
"""
Customer Churn Explorer - Gradio App
Loads churn.csv from GitHub 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
# --- GitHub Raw CSV URL ---
CSV_URL = "https://raw.githubusercontent.com/albayraktaroglu/Datasets/master/churn.csv"
# --- Load CSV ---
def load_csv():
"""Load churn.csv from GitHub."""
try:
response = requests.get(CSV_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_churn_distribution(df):
"""Plot churn vs non-churn counts."""
fig, ax = plt.subplots(figsize=(4, 3))
if "Churn" not in df.columns:
ax.text(0.5, 0.5, "No 'Churn' column found", ha="center")
return fig
df["Churn"].value_counts().plot(kind="bar", ax=ax, color=["skyblue", "salmon"])
ax.set_title("Churn vs Non-Churn Count")
ax.set_ylabel("Count")
plt.tight_layout()
return fig
def plot_corr(df):
"""Plot numeric correlation heatmap."""
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", cmap="coolwarm", ax=ax)
ax.set_title("Numeric Correlation Heatmap")
plt.tight_layout()
return fig
def plot_categorical(df):
"""Plot first categorical column distribution."""
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 '{col}' Values")
plt.tight_layout()
return fig
# --- Build Gradio App ---
def build_app():
df_default = load_csv()
with gr.Blocks(title="Customer Churn Explorer") as demo:
gr.Markdown(
"""
# 📊 Customer Churn Explorer
Explore customer churn data interactively.
Loaded automatically from GitHub.
**Visuals included:**
- Churn vs Non-Churn count
- Numeric correlation heatmap
- Categorical value distribution
- Summary statistics
"""
)
with gr.Tab("🧾 Data & Summary"):
table = gr.Dataframe(df_default.head(20), label="Data Preview")
summary = gr.Dataframe(df_default.describe(include="all").reset_index(), label="Summary Statistics")
with gr.Tab("📈 Visualizations"):
fig1 = gr.Plot(label="Churn Distribution")
fig2 = gr.Plot(label="Correlation Heatmap")
fig3 = gr.Plot(label="Categorical Distribution")
def update():
df = load_csv()
return (
df.head(50),
df.describe(include="all").reset_index(),
plot_churn_distribution(df),
plot_corr(df),
plot_categorical(df),
)
refresh_btn = gr.Button("🔄 Refresh Data & Visuals")
refresh_btn.click(fn=update, inputs=[], 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)