Milestone

Completed

The Python script

What we need in the script

The script

It pulls your entire Last.fm weekly artist history, week‑by‑week, and writes the results into either CSV or NDJSON, with optional resume support, retry logic, and top‑N filtering.

Below is a structured, detailed breakdown of what each part does.

🧠 High‑level summary

The script:

  • Calls Last.fm’s API to fetch all weekly chart periods for a given user.
  • For each week, fetches the weekly top artists.
  • Writes each week’s results to:
    • CSV (tabular)
    • NDJSON (one JSON object per line)

Supports:

  • Resuming interrupted runs (skips already‑written weeks)
  • Rate‑limit backoff
  • Top‑N filtering
  • Delay between API calls

🧩 Breakdown by component

1. Imports and constants

Uses standard libraries (argparse, csv, json, os, time, etc.) plus requests for HTTP calls.

API_BASE is the Last.fm API endpoint.


2. api_call()

A robust wrapper around Last.fm API requests.

  • Adds api_key and format=json to the request.

  • Retries up to max_retries times.

  • Handles:

    • HTTP 429 (rate limit)
    • Last.fm error code 29 (rate limit exceeded)
  • Exponential backoff: sleeps 2^attempt seconds.

  • Returns parsed JSON.

This ensures the script doesn’t crash on transient API issues.


3. get_weekly_chart_list(user, api_key)

Calls:

user.getweeklychartlist

Returns a list of week objects:

{
  "from": "timestamp",
  "to": "timestamp"
}

This defines the full scrobbling history in weekly chunks.


4. get_weekly_artist_chart(user, from_ts, to_ts, api_key)

Calls:

user.getweeklyartistchart

Returns a list of artists for that week.

Last.fm sometimes returns a single artist as a dict instead of a list, so the script normalises it:

if isinstance(artists, dict):
    artists = [artists]

5. fmt_date(ts)

Converts a Unix timestamp → YYYY-MM-DD in UTC.


6. load_done_weeks(path)

Used when --resume is passed.

Reads the output file and extracts all from_ts values already written.

Supports:

  • CSV
  • NDJSON / JSONL

Returns a set of week timestamps to skip.


7. Argument parsing

Supported flags: --user (required)

--output (.csv or .ndjson)

--top-n (default 10)

--delay between API calls

--resume to skip already-written weeks


8. Main workflow

Step 1 — Load API key Requires LASTFM_API_KEY environment variable.

Step 2 — Fetch all weeks Calls get_weekly_chart_list.

Step 3 — Determine resume state If --resume and file exists → load done weeks.

Step 4 — Open output file CSV: writes header if not resuming

NDJSON: no header

Step 5 — Loop over each week For each week:

  1. Skip if already done.

  2. Print progress.

  3. Fetch weekly artist chart.

  4. Take top‑N artists.

  5. Write: If no artists → write an empty row (playcount 0) Otherwise → write each artist with rank, name, mbid, playcount.

Flush after each week.

Sleep args.delay seconds.


9. Final cleanup

Closes files and prints completion message.

📄 What the output looks like:

CSV Columns:

  • week_start
  • week_end
  • from_ts
  • to_ts
  • rank
  • artist
  • mbid
  • playcount

NDJSON

Each line is a JSON object with the same fields.


🧠 Why this script is useful

It provides a complete historical dataset of listening habits, week‑by‑week, suitable for:

  • time‑series analysis
  • trend detection
  • visualisations
  • artist popularity tracking
  • personal listening history archives