{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cell-00",
   "metadata": {},
   "source": [
    "# Popularity and audio in ListenBrainz listening — a practical research notebook\n",
    "\n",
    "This notebook uses the **Persistfolio Music Research Dataset** (release music-research-dataset-2026-11-r1). It was executed on the 10,000-recording (medium) edition, the edition listed on Kaggle, and runs unchanged on the free 1,000 and 1 million editions from https://persistfolio.com/datasets. It finds the data next to the notebook (`../data/`) or under `/kaggle/input/`.\n",
    "\n",
    "**Read this first.**\n",
    "- **What the counts are:** listening counts are *attributable observations from the public ListenBrainz CC0 dumps* for October 2026 and ISO week 2026-W47, received by 2026-11-29.\n",
    "- **What they are not:** worldwide streaming figures, complete platform activity, or the numbers on listenbrainz.org charts. For top recordings the public-dump counts are well below those charts; see `docs/QUALITY_REPORT.md`.\n",
    "- **Audio descriptors:** these are AcousticBrainz (Essentia) analyses up to 2022. Their danceability is not Spotify's.\n",
    "- **Modelling:** anything modelled here is *retrospective estimation* of one community's observed listening, not hit prediction.\n",
    "- **Licence:** Persistfolio's documentation, code, notebook and compilation are CC BY 4.0; the underlying ListenBrainz, MusicBrainz and AcousticBrainz data stay CC0 1.0 (see `license/`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "cell-01",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10,000 recordings; columns: 37\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>popularity_rank</th>\n",
       "      <th>title</th>\n",
       "      <th>artist_credit_name</th>\n",
       "      <th>oct_listen_count</th>\n",
       "      <th>oct_listener_count</th>\n",
       "      <th>first_release_year</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>In the End</td>\n",
       "      <td>Linkin Park</td>\n",
       "      <td>5451</td>\n",
       "      <td>2511</td>\n",
       "      <td>2000.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>Numb</td>\n",
       "      <td>Linkin Park</td>\n",
       "      <td>5363</td>\n",
       "      <td>2496</td>\n",
       "      <td>2003.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>Creep</td>\n",
       "      <td>Radiohead</td>\n",
       "      <td>5666</td>\n",
       "      <td>2371</td>\n",
       "      <td>1992.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   popularity_rank       title artist_credit_name  oct_listen_count  \\\n",
       "0                1  In the End        Linkin Park              5451   \n",
       "1                2        Numb        Linkin Park              5363   \n",
       "2                3       Creep          Radiohead              5666   \n",
       "\n",
       "   oct_listener_count  first_release_year  \n",
       "0                2511              2000.0  \n",
       "1                2496              2003.0  \n",
       "2                2371              1992.0  "
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np, pandas as pd, matplotlib\n",
    "matplotlib.use(\"Agg\")\n",
    "import matplotlib.pyplot as plt\n",
    "plt.rcParams.update({\"figure.dpi\": 90, \"figure.figsize\": (7, 4), \"svg.hashsalt\": \"persistfolio\"})\n",
    "from pathlib import Path\n",
    "candidates = [Path(\"../data/music_recordings_flat.csv\"), Path(\"data/music_recordings_flat.csv\"),\n",
    "              *sorted(Path(\"/kaggle/input\").glob(\"**/music_recordings_flat.csv\"))]\n",
    "FLAT = next(p for p in candidates if p.exists())\n",
    "flat = pd.read_csv(FLAT, keep_default_na=False, na_values=[\"\"])\n",
    "print(f\"{len(flat):,} recordings; columns: {len(flat.columns)}\")\n",
    "flat.head(3)[[\"popularity_rank\", \"title\", \"artist_credit_name\", \"oct_listen_count\", \"oct_listener_count\", \"first_release_year\"]]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-02",
   "metadata": {},
   "source": [
    "## 1. How concentrated is listening?\n",
    "Listens per recording follow a heavy-tailed rank–frequency curve. We also compare listens with distinct listeners: a high listens-per-listener ratio flags repeat listening, such as fan \"streaming\" campaigns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cell-03",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Top 1% of these recordings hold 49.1% of their October listens\n",
      "Listens per listener, quantiles: {0.5: 1.98, 0.9: 3.1, 0.99: 20.25}\n"
     ]
    }
   ],
   "source": [
    "o = flat.dropna(subset=[\"oct_listen_count\"]).copy()\n",
    "o[\"listens_per_listener\"] = o.oct_listen_count / o.oct_listener_count\n",
    "s = np.sort(o.oct_listen_count.values)[::-1]\n",
    "top1 = s[: max(1, len(s) // 100)].sum() / s.sum()\n",
    "print(f\"Top 1% of these recordings hold {top1:.1%} of their October listens\")\n",
    "print(\"Listens per listener, quantiles:\", o.listens_per_listener.quantile([.5, .9, .99]).round(2).to_dict())\n",
    "fig, ax = plt.subplots(1, 2, figsize=(10, 4))\n",
    "ax[0].loglog(np.arange(1, len(s) + 1), s); ax[0].set_xlabel(\"rank\"); ax[0].set_ylabel(\"October listens\"); ax[0].set_title(\"Rank-frequency\")\n",
    "ax[1].scatter(o.oct_listener_count, o.oct_listen_count, s=3, alpha=.3); ax[1].set_xscale(\"log\"); ax[1].set_yscale(\"log\")\n",
    "ax[1].set_xlabel(\"listeners\"); ax[1].set_ylabel(\"listens\"); ax[1].set_title(\"Listens vs listeners\")\n",
    "plt.tight_layout(); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-04",
   "metadata": {},
   "source": [
    "## 2. October versus one November week\n",
    "These are two separate observation periods; their listener counts must never be added. How stable is popularity between them?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "cell-05",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10,000 of 10,000 recordings were observed in both periods; Spearman rho of listener counts = 0.885\n",
      "0 recordings had no attributable W47 listen (left empty, not zero)\n"
     ]
    }
   ],
   "source": [
    "both = flat.dropna(subset=[\"oct_listener_count\", \"w47_listener_count\"])\n",
    "rho = both.oct_listener_count.rank().corr(both.w47_listener_count.rank())\n",
    "print(f\"{len(both):,} of {len(flat):,} recordings were observed in both periods; Spearman rho of listener counts = {rho:.3f}\")\n",
    "print(f\"{flat.w47_listen_count.isna().sum():,} recordings had no attributable W47 listen (left empty, not zero)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-06",
   "metadata": {},
   "source": [
    "## 3. Audio descriptors: coverage first\n",
    "AcousticBrainz stopped collecting in 2022, so coverage collapses for recent releases. Any audio analysis must report this denominator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cell-07",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>recordings</th>\n",
       "      <th>with_audio</th>\n",
       "      <th>share_with_audio</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>decade</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1950</th>\n",
       "      <td>11</td>\n",
       "      <td>11</td>\n",
       "      <td>1.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1960</th>\n",
       "      <td>209</td>\n",
       "      <td>207</td>\n",
       "      <td>0.990</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1970</th>\n",
       "      <td>533</td>\n",
       "      <td>531</td>\n",
       "      <td>0.996</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1980</th>\n",
       "      <td>668</td>\n",
       "      <td>656</td>\n",
       "      <td>0.982</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1990</th>\n",
       "      <td>1169</td>\n",
       "      <td>1130</td>\n",
       "      <td>0.967</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2000</th>\n",
       "      <td>1743</td>\n",
       "      <td>1673</td>\n",
       "      <td>0.960</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010</th>\n",
       "      <td>2431</td>\n",
       "      <td>2248</td>\n",
       "      <td>0.925</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020</th>\n",
       "      <td>3217</td>\n",
       "      <td>567</td>\n",
       "      <td>0.176</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        recordings  with_audio  share_with_audio\n",
       "decade                                          \n",
       "1950            11          11             1.000\n",
       "1960           209         207             0.990\n",
       "1970           533         531             0.996\n",
       "1980           668         656             0.982\n",
       "1990          1169        1130             0.967\n",
       "2000          1743        1673             0.960\n",
       "2010          2431        2248             0.925\n",
       "2020          3217         567             0.176"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "flat[\"decade\"] = (flat.first_release_year // 10 * 10).astype(\"Int64\")\n",
    "cov = flat.groupby(\"decade\").agg(recordings=(\"recording_mbid\", \"size\"), with_audio=(\"ab_features_available\", lambda x: (x == True).sum()))\n",
    "cov[\"share_with_audio\"] = (cov.with_audio / cov.recordings).round(3)\n",
    "cov"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "cell-08",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{np.int64(1950): 1.069, np.int64(1960): 1.084, np.int64(1970): 1.152, np.int64(1980): 1.211, np.int64(1990): 1.139, np.int64(2000): 1.116, np.int64(2010): 1.126, np.int64(2020): 1.135}\n"
     ]
    }
   ],
   "source": [
    "a = flat[flat.ab_features_available == True]\n",
    "fig, ax = plt.subplots(1, 2, figsize=(10, 4))\n",
    "a.ab_bpm.clip(50, 220).plot.hist(bins=60, ax=ax[0]); ax[0].set_xlabel(\"BPM (Essentia)\"); ax[0].set_title(\"Tempo\")\n",
    "(a.ab_key + \" \" + a.ab_scale).value_counts().head(12).plot.bar(ax=ax[1]); ax[1].set_title(\"Most frequent keys\")\n",
    "plt.tight_layout(); plt.show()\n",
    "print(a.groupby(\"decade\").ab_danceability_essentia.median().round(3).to_dict())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-09",
   "metadata": {},
   "source": [
    "## 4. A truthful baseline: do audio descriptors explain October listens?\n",
    "Target: `log1p(oct_listen_count)`. Rows: recordings with audio descriptors. Split: five folds grouped by first credited artist, so no artist appears in both train and test. Model: ridge regression (alpha 1), compared with predicting the training median. `release_count` is shown separately because it reflects catalogue attention observed *after* the listening period (leakage risk)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "cell-10",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "rows with audio: 7,026 of 10,000 (70.3% coverage)\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>MAE log1p</th>\n",
       "      <th>vs median</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>train median</th>\n",
       "      <td>0.489334</td>\n",
       "      <td>+0.0%</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>audio</th>\n",
       "      <td>0.505073</td>\n",
       "      <td>+3.2%</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>audio + length + year</th>\n",
       "      <td>0.503406</td>\n",
       "      <td>+2.9%</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>+ release_count (leakage risk)</th>\n",
       "      <td>0.488406</td>\n",
       "      <td>-0.2%</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                MAE log1p vs median\n",
       "train median                     0.489334     +0.0%\n",
       "audio                            0.505073     +3.2%\n",
       "audio + length + year            0.503406     +2.9%\n",
       "+ release_count (leakage risk)   0.488406     -0.2%"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import hashlib\n",
    "feats_audio = [\"ab_bpm\", \"ab_average_loudness\", \"ab_dynamic_complexity_db\", \"ab_danceability_essentia\", \"ab_onset_rate_per_s\",\n",
    "               \"ab_tuning_frequency_hz\", \"ab_mfcc_mean_00\"]\n",
    "d = flat[(flat.ab_features_available == True) & flat.oct_listen_count.notna()].copy()\n",
    "d[\"y\"] = np.log1p(d.oct_listen_count)\n",
    "d[\"fold\"] = [int(hashlib.sha256(str(x).encode()).hexdigest(), 16) % 5 for x in d.first_artist_mbid.fillna(d.recording_mbid)]\n",
    "def ridge(Xtr, ytr, Xte, alpha=1.0):\n",
    "    med = np.nanmedian(Xtr, 0); Xtr = np.where(np.isnan(Xtr), med, Xtr); Xte = np.where(np.isnan(Xte), med, Xte)\n",
    "    mu, sd = Xtr.mean(0), Xtr.std(0); sd[sd == 0] = 1\n",
    "    Z, Zt = (Xtr - mu) / sd, (Xte - mu) / sd\n",
    "    w = np.linalg.solve(Z.T @ Z + alpha * np.eye(Z.shape[1]), Z.T @ (ytr - ytr.mean()))\n",
    "    return Zt @ w + ytr.mean()\n",
    "sets = {\"audio\": feats_audio, \"audio + length + year\": feats_audio + [\"length_ms\", \"first_release_year\"],\n",
    "        \"+ release_count (leakage risk)\": feats_audio + [\"length_ms\", \"first_release_year\", \"release_count\"]}\n",
    "res = {\"train median\": []} | {k: [] for k in sets}\n",
    "pred = {k: np.zeros(len(d)) for k in res}\n",
    "for f in range(5):\n",
    "    tr, te = d.fold != f, d.fold == f\n",
    "    pred[\"train median\"][te.values] = d.y[tr].median()\n",
    "    for k, cols in sets.items():\n",
    "        X = d[cols].astype(float).values\n",
    "        pred[k][te.values] = ridge(X[tr.values], d.y[tr].values, X[te.values])\n",
    "out = pd.DataFrame({k: [np.abs(p - d.y.values).mean()] for k, p in pred.items()}, index=[\"MAE log1p\"]).T\n",
    "out[\"vs median\"] = (out[\"MAE log1p\"] / out.loc[\"train median\", \"MAE log1p\"] - 1).map(\"{:+.1%}\".format)\n",
    "print(f\"rows with audio: {len(d):,} of {len(flat):,} ({len(d)/len(flat):.1%} coverage)\")\n",
    "out"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-11",
   "metadata": {},
   "source": [
    "**Reading the baseline.** In the 1,000-recording pilot, audio descriptors improved on the median by about 1% once artists were held out. Check the table above for this edition. Only the leakage-risk variable helps materially, and it encodes popularity itself.\n",
    "\n",
    "These files are therefore better suited to descriptive and historical questions than to popularity prediction:\n",
    "- tempo and key by era;\n",
    "- songwriting credit concentration;\n",
    "- band-membership networks;\n",
    "- concentration and long-tail measures with explicit denominators.\n",
    "\n",
    "Genuine forecasting would need dated feature and label windows that this snapshot does not provide."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-12",
   "metadata": {},
   "source": [
    "## 5. Release history context\n",
    "When were today's most-heard recordings first released? (MusicBrainz release-event dates, not composition dates.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "cell-13",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "median first release year: 2013; share released 2020 or later: 32.2%\n"
     ]
    }
   ],
   "source": [
    "y = flat.dropna(subset=[\"first_release_year\"])\n",
    "y = y[y.first_release_year >= 1950]\n",
    "fig, ax = plt.subplots()\n",
    "ax.hist(y.first_release_year, bins=range(1950, 2028)); ax.set_xlabel(\"first release year\"); ax.set_ylabel(\"recordings\")\n",
    "ax.set_title(\"First documented release of recordings heard in October 2026\")\n",
    "plt.tight_layout(); plt.show()\n",
    "print(f\"median first release year: {int(y.first_release_year.median())}; share released 2020 or later: {(y.first_release_year >= 2020).mean():.1%}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
