{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "pyLKd2-h5OLF" }, "source": [ "# Spotify Audio Features Dataset\n", "\n", "Here we create a simple merged dataset of Spotify Audio Features. For more information, please check this repository on HuggingFace: [Spotify Audio Features](https://huggingface.co/datasets/ozefe/spotify_audio_features)\n", "\n", "- https://annas-archive.org/torrents/spotify\n", "- https://annas-archive.org/blog/backing-up-spotify.html" ] }, { "cell_type": "markdown", "metadata": { "id": "k68juUF3pRs4" }, "source": [ "## Download Packages" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "mA-YpDhhtXJH", "scrolled": true }, "outputs": [], "source": [ "!apt-get install -y aria2 zstd" ] }, { "cell_type": "markdown", "source": [ "## Dependencies" ], "metadata": { "id": "Db-OJyp6RGp1" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "oSeRSe9bQuTH" }, "outputs": [], "source": [ "%pip install duckdb" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "aiAjzX_dtE6H" }, "outputs": [], "source": [ "import sqlite3\n", "import duckdb\n", "\n", "from pathlib import Path" ] }, { "cell_type": "markdown", "source": [ "## Constants" ], "metadata": { "id": "m91lb2EwRKHL" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "MxMwmZgttIBq" }, "outputs": [], "source": [ "SPOTIFY_DATA_DOWNLOAD_MAIN_DIR = Path(\"./spotify\")\n", "SPOTIFY_DATA_DOWNLOAD_TORRENT_DIR = SPOTIFY_DATA_DOWNLOAD_MAIN_DIR / \"annas_archive_spotify_2025_07_metadata\"\n", "\n", "SPOTIFY_TRACK_METADATA_ZST = SPOTIFY_DATA_DOWNLOAD_MAIN_DIR / \"track_metadata.sqlite3.zst\"\n", "SPOTIFY_AUDIO_FEATURES_ZST = SPOTIFY_DATA_DOWNLOAD_MAIN_DIR / \"audio_features.sqlite3.zst\"\n", "\n", "SPOTIFY_AUDIO_FEATURES_SQLITE3 = SPOTIFY_DATA_DOWNLOAD_MAIN_DIR / \"audio_features.sqlite3\"\n", "SPOTIFY_TRACK_METADATA_SQLITE3 = SPOTIFY_DATA_DOWNLOAD_MAIN_DIR / \"track_metadata.sqlite3\"\n", "\n", "SPOTIFY_MERGED_DATA_DIR = SPOTIFY_DATA_DOWNLOAD_MAIN_DIR / \"merged_data\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "a7kTcOastP_r" }, "outputs": [], "source": [ "TORRENT_LINK = \"https://annas-archive.org/dyn/small_file/torrents/other_aa/aa_misc_data/annas_archive_spotify_2025_07_metadata.torrent\"" ] }, { "cell_type": "markdown", "source": [ "## Raw Data" ], "metadata": { "id": "dBRaudpURM6V" } }, { "cell_type": "markdown", "source": [ "### Download" ], "metadata": { "id": "btrgRPCKRQop" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "3X9j6ipj-1MI", "scrolled": true }, "outputs": [], "source": [ "# Download ./annas_archive_spotify_2025_07_metadata/spotify_clean.sqlite3.zst\n", "# and ./annas_archive_spotify_2025_07_metadata/spotify_clean_audio_features.sqlite3.zst\n", "!aria2c --check-integrity=true \\\n", " --seed-time=0 \\\n", " --bt-max-peers=0 \\\n", " --select-file=\"4,5\" \\\n", " --bt-remove-unselected-file=true \\\n", " --follow-torrent=mem \\\n", " --remove-control-file=true \\\n", " --bt-save-metadata=false \\\n", " --rpc-save-upload-metadata=false \\\n", " --dir {SPOTIFY_DATA_DOWNLOAD_MAIN_DIR} \\\n", " {TORRENT_LINK}\n", "\n", "# Move the file up one directory and change its name for better readability\n", "!mv {SPOTIFY_DATA_DOWNLOAD_TORRENT_DIR}/spotify_clean.sqlite3.zst {SPOTIFY_TRACK_METADATA_ZST}\n", "!mv {SPOTIFY_DATA_DOWNLOAD_TORRENT_DIR}/spotify_clean_audio_features.sqlite3.zst {SPOTIFY_AUDIO_FEATURES_ZST}\n", "\n", "# Cleanup\n", "!rm -f {SPOTIFY_DATA_DOWNLOAD_MAIN_DIR}/*.aria2\n", "!rm -f {SPOTIFY_DATA_DOWNLOAD_MAIN_DIR}/*.torrent\n", "!rm -rf {SPOTIFY_DATA_DOWNLOAD_TORRENT_DIR}" ] }, { "cell_type": "markdown", "source": [ "### Uncompress" ], "metadata": { "id": "21NqiIFuRXFU" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "3eikGHX2B4A6" }, "outputs": [], "source": [ "# Uncompress the ZStandard files to get SQLite3 database files (160GB)\n", "!zstd --rm --decompress {SPOTIFY_TRACK_METADATA_ZST} -o {SPOTIFY_TRACK_METADATA_SQLITE3}\n", "!zstd --rm --decompress {SPOTIFY_AUDIO_FEATURES_ZST} -o {SPOTIFY_AUDIO_FEATURES_SQLITE3}" ] }, { "cell_type": "markdown", "source": [ "## Merge and Convert to Parquet" ], "metadata": { "id": "nUb3FUHXRckq" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "EU76M7UVQuTK" }, "outputs": [], "source": [ "def merge_to_parquet():\n", " # Connect to an in-memory DuckDB instance\n", " con = duckdb.connect()\n", "\n", " # Install and load the SQLite extension so DuckDB can read our files directly\n", " con.execute(\"INSTALL sqlite; LOAD sqlite;\")\n", "\n", " # This prevents the \"Type Mismatch\" crash by reading everything as raw text first.\n", " # We will fix the types in the SELECT statement below.\n", " con.execute(\"SET GLOBAL sqlite_all_varchar = true;\")\n", "\n", " # Attach the two SQLite databases\n", " # This treats them like mounted drives; it does not load them into RAM.\n", " con.execute(f\"ATTACH '{SPOTIFY_TRACK_METADATA_SQLITE3}' AS tm (TYPE SQLITE);\")\n", " con.execute(f\"ATTACH '{SPOTIFY_AUDIO_FEATURES_SQLITE3}' AS af (TYPE SQLITE);\")\n", "\n", " # Define the query\n", " # We select rowid explicitly from both tables and alias them to avoid collision\n", " # We then CAST columns to their correct types. Since we read everything as VARCHAR,\n", " # we must cast them to BIGINT or DOUBLE.\n", " sql_query = \"\"\"\n", " SELECT\n", " -- Track Metadata (Integers and Strings)\n", " tm.tracks.id,\n", " tm.tracks.name,\n", " TRY_CAST(tm.tracks.popularity AS BIGINT) AS popularity,\n", "\n", " -- Audio Features (Integers)\n", " TRY_CAST(af.track_audio_features.null_response AS BIGINT) AS null_response,\n", " TRY_CAST(af.track_audio_features.duration_ms AS BIGINT) AS duration_ms,\n", " TRY_CAST(af.track_audio_features.time_signature AS BIGINT) AS time_signature,\n", " TRY_CAST(af.track_audio_features.key AS BIGINT) AS key,\n", " TRY_CAST(af.track_audio_features.mode AS BIGINT) AS mode,\n", "\n", " -- Audio Features (Floats)\n", " -- We explicitly CAST these to DOUBLE to ensure the Parquet file uses Float types\n", " TRY_CAST(af.track_audio_features.tempo AS DOUBLE) AS tempo,\n", " TRY_CAST(af.track_audio_features.danceability AS DOUBLE) AS danceability,\n", " TRY_CAST(af.track_audio_features.energy AS DOUBLE) AS energy,\n", " TRY_CAST(af.track_audio_features.loudness AS DOUBLE) AS loudness,\n", " TRY_CAST(af.track_audio_features.speechiness AS DOUBLE) AS speechiness,\n", " TRY_CAST(af.track_audio_features.acousticness AS DOUBLE) AS acousticness,\n", " TRY_CAST(af.track_audio_features.instrumentalness AS DOUBLE) AS instrumentalness,\n", " TRY_CAST(af.track_audio_features.liveness AS DOUBLE) AS liveness,\n", " TRY_CAST(af.track_audio_features.valence AS DOUBLE) AS valence\n", "\n", " FROM tm.tracks\n", " JOIN af.track_audio_features\n", " ON tm.tracks.id = af.track_audio_features.track_id\n", " \"\"\"\n", "\n", " print(\"Starting merge and write... this may take a while depending on disk speed.\")\n", "\n", " # COPY ... TO ... is the fastest way to export.\n", " # We output to a folder ('merged_output').\n", " # PER_THREAD_OUTPUT=TRUE creates multiple files in parallel (much faster for 100GB).\n", " # ZSTD compression reduces file size significantly.\n", " con.sql(f\"\"\"\n", " COPY ({sql_query})\n", " TO '{SPOTIFY_MERGED_DATA_DIR}'\n", " (FORMAT PARQUET, PER_THREAD_OUTPUT TRUE, COMPRESSION 'ZSTD')\n", " \"\"\")\n", "\n", " print(f\"Done! Data saved in '{SPOTIFY_MERGED_DATA_DIR}' folder.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "e_vrm51TQuTL" }, "outputs": [], "source": [ "merge_to_parquet()" ] }, { "cell_type": "markdown", "source": [ "## Metadata Information" ], "metadata": { "id": "l0UVycEsRjcP" } }, { "cell_type": "markdown", "metadata": { "id": "JLT0-uNyzI8g" }, "source": [ "### Audio Features\n", "\n", "> Official API Documentation: https://developer.spotify.com/documentation/web-api/reference/get-audio-features\n", "\n", "- **`track_id`**: The Spotify ID (Base62) for the track.\n", "- **`null_response`**: true if the API returned null for the whole request\n", "- **`duration_ms`**: The duration of the track in milliseconds.\n", "- **`time_signature`**: An estimated time signature. The time signature (meter) is a notational convention to specify how many beats are in each bar (or measure). The time signature ranges from 3 to 7 indicating time signatures of \"3/4\" to \"7/4\".\n", "- **`tempo`**: The overall estimated tempo of a track in beats per minute (BPM). In musical terminology, tempo is the speed or pace of a given piece and derives directly from the average beat duration.\n", "- **`key`**: The key the track is in. Integers map to pitches using standard Pitch Class (https://en.wikipedia.org/wiki/Pitch_class) notation. E.g. 0 = C, 1 = C♯/D♭, 2 = D, and so on. If no key was detected, the value is -1.\n", "- **`mode`**: Mode indicates the modality (major or minor) of a track, the type of scale from which its melodic content is derived. Major is represented by 1 and minor is 0.\n", "- **`danceability`**: Danceability describes how suitable a track is for dancing based on a combination of musical elements including tempo, rhythm stability, beat strength, and overall regularity. A value of 0.0 is least danceable and 1.0 is most danceable.\n", "- **`energy`**: Energy is a measure from 0.0 to 1.0 and represents a perceptual measure of intensity and activity. Typically, energetic tracks feel fast, loud, and noisy. For example, death metal has high energy, while a Bach prelude scores low on the scale. Perceptual features contributing to this attribute include dynamic range, perceived loudness, timbre, onset rate, and general entropy.\n", "- **`loudness`**: The overall loudness of a track in decibels (dB). Loudness values are averaged across the entire track and are useful for comparing relative loudness of tracks. Loudness is the quality of a sound that is the primary psychological correlate of physical strength (amplitude). Values typically range between -60 and 0 db.\n", "- **`speechiness`**: Speechiness detects the presence of spoken words in a track. The more exclusively speech-like the recording (e.g. talk show, audio book, poetry), the closer to 1.0 the attribute value. Values above 0.66 describe tracks that are probably made entirely of spoken words. Values between 0.33 and 0.66 describe tracks that may contain both music and speech, either in sections or layered, including such cases as rap music. Values below 0.33 most likely represent music and other non-speech-like tracks.\n", "- **`acousticness`**: A confidence measure from 0.0 to 1.0 of whether the track is acoustic. 1.0 represents high confidence the track is acoustic.\n", "- **`instrumentalness`**: Predicts whether a track contains no vocals. \"Ooh\" and \"aah\" sounds are treated as instrumental in this context. Rap or spoken word tracks are clearly \"vocal\". The closer the instrumentalness value is to 1.0, the greater likelihood the track contains no vocal content. Values above 0.5 are intended to represent instrumental tracks, but confidence is higher as the value approaches 1.0.\n", "- **`liveness`**: Detects the presence of an audience in the recording. Higher liveness values represent an increased probability that the track was performed live. A value above 0.8 provides strong likelihood that the track is live.\n", "- **`valence`**: A measure from 0.0 to 1.0 describing the musical positiveness conveyed by a track. Tracks with high valence sound more positive (e.g. happy, cheerful, euphoric), while tracks with low valence sound more negative (e.g. sad, depressed, angry)." ] }, { "cell_type": "markdown", "metadata": { "id": "YF5Lyd5pQuTN" }, "source": [ "### Track Metadata\n", "\n", "> Official API Documentation: https://developer.spotify.com/documentation/web-api/reference/get-track\n", "\n", "- **`id`**: The Spotify ID (Base62) for the track.\n", "- **`name`**: The name of the track.\n", "- **`popularity`**: The popularity of the track. The value will be between 0 and 100, with 100 being the most popular. The popularity of a track is a value between 0 and 100, with 100 being the most popular. The popularity is calculated by algorithm and is based, in the most part, on the total number of plays the track has had and how recent those plays are. Generally speaking, songs that are being played a lot now will have a higher popularity than songs that were played a lot in the past. Duplicate tracks (e.g. the same track from a single and an album) are rated independently. Artist and album popularity is derived mathematically from track popularity. **Note**: *the popularity value may lag actual popularity by a few days: the value is not updated in real time.*" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "OlSHZ5M3X2f0" }, "outputs": [], "source": [] } ], "metadata": { "colab": { "provenance": [] }, "kernelspec": { "display_name": "Python3 (ipykernel)", "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.12.12" } }, "nbformat": 4, "nbformat_minor": 0 }