Update app.py
Browse files12344 unmodified lines9101112131415161718192021222 unmodified lines2526272829303132333 unmodified lines3738394041424332 unmodified lines767778798081828313 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712850 unmodified lines1791801811821831841851861871881891901911921931941951961971 unmodified line1992002012022032042052062072082092102112122132142152162172184 unmodified lines2232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772781 unmodified line2802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483 unmodified lines352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444# app_simple_plus.py — ASAP Explorer (no table, log-scale map, English-filtered word cloud, top-15 composers)import reimport pandas as pdimport numpy as np4 unmodified linesimport gradio as grfrom datasets import load_datasetimport osCOMPOSITION_PATH = "ASAPcomposition.csv"PEOPLE_PATH = "ASAPdata.csv"PLOT_TEMPLATE = "plotly_white"HF_TOKEN = os.environ.get("HF_TOKEN")# ===== Word cloud English filter =====MIN_ASCII_RATIO = 0.7 # keep titles whose ASCII-char ratio >= thisdef _ascii_ratio(s: str) -> float:if not s:2 unmodified linesascii_count = sum(1 for ch in s if ord(ch) < 128)return ascii_count / total if total else 0.0# =========================# Robust Year Parsing# =========================def _norm_year_text(s: str) -> str:s = s.strip()s = s.replace("–", "-").replace("—", "-").replace(" to ", "-")3 unmodified linessl = re.sub(r"\s+", " ", sl).strip()return sldef _parse_year_robust(y):if pd.isna(y):return (np.nan, np.nan)s = _norm_year_text(str(y))32 unmodified linespassreturn (np.nan, np.nan)def _parse_duration(d):if pd.isna(d): return np.nans = str(d).strip().lower()if ":" in s:parts = [p.strip() for p in s.split(":")]13 unmodified linesreturn np.nan# =========================# Loaders (compositions)# =========================def load_compositions():ds = load_dataset("csv", data_files="hf://datasets/zliang/ASAP/ASAPcomposition.csv", token=HF_TOKEN)df = ds["train"].to_pandas()df = df.rename(columns={"Name": "Composer","Composition Title": "Title","Duration": "Duration","Year": "Year","Level": "Level"})starts, ends = [], []for raw in df.get("Year", pd.Series([np.nan] * len(df))):y0, y1 = _parse_year_robust(raw)starts.append(y0); ends.append(y1)df["YearStart"] = startsdf["YearEnd"] = endsdf["YearParsed"] = df["YearStart"]df["DurationMin"] = df.get("Duration", pd.Series([np.nan]*len(df))).map(_parse_duration)df["LevelStd"] = df.get("Level", pd.Series(["Unknown"]*len(df))).fillna("Unknown")return df# =========================# Demonyms & country normalization (people)# =========================_COUNTRY_ALIASES = {"czech republic": "Czechia","viet nam": "Vietnam",50 unmodified lines"australian": "Australia", "new zealander": "New Zealand", "fijian": "Fiji", "samoan": "Samoa", "tongan": "Tonga",}def _col(df, *candidates):cols = {c.lower().strip(): c for c in df.columns}for cand in candidates:k = cand.lower().strip()if k in cols: return cols[k]return Nonedef _basic_clean_nat(s: str) -> str:s = str(s)s = s.replace("(", " ").replace(")", " ")s = re.sub(r"[.\u200b]", " ", s)s = re.sub(r"\s+", " ", s)return s.strip()def _normalize_country_or_demonym(token: str):if token is None or (isinstance(token, float) and np.isnan(token)):1 unmodified linet = _basic_clean_nat(token).lower()t = re.sub(r"\b(citizen|national|born|of|the|composer)\b", " ", t)t = re.sub(r"\s+", " ", t).strip()if t in _DEMONYM_TO_COUNTRY: return _DEMONYM_TO_COUNTRY[t]if t in _COUNTRY_ALIASES: return _COUNTRY_ALIASES[t]short = {"usa": "United States", "u.s.a": "United States", "u.s": "United States", "us": "United States","uk": "United Kingdom", "england": "United Kingdom", "scotland": "United Kingdom", "wales": "United Kingdom","korea": "South Korea", "russia": "Russia",}if t in short: return short[t]if re.search(r"[a-z]", t): # likely a country alreadyreturn t.title()return np.nandef _split_and_normalize_nationalities(value):if pd.isna(value): return []s = _basic_clean_nat(value)s = re.sub(r"\s*(/|;|&|\band\b|,)\s*", ",", s, flags=re.I)parts = [p for p in (x.strip() for x in s.split(",")) if p]4 unmodified linesout.append(norm)return outdef load_people():ds = load_dataset("csv", data_files="hf://datasets/zliang/ASAP/ASAPdata.csv", token=HF_TOKEN)df = ds["train"].to_pandas()col_gender = _col(df, "Gender", "gender")col_nat = _col(df, "Nationality", "Country", "nationality", "country")col_eth = _col(df, "Ethnicity", "ethnicity")col_era = _col(df, "Music Era", "Era", "Period", "music era", "era", "period")if col_gender: df = df.rename(columns={col_gender: "Gender"})else: df["Gender"] = np.nanif col_nat: df = df.rename(columns={col_nat: "Nationality"})else: df["Nationality"] = np.nanif col_eth: df = df.rename(columns={col_eth: "Ethnicity"})else: df["Ethnicity"] = np.nanif col_era: df = df.rename(columns={col_era: "Music Era"})else: df["Music Era"] = np.nandf["NationalityList"] = df["Nationality"].apply(_split_and_normalize_nationalities)df_exp = df.explode("NationalityList").rename(columns={"NationalityList": "NationalityNorm"})df_exp["NationalityNorm"] = df_exp["NationalityNorm"].replace({"": np.nan})return df, df_exp# =========================# Visuals — Compositions# =========================def area_timeline(df):d = df.dropna(subset=["YearParsed"])if d.empty: return go.Figure()counts = d.groupby(["YearParsed", "LevelStd"])["Title"].count().reset_index(name="Count")counts = counts.sort_values("YearParsed")counts["Smoothed"] = counts.groupby("LevelStd")["Count"].transform(lambda s: s.rolling(3, min_periods=1).mean())fig = px.area(counts, x="YearParsed", y="Smoothed", color="LevelStd",title="Compositions per Year by Level", template=PLOT_TEMPLATE)fig.update_layout(margin=dict(l=10, r=10, t=50, b=10), legend_title="Level")fig.update_xaxes(title="Year"); fig.update_yaxes(title="Smoothed count")return figdef bar_top_composers(df, top_n=15):if df.empty:return go.Figure()# group + sortd = (df.groupby("Composer")["Title"].count().sort_values(ascending=False).head(top_n).reset_index().rename(columns={"Title": "Count"}))# order composers by descending countcomposer_order = d["Composer"].tolist()fig = px.bar(d,1 unmodified liney="Composer",orientation="h",title=f"Top {top_n} Composers by Number of Compositions",template=PLOT_TEMPLATE)# force y-axis order: most at top → least at bottomfig.update_layout(yaxis=dict(categoryorder="array", categoryarray=composer_order[::-1]),margin=dict(l=10, r=10, t=50, b=10))return figdef treemap_composer_level(df):if df.empty: return go.Figure()d = df.groupby(["Composer", "LevelStd"])["Title"].count().reset_index(name="Count")fig = px.treemap(d, path=["Composer", "LevelStd"], values="Count",title="Catalog Structure: Composer → Level", template=PLOT_TEMPLATE)fig.update_layout(margin=dict(l=10, r=10, t=50, b=10))return figdef make_wordcloud(df):titles = df["Title"].dropna().astype(str)# English filter: keep titles with sufficient ASCII ratiotitles = [t for t in titles if _ascii_ratio(t) >= MIN_ASCII_RATIO]if not titles:return Nonetext = " ".join(titles)stopwords = set(STOPWORDS)stopwords.update({"Piano", "II", "IV","V","III","Piece","Pieces","Op","VII","IX","VIII"}) # 👈 add more as neededwc = WordCloud(width=1200, height=500, background_color="white",stopwords=stopwords, collocations=True)return wc.generate(text).to_image()# =========================# Visuals — People (pies + LOG map)# =========================def pie(df_people_exp_or_raw, column, title, max_slices=12):if column not in df_people_exp_or_raw.columns:return go.Figure()s = df_people_exp_or_raw[column].dropna()if s.empty: return go.Figure()counts = s.value_counts(dropna=False)if len(counts) > max_slices:head = counts.iloc[:max_slices-1]other = pd.Series({"Other": counts.iloc[max_slices-1:].sum()})counts = pd.concat([head, other])d = counts.reset_index()d.columns = [column, "Count"]fig = px.pie(d, names=column, values="Count", title=title, template=PLOT_TEMPLATE, hole=0.35)fig.update_traces(textposition="inside", textinfo="percent+label")fig.update_layout(margin=dict(l=10, r=10, t=50, b=10))return figdef world_map_nationality(df_people_exp):# Exploded + normalized nationalities expected heres = df_people_exp["NationalityNorm"].dropna()if s.empty:return go.Figure()counts = s.value_counts().reset_index()counts.columns = ["country", "count"]# ---- log transform in the data (avoid coloraxis.type) ----counts["count_log10"] = np.log10(counts["count"] + 1.0)fig = px.choropleth(3 unmodified linescolor="count_log10",color_continuous_scale="Blues",title="Global Distribution by Nationality (log scale)",template=PLOT_TEMPLATE,hover_data={"count": True, "count_log10": False, "country": False},)# Colorbar: show a few human-friendly ticks with labels in raw countsif not counts.empty:vmax = int(counts["count"].max())# choose nice ticks (1, 3, 10, 30, 100, ...)raw_ticks = []step = 1base = [1, 3]while step <= vmax:for b in base:val = b * stepif val <= vmax:raw_ticks.append(val)step *= 10raw_ticks = sorted(set([1] + raw_ticks + [vmax]))tickvals = np.log10(np.array(raw_ticks, dtype=float) + 1.0)ticktext = [str(v) for v in raw_ticks]fig.update_layout(margin=dict(l=10, r=10, t=50, b=10),coloraxis_colorbar=dict(title="Count", tickvals=tickvals, ticktext=ticktext),)else:fig.update_layout(margin=dict(l=10, r=10, t=50, b=10), coloraxis_colorbar_title="Count")return fig# =========================# Pipeline# =========================def compute_all():comp = load_compositions()ppl_raw, ppl_exp = load_people()return (# compositionsarea_timeline(comp),bar_top_composers(comp),treemap_composer_level(comp),make_wordcloud(comp),# people pies + log mappie(ppl_raw, "Gender", "Gender"),pie(ppl_exp, "NationalityNorm", "Nationality"),pie(ppl_raw, "Ethnicity", "Ethnicity"),pie(ppl_raw, "Music Era", "Music Era"),world_map_nationality(ppl_exp))# =========================# UI (simple, no uploads, no filters, no table)# =========================theme = gr.themes.Soft(primary_hue="blue", neutral_hue="slate")with gr.Blocks(title="A Seat At The Piano", theme=theme) as demo:gr.Markdown(f"## 🎼 ASAP Explorer\n"f"A Seat at the Piano was founded in the summer of 2020 in the midst of social and racial reckoning around the world. We are a team of classically trained pianists with varying backgrounds and experiences, who strive to raise the voices of those who are less heard and to inspire more thoughtful, inclusive programming within the performing and pedagogical spheres.\n")with gr.Tabs():with gr.Tab("Composer Demographics"):with gr.Row():pie_gender = gr.Plot()pie_nat = gr.Plot()with gr.Row():pie_eth = gr.Plot()pie_era = gr.Plot()world_map = gr.Plot()with gr.Tab("Compositions Overview"):timeline_plot = gr.Plot()top_plot = gr.Plot()with gr.Tab("Compositions Catogories"):tree_plot = gr.Plot()wc_img = gr.Image(type="pil")demo.load(compute_all,inputs=None,outputs=[timeline_plot, top_plot, tree_plot, wc_img,pie_gender, pie_nat, pie_eth, pie_era, world_map],)if __name__ == "__main__":demo.launch()1234 unmodified lines891011121314151617181920212223242526272829303132333435363738394041422 unmodified lines45464748495051523 unmodified lines565758596061626332 unmodified lines9697989910010110210310410513 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314450 unmodified lines1951961971981992001 unmodified line2022032042052062072082092102112122132142152162172182192202212222232242252264 unmodified lines2312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663671 unmodified line3693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264273 unmodified lines431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560import reimport pandas as pdimport numpy as np4 unmodified linesimport gradio as grfrom datasets import load_datasetimport osfrom typing import Tuple, Optional# =========================# Config# =========================COMPOSITION_PATH = "ASAPcomposition.csv"PEOPLE_PATH = "ASAPdata.csv"PLOT_TEMPLATE = "plotly_white"HF_TOKEN = os.environ.get("HF_TOKEN")MIN_ASCII_RATIO = 0.7 # wordcloud English-ish filter# Small, mobile-friendly visual defaults_MOBILE_LAYOUT_KW = dict(margin=dict(l=8, r=8, t=38, b=8),legend=dict(orientation="h", yanchor="bottom", y=-0.25, xanchor="left", x=0),transition_duration=0,)# =========================# In-memory caches (avoid recomputation + network hits)# =========================_COMPOSITIONS_DF: Optional[pd.DataFrame] = None_PEOPLE_RAW_DF: Optional[pd.DataFrame] = None_PEOPLE_EXP_DF: Optional[pd.DataFrame] = None_WC_IMG = None# =========================# Utilities# =========================def _ascii_ratio(s: str) -> float:if not s:2 unmodified linesascii_count = sum(1 for ch in s if ord(ch) < 128)return ascii_count / total if total else 0.0# ---- Robust Year Parsing ----def _norm_year_text(s: str) -> str:s = s.strip()s = s.replace("–", "-").replace("—", "-").replace(" to ", "-")3 unmodified linessl = re.sub(r"\s+", " ", sl).strip()return sldef _parse_year_robust(y) -> Tuple[float, float]:if pd.isna(y):return (np.nan, np.nan)s = _norm_year_text(str(y))32 unmodified linespassreturn (np.nan, np.nan)def _parse_duration(d):if pd.isna(d):return np.nans = str(d).strip().lower()if ":" in s:parts = [p.strip() for p in s.split(":")]13 unmodified linesreturn np.nan# =========================# Loaders (with caching)# =========================def _col(df, *candidates):cols = {c.lower().strip(): c for c in df.columns}for cand in candidates:k = cand.lower().strip()if k in cols:return cols[k]return Nonedef _basic_clean_nat(s: str) -> str:s = str(s)s = s.replace("(", " ").replace(")", " ")s = re.sub(r"[.\u200b]", " ", s)s = re.sub(r"\s+", " ", s)return s.strip()_COUNTRY_ALIASES = {"czech republic": "Czechia","viet nam": "Vietnam",50 unmodified lines"australian": "Australia", "new zealander": "New Zealand", "fijian": "Fiji", "samoan": "Samoa", "tongan": "Tonga",}def _normalize_country_or_demonym(token: str):if token is None or (isinstance(token, float) and np.isnan(token)):1 unmodified linet = _basic_clean_nat(token).lower()t = re.sub(r"\b(citizen|national|born|of|the|composer)\b", " ", t)t = re.sub(r"\s+", " ", t).strip()if t in _DEMONYM_TO_COUNTRY:return _DEMONYM_TO_COUNTRY[t]if t in _COUNTRY_ALIASES:return _COUNTRY_ALIASES[t]short = {"usa": "United States", "u.s.a": "United States", "u.s": "United States", "us": "United States","uk": "United Kingdom", "england": "United Kingdom", "scotland": "United Kingdom", "wales": "United Kingdom","korea": "South Korea", "russia": "Russia",}if t in short:return short[t]if re.search(r"[a-z]", t):return t.title()return np.nandef _split_and_normalize_nationalities(value):if pd.isna(value):return []s = _basic_clean_nat(value)s = re.sub(r"\s*(/|;|&|\band\b|,)\s*", ",", s, flags=re.I)parts = [p for p in (x.strip() for x in s.split(",")) if p]4 unmodified linesout.append(norm)return out# ---- Data loaders (cached in-module) ----def load_compositions() -> pd.DataFrame:global _COMPOSITIONS_DFif _COMPOSITIONS_DF is not None:return _COMPOSITIONS_DFds = load_dataset("csv",data_files="hf://datasets/zliang/ASAP/ASAPcomposition.csv",token=HF_TOKEN,)df = ds["train"].to_pandas()df = df.rename(columns={"Name": "Composer","Composition Title": "Title","Duration": "Duration","Year": "Year","Level": "Level",})# Vectorized-ish year parsing (fast enough and clearer)parsed = df.get("Year", pd.Series([np.nan] * len(df))).map(_parse_year_robust)df["YearStart"] = [p[0] for p in parsed]df["YearEnd"] = [p[1] for p in parsed]df["YearParsed"] = df["YearStart"]df["DurationMin"] = df.get("Duration", pd.Series([np.nan] * len(df))).map(_parse_duration)df["LevelStd"] = df.get("Level", pd.Series(["Unknown"] * len(df))).fillna("Unknown")_COMPOSITIONS_DF = dfreturn dfdef load_people():global _PEOPLE_RAW_DF, _PEOPLE_EXP_DFif _PEOPLE_RAW_DF is not None and _PEOPLE_EXP_DF is not None:return _PEOPLE_RAW_DF, _PEOPLE_EXP_DFds = load_dataset("csv",data_files="hf://datasets/zliang/ASAP/ASAPdata.csv",token=HF_TOKEN,)df = ds["train"].to_pandas()# Robust rename with fallbackscol_gender = _col(df, "Gender", "gender")col_nat = _col(df, "Nationality", "Country", "nationality", "country")col_eth = _col(df, "Ethnicity", "ethnicity")col_era = _col(df, "Music Era", "Era", "Period", "music era", "era", "period")if col_gender:df = df.rename(columns={col_gender: "Gender"})else:df["Gender"] = np.nanif col_nat:df = df.rename(columns={col_nat: "Nationality"})else:df["Nationality"] = np.nanif col_eth:df = df.rename(columns={col_eth: "Ethnicity"})else:df["Ethnicity"] = np.nanif col_era:df = df.rename(columns={col_era: "Music Era"})else:df["Music Era"] = np.nandf["NationalityList"] = df["Nationality"].apply(_split_and_normalize_nationalities)df_exp = df.explode("NationalityList").rename(columns={"NationalityList": "NationalityNorm"})df_exp["NationalityNorm"] = df_exp["NationalityNorm"].replace({"": np.nan})_PEOPLE_RAW_DF, _PEOPLE_EXP_DF = df, df_expreturn df, df_exp# =========================# Visuals (tuned for speed + mobile)# =========================def _apply_mobile_layout(fig: go.Figure) -> go.Figure:fig.update_layout(**_MOBILE_LAYOUT_KW, template=PLOT_TEMPLATE)fig.update_xaxes(title_standoff=4)fig.update_yaxes(title_standoff=4)return figdef area_timeline(df):d = df.dropna(subset=["YearParsed"])if d.empty:return go.Figure()counts = (d.groupby(["YearParsed", "LevelStd"], observed=True)["Title"].count().rename("Count").reset_index().sort_values("YearParsed"))# quick smoothing (window=3)counts["Smoothed"] = (counts.groupby("LevelStd", observed=True)["Count"].transform(lambda s: s.rolling(3, min_periods=1).mean()))fig = px.area(counts,x="YearParsed",y="Smoothed",color="LevelStd",title="Compositions per Year by Level",)fig.update_xaxes(title="Year")fig.update_yaxes(title="Smoothed count")return _apply_mobile_layout(fig)def bar_top_composers(df, top_n=15):if df.empty:return go.Figure()d = (df.groupby("Composer", observed=True)["Title"].count().sort_values(ascending=False).head(top_n).reset_index())d = d.rename(columns={"Title": "Count"})order = d["Composer"].tolist()fig = px.bar(d,1 unmodified liney="Composer",orientation="h",title=f"Top {top_n} Composers by Number of Compositions",)fig.update_layout(yaxis=dict(categoryorder="array", categoryarray=order[::-1]))return _apply_mobile_layout(fig)def treemap_composer_level(df):if df.empty:return go.Figure()d = df.groupby(["Composer", "LevelStd"], observed=True)["Title"].count().reset_index(name="Count")fig = px.treemap(d, path=["Composer", "LevelStd"], values="Count", title="Catalog Structure: Composer → Level")return _apply_mobile_layout(fig)def make_wordcloud(df):global _WC_IMGif _WC_IMG is not None:return _WC_IMGtitles = df["Title"].dropna().astype(str)titles = [t for t in titles if _ascii_ratio(t) >= MIN_ASCII_RATIO]if not titles:return Nonetext = " ".join(titles)stopwords = set(STOPWORDS)stopwords.update({"Piano", "II", "IV", "V", "III", "Piece", "Pieces", "Op", "VII", "IX", "VIII"})wc = WordCloud(width=1200, height=500, background_color="white", stopwords=stopwords, collocations=True)_WC_IMG = wc.generate(text).to_image()return _WC_IMGdef pie_counts(series: pd.Series, title: str, max_slices: int = 12):s = series.dropna()if s.empty:return go.Figure()counts = s.value_counts(dropna=False)if len(counts) > max_slices:head = counts.iloc[: max_slices - 1]other = pd.Series({"Other": counts.iloc[max_slices - 1 :].sum()})counts = pd.concat([head, other])d = counts.reset_index()d.columns = ["label", "Count"]fig = px.pie(d, names="label", values="Count", title=title, hole=0.35)fig.update_traces(textposition="inside", textinfo="percent+label")return _apply_mobile_layout(fig)def world_map_nationality(df_people_exp):s = df_people_exp["NationalityNorm"].dropna()if s.empty:return go.Figure()counts = s.value_counts().reset_index()counts.columns = ["country", "count"]counts["count_log10"] = np.log10(counts["count"] + 1.0)fig = px.choropleth(3 unmodified linescolor="count_log10",color_continuous_scale="Blues",title="Global Distribution by Nationality (log scale)",hover_data={"count": True, "count_log10": False, "country": False},)# Colorbar ticks in raw countsvmax = int(counts["count"].max())raw_ticks = [1]step = 1base = [1, 3]while step <= vmax:for b in base:val = b * stepif val <= vmax:raw_ticks.append(val)step *= 10raw_ticks = sorted(set(raw_ticks + [vmax]))tickvals = np.log10(np.array(raw_ticks, dtype=float) + 1.0)ticktext = [str(v) for v in raw_ticks]fig.update_layout(coloraxis_colorbar=dict(title="Count", tickvals=tickvals, ticktext=ticktext))return _apply_mobile_layout(fig)# =========================# Pipelines (computed per-tab, lazily)# =========================def compute_people_viz():ppl_raw, ppl_exp = load_people()return (pie_counts(ppl_raw["Gender"], "Gender"),pie_counts(ppl_exp["NationalityNorm"], "Nationality"),pie_counts(ppl_raw["Ethnicity"], "Ethnicity"),pie_counts(ppl_raw["Music Era"], "Music Era"),world_map_nationality(ppl_exp),)def compute_compositions_overview():comp = load_compositions()return (area_timeline(comp),bar_top_composers(comp),)def compute_categories_viz():comp = load_compositions()return (treemap_composer_level(comp),make_wordcloud(comp),)# =========================# UI (lazy-load tabs; responsive stacking)# =========================theme = gr.themes.Soft(primary_hue="blue", neutral_hue="slate")with gr.Blocks(title="A Seat At The Piano — ASAP Explorer", theme=theme, css="""/***** Lightweight responsive tweaks *****/.gradio-container {max-width: 1200px}.plotly-graph-div {height: auto !important}@media (max-width: 700px){.gr-row {flex-direction: column !important}}""") as demo:gr.Markdown("## 🎼 ASAP Explorer\n""A Seat at the Piano was founded in the summer of 2020 in the midst of social and racial reckoning around the world.\n""We strive to raise the voices of those who are less heard and to inspire more thoughtful, inclusive programming.")with gr.Tabs() as tabs:with gr.Tab("Composer Demographics") as tab_people:with gr.Row(equal_height=False):pie_gender = gr.Plot(label="Gender")pie_nat = gr.Plot(label="Nationality")with gr.Row(equal_height=False):pie_eth = gr.Plot(label="Ethnicity")pie_era = gr.Plot(label="Music Era")world_map = gr.Plot(label="Global Map (log scale)")with gr.Tab("Compositions Overview") as tab_overview:with gr.Row(equal_height=False):timeline_plot = gr.Plot(label="Timeline")with gr.Row(equal_height=False):top_plot = gr.Plot(label="Top Composers")with gr.Tab("Composition Categories") as tab_cats:with gr.Row(equal_height=False):tree_plot = gr.Plot(label="Composer → Level Treemap")with gr.Row(equal_height=False):wc_img = gr.Image(type="pil", label="Word Cloud")# --- Lazy load on tab select (much faster initial render) ---tab_people.select(fn=compute_people_viz,inputs=None,outputs=[pie_gender, pie_nat, pie_eth, pie_era, world_map],queue=False,)tab_overview.select(fn=compute_compositions_overview,inputs=None,outputs=[timeline_plot, top_plot],queue=False,)tab_cats.select(fn=compute_categories_viz,inputs=None,outputs=[tree_plot, wc_img],queue=False,)# Optional: pre-warm smallest tab to show something immediately (cheap plots)# Comment out if you want totally empty initial viewdemo.load(fn=compute_compositions_overview,inputs=None,outputs=[timeline_plot, top_plot],queue=False,)if __name__ == "__main__":# Gradio queues can add overhead; keep it off for snappier single-user usedemo.launch(quiet=True)
app.py+292-176