scrobbles 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scrobbles/__init__.py +76 -0
- scrobbles/albums.py +392 -0
- scrobbles/cli.py +95 -0
- scrobbles/spotify.py +164 -0
- scrobbles-0.1.0.dist-info/METADATA +175 -0
- scrobbles-0.1.0.dist-info/RECORD +9 -0
- scrobbles-0.1.0.dist-info/WHEEL +4 -0
- scrobbles-0.1.0.dist-info/entry_points.txt +2 -0
- scrobbles-0.1.0.dist-info/licenses/LICENSE +21 -0
scrobbles/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# scrobbles/__init__.py
|
|
2
|
+
#
|
|
3
|
+
# You have to have your own unique two values for API_KEY and API_SECRET
|
|
4
|
+
# Obtain yours from https://www.last.fm/api/account for Last.fm
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import pylast
|
|
9
|
+
|
|
10
|
+
API_KEY = os.environ["LASTFM_API_KEY"]
|
|
11
|
+
API_SECRET = os.environ["LASTFM_API_SECRET"]
|
|
12
|
+
username = os.environ["LASTFM_USERNAME"]
|
|
13
|
+
password = os.environ["LASTFM_PASSWORD"]
|
|
14
|
+
password_hash = pylast.md5(password)
|
|
15
|
+
network = pylast.LastFMNetwork(
|
|
16
|
+
api_key=API_KEY,
|
|
17
|
+
api_secret=API_SECRET,
|
|
18
|
+
username=username,
|
|
19
|
+
password_hash=password_hash,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
TRACK_SEPARATOR = " - "
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def get_user(network: pylast.LastFMNetwork, username: str) -> pylast.User:
|
|
26
|
+
return network.get_user(username)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def track_and_timestamp(track):
|
|
30
|
+
return f"{track.playback_date}\t{track.track}"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def print_track(track):
|
|
34
|
+
print(track_and_timestamp(track))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def split_artist_track(artist_track):
|
|
38
|
+
artist_track = artist_track.replace(" – ", " - ")
|
|
39
|
+
artist_track = artist_track.replace("“", '"')
|
|
40
|
+
artist_track = artist_track.replace("”", '"')
|
|
41
|
+
|
|
42
|
+
(artist, track) = artist_track.split(TRACK_SEPARATOR)
|
|
43
|
+
artist = artist.strip()
|
|
44
|
+
track = track.strip()
|
|
45
|
+
print("Artist:\t\t'" + artist + "'")
|
|
46
|
+
print("Track:\t\t'" + track + "'")
|
|
47
|
+
|
|
48
|
+
# Validate
|
|
49
|
+
if len(artist) == 0 and len(track) == 0:
|
|
50
|
+
sys.exit("Error: Artist and track are blank")
|
|
51
|
+
if len(artist) == 0:
|
|
52
|
+
sys.exit("Error: Artist is blank")
|
|
53
|
+
if len(track) == 0:
|
|
54
|
+
sys.exit("Error: Track is blank")
|
|
55
|
+
|
|
56
|
+
return (artist, track)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def get_now_playing(username: str) -> str:
|
|
60
|
+
user = get_user(network, username)
|
|
61
|
+
now_playing = user.get_now_playing()
|
|
62
|
+
if now_playing is None:
|
|
63
|
+
return "Nothing is currently playing."
|
|
64
|
+
return f"Now playing: {now_playing.artist} - {now_playing.title}"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def get_recent_tracks(username, number):
|
|
68
|
+
recent_tracks = network.get_user(username).get_recent_tracks(limit=number)
|
|
69
|
+
for i, track in enumerate(recent_tracks):
|
|
70
|
+
printable = track_and_timestamp(track)
|
|
71
|
+
print(str(i + 1) + " " + printable)
|
|
72
|
+
return recent_tracks
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
from scrobbles.albums import build_dashboard, dump_top_albums, get_top_albums, print_top_albums
|
|
76
|
+
from scrobbles.spotify import create_all_playlists, create_playlist_from_albums
|
scrobbles/albums.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
# scrobbles/albums.py
|
|
2
|
+
"""Fetch and display top albums for a Last.fm user."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
from datetime import datetime, timedelta
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import pylast
|
|
10
|
+
|
|
11
|
+
from scrobbles import network
|
|
12
|
+
|
|
13
|
+
_PREDEFINED_PERIODS = {
|
|
14
|
+
"overall": pylast.PERIOD_OVERALL,
|
|
15
|
+
"7day": pylast.PERIOD_7DAYS,
|
|
16
|
+
"1month": pylast.PERIOD_1MONTH,
|
|
17
|
+
"3month": pylast.PERIOD_3MONTHS,
|
|
18
|
+
"6month": pylast.PERIOD_6MONTHS,
|
|
19
|
+
"12month": pylast.PERIOD_12MONTHS,
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _resolve_date_range(period: str) -> tuple[str, str]:
|
|
24
|
+
"""Convert a human-readable period string to (from_ts, to_ts) Unix timestamps."""
|
|
25
|
+
now = datetime.now()
|
|
26
|
+
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
27
|
+
|
|
28
|
+
if period == "today":
|
|
29
|
+
start, end = today, now
|
|
30
|
+
elif period == "yesterday":
|
|
31
|
+
start = today - timedelta(days=1)
|
|
32
|
+
end = today
|
|
33
|
+
elif period == "last_week":
|
|
34
|
+
# Monday of this week, then back 7 days
|
|
35
|
+
monday = today - timedelta(days=today.weekday())
|
|
36
|
+
start = monday - timedelta(weeks=1)
|
|
37
|
+
end = monday
|
|
38
|
+
elif period == "last_month":
|
|
39
|
+
first_of_month = today.replace(day=1)
|
|
40
|
+
end = first_of_month
|
|
41
|
+
# First of previous month
|
|
42
|
+
prev = first_of_month - timedelta(days=1)
|
|
43
|
+
start = prev.replace(day=1)
|
|
44
|
+
elif period == "last_year":
|
|
45
|
+
start = today.replace(month=1, day=1, year=today.year - 1)
|
|
46
|
+
end = today.replace(month=1, day=1)
|
|
47
|
+
elif re.fullmatch(r"\d{4}", period):
|
|
48
|
+
year = int(period)
|
|
49
|
+
start = today.replace(year=year, month=1, day=1)
|
|
50
|
+
end = today.replace(year=year + 1, month=1, day=1)
|
|
51
|
+
elif re.fullmatch(r"\d{4}-\d{2}", period):
|
|
52
|
+
year, month = (int(x) for x in period.split("-"))
|
|
53
|
+
start = today.replace(year=year, month=month, day=1)
|
|
54
|
+
if month == 12:
|
|
55
|
+
end = today.replace(year=year + 1, month=1, day=1)
|
|
56
|
+
else:
|
|
57
|
+
end = today.replace(year=year, month=month + 1, day=1)
|
|
58
|
+
elif re.fullmatch(r"\d{4}-\d{2}-\d{2}", period):
|
|
59
|
+
year, month, day = (int(x) for x in period.split("-"))
|
|
60
|
+
start = today.replace(year=year, month=month, day=day)
|
|
61
|
+
end = start + timedelta(days=1)
|
|
62
|
+
else:
|
|
63
|
+
raise ValueError(
|
|
64
|
+
f"Unrecognized period: {period!r}. "
|
|
65
|
+
f"Use a predefined period ({', '.join(_PREDEFINED_PERIODS)}), "
|
|
66
|
+
"or: today, yesterday, last_week, last_month, last_year, "
|
|
67
|
+
"YYYY, YYYY-MM, YYYY-MM-DD"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
return str(int(start.timestamp())), str(int(end.timestamp()))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def get_top_albums(username: str, period: str = "overall", limit: int = 10):
|
|
74
|
+
"""Return top albums for a user over the given period."""
|
|
75
|
+
user = network.get_user(username)
|
|
76
|
+
|
|
77
|
+
if period in _PREDEFINED_PERIODS:
|
|
78
|
+
return user.get_top_albums(period=_PREDEFINED_PERIODS[period], limit=limit)
|
|
79
|
+
|
|
80
|
+
from_date, to_date = _resolve_date_range(period)
|
|
81
|
+
charts = user.get_weekly_album_charts(from_date=from_date, to_date=to_date)
|
|
82
|
+
charts.sort(key=lambda item: int(item.weight), reverse=True)
|
|
83
|
+
return charts[:limit]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def format_top_albums(items) -> str:
|
|
87
|
+
"""Format album items as a numbered list."""
|
|
88
|
+
lines = []
|
|
89
|
+
for i, item in enumerate(items, 1):
|
|
90
|
+
lines.append(f"{i}. {item.item.artist} - {item.item.title} ({item.weight} plays)")
|
|
91
|
+
return "\n".join(lines)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def print_top_albums(username: str, period: str = "overall", limit: int = 10):
|
|
95
|
+
"""Fetch, print, and return top albums for a user."""
|
|
96
|
+
items = get_top_albums(username, period, limit)
|
|
97
|
+
print(format_top_albums(items))
|
|
98
|
+
return items
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def top_item_to_dict(item) -> dict:
|
|
102
|
+
"""Convert a pylast TopItem to a plain dict."""
|
|
103
|
+
return {
|
|
104
|
+
"artist": str(item.item.artist),
|
|
105
|
+
"album": str(item.item.title),
|
|
106
|
+
"plays": int(item.weight),
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def top_albums_to_json(items, **kwargs) -> str:
|
|
111
|
+
"""Serialize a list of TopItems to a JSON string."""
|
|
112
|
+
return json.dumps([top_item_to_dict(i) for i in items], **kwargs)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def dump_top_albums(
|
|
116
|
+
username: str,
|
|
117
|
+
period: str = "overall",
|
|
118
|
+
limit: int = 10,
|
|
119
|
+
path: str | Path | None = None,
|
|
120
|
+
) -> Path:
|
|
121
|
+
"""Fetch top albums and write them to a JSON file.
|
|
122
|
+
|
|
123
|
+
If path is None, writes to data/albums/topN-{period}.json
|
|
124
|
+
relative to the project root.
|
|
125
|
+
"""
|
|
126
|
+
items = get_top_albums(username, period, limit)
|
|
127
|
+
if path is None:
|
|
128
|
+
path = Path("data/albums") / f"top{limit}-{period}.json"
|
|
129
|
+
path = Path(path)
|
|
130
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
131
|
+
path.write_text(top_albums_to_json(items, indent=2) + "\n")
|
|
132
|
+
print(f"Wrote {len(items)} albums to {path}")
|
|
133
|
+
return path
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def build_dashboard(data_dir: str | Path = "data/albums", output: str | Path | None = None) -> Path:
|
|
137
|
+
"""Generate an interactive HTML dashboard from the JSON data files.
|
|
138
|
+
|
|
139
|
+
Reads all top100-*.json from *data_dir*, embeds the data inline,
|
|
140
|
+
and writes a self-contained HTML file with Chart.js charts, a year
|
|
141
|
+
selector, search, and a dark-themed album table.
|
|
142
|
+
|
|
143
|
+
Returns the output path.
|
|
144
|
+
"""
|
|
145
|
+
data_dir = Path(data_dir)
|
|
146
|
+
if output is None:
|
|
147
|
+
output = data_dir / "index.html"
|
|
148
|
+
output = Path(output)
|
|
149
|
+
|
|
150
|
+
# Collect all top100 JSON files into a single {year: [...]} dict
|
|
151
|
+
all_data: dict[str, list[dict]] = {}
|
|
152
|
+
for f in sorted(data_dir.glob("top100-*.json")):
|
|
153
|
+
year = f.stem.split("-", 1)[1]
|
|
154
|
+
all_data[year] = json.loads(f.read_text())
|
|
155
|
+
|
|
156
|
+
if not all_data:
|
|
157
|
+
raise FileNotFoundError(f"No top100-*.json files found in {data_dir}")
|
|
158
|
+
|
|
159
|
+
years = sorted(all_data.keys())
|
|
160
|
+
data_blob = json.dumps(all_data, separators=(",", ":"))
|
|
161
|
+
|
|
162
|
+
html = f"""\
|
|
163
|
+
<!DOCTYPE html>
|
|
164
|
+
<html lang="en">
|
|
165
|
+
<head>
|
|
166
|
+
<meta charset="UTF-8">
|
|
167
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
168
|
+
<title>Last.fm Top Albums</title>
|
|
169
|
+
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
|
|
170
|
+
<style>
|
|
171
|
+
:root {{
|
|
172
|
+
--bg: #0d1117; --surface: #161b22; --border: #30363d;
|
|
173
|
+
--text: #e6edf3; --text-muted: #8b949e; --accent: #58a6ff;
|
|
174
|
+
--accent2: #f78166; --accent3: #7ee787; --accent4: #d2a8ff;
|
|
175
|
+
}}
|
|
176
|
+
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
|
|
177
|
+
body {{
|
|
178
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
|
|
179
|
+
background: var(--bg); color: var(--text); line-height: 1.5;
|
|
180
|
+
padding: 2rem; max-width: 1200px; margin: 0 auto;
|
|
181
|
+
}}
|
|
182
|
+
h1 {{ font-size: 2rem; margin-bottom: 0.25rem; }}
|
|
183
|
+
.subtitle {{ color: var(--text-muted); margin-bottom: 2rem; font-size: 0.95rem; }}
|
|
184
|
+
.cards {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 1rem; margin-bottom: 2rem; }}
|
|
185
|
+
.card {{
|
|
186
|
+
background: var(--surface); border: 1px solid var(--border); border-radius: 8px;
|
|
187
|
+
padding: 1rem; text-align: center;
|
|
188
|
+
}}
|
|
189
|
+
.card .value {{ font-size: 1.8rem; font-weight: 700; color: var(--accent); }}
|
|
190
|
+
.card .label {{ font-size: 0.8rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; }}
|
|
191
|
+
.chart-row {{ display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 2rem; }}
|
|
192
|
+
.chart-box {{
|
|
193
|
+
background: var(--surface); border: 1px solid var(--border); border-radius: 8px;
|
|
194
|
+
padding: 1.25rem;
|
|
195
|
+
}}
|
|
196
|
+
.chart-box h3 {{ font-size: 0.95rem; color: var(--text-muted); margin-bottom: 0.75rem; }}
|
|
197
|
+
.chart-box canvas {{ width: 100% !important; }}
|
|
198
|
+
.year-bar {{ display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 1.5rem; }}
|
|
199
|
+
.year-btn {{
|
|
200
|
+
background: var(--surface); border: 1px solid var(--border); border-radius: 6px;
|
|
201
|
+
color: var(--text-muted); padding: 0.4rem 0.9rem; cursor: pointer; font-size: 0.85rem;
|
|
202
|
+
transition: all 0.15s;
|
|
203
|
+
}}
|
|
204
|
+
.year-btn:hover {{ border-color: var(--accent); color: var(--text); }}
|
|
205
|
+
.year-btn.active {{ background: var(--accent); color: var(--bg); border-color: var(--accent); font-weight: 600; }}
|
|
206
|
+
.table-wrap {{ background: var(--surface); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }}
|
|
207
|
+
table {{ width: 100%; border-collapse: collapse; }}
|
|
208
|
+
th {{ text-align: left; padding: 0.75rem 1rem; font-size: 0.75rem; text-transform: uppercase;
|
|
209
|
+
letter-spacing: 0.05em; color: var(--text-muted); border-bottom: 1px solid var(--border); }}
|
|
210
|
+
td {{ padding: 0.6rem 1rem; border-bottom: 1px solid var(--border); font-size: 0.9rem; }}
|
|
211
|
+
tr:last-child td {{ border-bottom: none; }}
|
|
212
|
+
tr:hover td {{ background: rgba(88,166,255,0.05); }}
|
|
213
|
+
.rank {{ color: var(--text-muted); font-weight: 600; width: 3rem; }}
|
|
214
|
+
.plays {{ text-align: right; font-variant-numeric: tabular-nums; font-weight: 600; color: var(--accent3); }}
|
|
215
|
+
.bar-cell {{ width: 30%; }}
|
|
216
|
+
.bar-bg {{ background: var(--border); border-radius: 3px; height: 6px; }}
|
|
217
|
+
.bar-fill {{ background: var(--accent); border-radius: 3px; height: 6px; transition: width 0.3s; }}
|
|
218
|
+
.artist-col {{ color: var(--text-muted); }}
|
|
219
|
+
.top-artists {{ display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 2rem; }}
|
|
220
|
+
.artist-badge {{
|
|
221
|
+
background: var(--surface); border: 1px solid var(--border); border-radius: 20px;
|
|
222
|
+
padding: 0.35rem 0.85rem; font-size: 0.82rem; display: flex; align-items: center; gap: 0.4rem;
|
|
223
|
+
}}
|
|
224
|
+
.artist-badge .count {{ color: var(--accent); font-weight: 600; }}
|
|
225
|
+
.search-wrap {{ margin-bottom: 1rem; }}
|
|
226
|
+
.search-wrap input {{
|
|
227
|
+
background: var(--surface); border: 1px solid var(--border); border-radius: 6px;
|
|
228
|
+
color: var(--text); padding: 0.5rem 0.75rem; font-size: 0.9rem; width: 100%; max-width: 360px;
|
|
229
|
+
outline: none;
|
|
230
|
+
}}
|
|
231
|
+
.search-wrap input:focus {{ border-color: var(--accent); }}
|
|
232
|
+
.search-wrap input::placeholder {{ color: var(--text-muted); }}
|
|
233
|
+
.year-stats {{ color: var(--text-muted); font-size: 0.85rem; margin-bottom: 1rem; }}
|
|
234
|
+
@media (max-width: 700px) {{ .chart-row {{ grid-template-columns: 1fr; }} body {{ padding: 1rem; }} }}
|
|
235
|
+
</style>
|
|
236
|
+
</head>
|
|
237
|
+
<body>
|
|
238
|
+
|
|
239
|
+
<h1>Last.fm Top Albums</h1>
|
|
240
|
+
<p class="subtitle">Top 100 albums per year · {years[0]} – {years[-1]}</p>
|
|
241
|
+
|
|
242
|
+
<div class="cards" id="cards"></div>
|
|
243
|
+
<div class="chart-row">
|
|
244
|
+
<div class="chart-box"><h3>Total Plays per Year (Top 100)</h3><canvas id="chartPlays"></canvas></div>
|
|
245
|
+
<div class="chart-box"><h3>Unique Artists per Year (Top 100)</h3><canvas id="chartArtists"></canvas></div>
|
|
246
|
+
</div>
|
|
247
|
+
<div class="chart-row">
|
|
248
|
+
<div class="chart-box"><h3>#1 Album Plays by Year</h3><canvas id="chartTop1"></canvas></div>
|
|
249
|
+
<div class="chart-box"><h3>Top 10 Artists (All Time by Appearances)</h3><canvas id="chartTopArtists"></canvas></div>
|
|
250
|
+
</div>
|
|
251
|
+
|
|
252
|
+
<h3 style="margin-bottom:0.75rem;">Albums by Year</h3>
|
|
253
|
+
<div class="year-bar" id="yearBar"></div>
|
|
254
|
+
<div class="search-wrap"><input type="text" id="search" placeholder="Filter by artist or album..."></div>
|
|
255
|
+
<p class="year-stats" id="yearStats"></p>
|
|
256
|
+
<h4 style="margin-bottom:0.5rem; color:var(--text-muted); font-size:0.8rem;">TOP ARTISTS THIS YEAR</h4>
|
|
257
|
+
<div class="top-artists" id="topArtists"></div>
|
|
258
|
+
<div class="table-wrap">
|
|
259
|
+
<table>
|
|
260
|
+
<thead><tr><th>#</th><th>Album</th><th>Artist</th><th></th><th>Plays</th></tr></thead>
|
|
261
|
+
<tbody id="tbody"></tbody>
|
|
262
|
+
</table>
|
|
263
|
+
</div>
|
|
264
|
+
|
|
265
|
+
<script>
|
|
266
|
+
const DATA = {data_blob};
|
|
267
|
+
|
|
268
|
+
const years = Object.keys(DATA).sort();
|
|
269
|
+
let activeYear = years[years.length - 2];
|
|
270
|
+
|
|
271
|
+
let totalPlaysAll = 0, totalAlbumsAll = 0;
|
|
272
|
+
const allArtists = new Set();
|
|
273
|
+
const artistYearCount = {{}};
|
|
274
|
+
const yearStatsMap = {{}};
|
|
275
|
+
|
|
276
|
+
years.forEach(y => {{
|
|
277
|
+
const albums = DATA[y];
|
|
278
|
+
const plays = albums.reduce((s, a) => s + a.plays, 0);
|
|
279
|
+
const artists = new Set(albums.map(a => a.artist));
|
|
280
|
+
totalPlaysAll += plays;
|
|
281
|
+
totalAlbumsAll += albums.length;
|
|
282
|
+
artists.forEach(a => {{ allArtists.add(a); artistYearCount[a] = (artistYearCount[a] || 0) + 1; }});
|
|
283
|
+
yearStatsMap[y] = {{ plays, artistCount: artists.size, top: albums[0] }};
|
|
284
|
+
}});
|
|
285
|
+
|
|
286
|
+
document.getElementById('cards').innerHTML = `
|
|
287
|
+
<div class="card"><div class="value">${{totalPlaysAll.toLocaleString()}}</div><div class="label">Total Plays</div></div>
|
|
288
|
+
<div class="card"><div class="value">${{years.length}}</div><div class="label">Years</div></div>
|
|
289
|
+
<div class="card"><div class="value">${{allArtists.size}}</div><div class="label">Unique Artists</div></div>
|
|
290
|
+
<div class="card"><div class="value">${{totalAlbumsAll.toLocaleString()}}</div><div class="label">Album Entries</div></div>
|
|
291
|
+
`;
|
|
292
|
+
|
|
293
|
+
const chartOpts = (ylabel) => ({{
|
|
294
|
+
responsive: true, plugins: {{ legend: {{ display: false }} }},
|
|
295
|
+
scales: {{
|
|
296
|
+
x: {{ ticks: {{ color: '#8b949e' }}, grid: {{ color: '#21262d' }} }},
|
|
297
|
+
y: {{ ticks: {{ color: '#8b949e' }}, grid: {{ color: '#21262d' }}, title: {{ display: true, text: ylabel, color: '#8b949e' }} }}
|
|
298
|
+
}}
|
|
299
|
+
}});
|
|
300
|
+
|
|
301
|
+
new Chart(document.getElementById('chartPlays'), {{
|
|
302
|
+
type: 'bar',
|
|
303
|
+
data: {{ labels: years, datasets: [{{ data: years.map(y => yearStatsMap[y].plays), backgroundColor: '#58a6ff88', borderColor: '#58a6ff', borderWidth: 1, borderRadius: 4 }}] }},
|
|
304
|
+
options: chartOpts('Plays')
|
|
305
|
+
}});
|
|
306
|
+
|
|
307
|
+
new Chart(document.getElementById('chartArtists'), {{
|
|
308
|
+
type: 'bar',
|
|
309
|
+
data: {{ labels: years, datasets: [{{ data: years.map(y => yearStatsMap[y].artistCount), backgroundColor: '#7ee78788', borderColor: '#7ee787', borderWidth: 1, borderRadius: 4 }}] }},
|
|
310
|
+
options: chartOpts('Artists')
|
|
311
|
+
}});
|
|
312
|
+
|
|
313
|
+
new Chart(document.getElementById('chartTop1'), {{
|
|
314
|
+
type: 'bar',
|
|
315
|
+
data: {{
|
|
316
|
+
labels: years.map(y => `${{y}}: ${{yearStatsMap[y].top.artist}}`),
|
|
317
|
+
datasets: [{{ data: years.map(y => yearStatsMap[y].top.plays), backgroundColor: '#d2a8ff88', borderColor: '#d2a8ff', borderWidth: 1, borderRadius: 4 }}]
|
|
318
|
+
}},
|
|
319
|
+
options: {{ ...chartOpts('Plays'),
|
|
320
|
+
scales: {{ ...chartOpts('Plays').scales, x: {{ ...chartOpts('Plays').scales.x, ticks: {{ ...chartOpts('Plays').scales.x.ticks, maxRotation: 45, minRotation: 45, font: {{ size: 10 }} }} }} }}
|
|
321
|
+
}}
|
|
322
|
+
}});
|
|
323
|
+
|
|
324
|
+
const topArtistsSorted = Object.entries(artistYearCount).sort((a, b) => b[1] - a[1]).slice(0, 10);
|
|
325
|
+
new Chart(document.getElementById('chartTopArtists'), {{
|
|
326
|
+
type: 'bar',
|
|
327
|
+
data: {{
|
|
328
|
+
labels: topArtistsSorted.map(a => a[0]),
|
|
329
|
+
datasets: [{{ data: topArtistsSorted.map(a => a[1]), backgroundColor: '#f7816688', borderColor: '#f78166', borderWidth: 1, borderRadius: 4 }}]
|
|
330
|
+
}},
|
|
331
|
+
options: {{ indexAxis: 'y', ...chartOpts('Year Appearances'),
|
|
332
|
+
scales: {{ x: {{ ticks: {{ color: '#8b949e', stepSize: 1 }}, grid: {{ color: '#21262d' }}, title: {{ display: true, text: 'Year Appearances', color: '#8b949e' }} }},
|
|
333
|
+
y: {{ ticks: {{ color: '#8b949e' }}, grid: {{ color: '#21262d' }} }} }}
|
|
334
|
+
}}
|
|
335
|
+
}});
|
|
336
|
+
|
|
337
|
+
function renderYear(year, filter = '') {{
|
|
338
|
+
activeYear = year;
|
|
339
|
+
document.querySelectorAll('.year-btn').forEach(b => b.classList.toggle('active', b.dataset.year === year));
|
|
340
|
+
|
|
341
|
+
const albums = DATA[year];
|
|
342
|
+
const maxPlays = albums[0]?.plays || 1;
|
|
343
|
+
const q = filter.toLowerCase();
|
|
344
|
+
const filtered = q ? albums.filter(a => a.artist.toLowerCase().includes(q) || a.album.toLowerCase().includes(q)) : albums;
|
|
345
|
+
|
|
346
|
+
const stats = yearStatsMap[year];
|
|
347
|
+
document.getElementById('yearStats').textContent =
|
|
348
|
+
`${{stats.plays.toLocaleString()}} plays \\u00b7 ${{stats.artistCount}} unique artists \\u00b7 #1: ${{stats.top.artist}} \\u2013 ${{stats.top.album}} (${{stats.top.plays}} plays)`;
|
|
349
|
+
|
|
350
|
+
const artistPlays = {{}};
|
|
351
|
+
albums.forEach(a => {{ artistPlays[a.artist] = (artistPlays[a.artist] || 0) + a.plays; }});
|
|
352
|
+
const topA = Object.entries(artistPlays).sort((a, b) => b[1] - a[1]).slice(0, 8);
|
|
353
|
+
document.getElementById('topArtists').innerHTML = topA.map(([name, plays]) =>
|
|
354
|
+
`<span class="artist-badge">${{name}} <span class="count">${{plays}}</span></span>`
|
|
355
|
+
).join('');
|
|
356
|
+
|
|
357
|
+
const tbody = document.getElementById('tbody');
|
|
358
|
+
tbody.innerHTML = filtered.map((a, i) => {{
|
|
359
|
+
const origIdx = albums.indexOf(a) + 1;
|
|
360
|
+
const pct = (a.plays / maxPlays * 100).toFixed(1);
|
|
361
|
+
return `<tr>
|
|
362
|
+
<td class="rank">${{origIdx}}</td>
|
|
363
|
+
<td>${{a.album}}</td>
|
|
364
|
+
<td class="artist-col">${{a.artist}}</td>
|
|
365
|
+
<td class="bar-cell"><div class="bar-bg"><div class="bar-fill" style="width:${{pct}}%"></div></div></td>
|
|
366
|
+
<td class="plays">${{a.plays}}</td>
|
|
367
|
+
</tr>`;
|
|
368
|
+
}}).join('');
|
|
369
|
+
}}
|
|
370
|
+
|
|
371
|
+
const yearBar = document.getElementById('yearBar');
|
|
372
|
+
years.forEach(y => {{
|
|
373
|
+
const btn = document.createElement('button');
|
|
374
|
+
btn.className = 'year-btn';
|
|
375
|
+
btn.dataset.year = y;
|
|
376
|
+
btn.textContent = y;
|
|
377
|
+
btn.onclick = () => renderYear(y, document.getElementById('search').value);
|
|
378
|
+
yearBar.appendChild(btn);
|
|
379
|
+
}});
|
|
380
|
+
|
|
381
|
+
document.getElementById('search').addEventListener('input', e => renderYear(activeYear, e.target.value));
|
|
382
|
+
|
|
383
|
+
renderYear(activeYear);
|
|
384
|
+
</script>
|
|
385
|
+
</body>
|
|
386
|
+
</html>
|
|
387
|
+
"""
|
|
388
|
+
|
|
389
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
390
|
+
output.write_text(html)
|
|
391
|
+
print(f"Wrote dashboard to {output} ({len(all_data)} years)")
|
|
392
|
+
return output
|
scrobbles/cli.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""CLI for scrobbles."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
USAGE = """\
|
|
6
|
+
Usage: scrobbles <command> [options]
|
|
7
|
+
|
|
8
|
+
Commands:
|
|
9
|
+
top-albums [period] [--limit N] Print top albums
|
|
10
|
+
dump-albums [period] [--limit N] Export top albums to JSON
|
|
11
|
+
dashboard Generate HTML dashboard
|
|
12
|
+
spotify-playlists [--dry-run] [--skip YEAR...] Create Spotify playlists
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _parse_args(argv: list[str], defaults: dict) -> dict:
|
|
17
|
+
"""Minimal argv parser. Supports --key value and --flag patterns."""
|
|
18
|
+
opts = dict(defaults)
|
|
19
|
+
i = 0
|
|
20
|
+
positional_keys = [k for k in defaults if not k.startswith("_")]
|
|
21
|
+
pos_idx = 0
|
|
22
|
+
while i < len(argv):
|
|
23
|
+
arg = argv[i]
|
|
24
|
+
if arg == "--limit" and i + 1 < len(argv):
|
|
25
|
+
opts["limit"] = int(argv[i + 1])
|
|
26
|
+
i += 2
|
|
27
|
+
elif arg == "--dry-run":
|
|
28
|
+
opts["dry_run"] = True
|
|
29
|
+
i += 1
|
|
30
|
+
elif arg == "--skip":
|
|
31
|
+
i += 1
|
|
32
|
+
skip = []
|
|
33
|
+
while i < len(argv) and not argv[i].startswith("--"):
|
|
34
|
+
skip.append(argv[i])
|
|
35
|
+
i += 1
|
|
36
|
+
opts["skip"] = skip
|
|
37
|
+
elif not arg.startswith("--") and pos_idx < len(positional_keys):
|
|
38
|
+
opts[positional_keys[pos_idx]] = arg
|
|
39
|
+
pos_idx += 1
|
|
40
|
+
i += 1
|
|
41
|
+
else:
|
|
42
|
+
i += 1
|
|
43
|
+
return opts
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def cmd_top_albums(argv: list[str]):
|
|
47
|
+
import os
|
|
48
|
+
from scrobbles.albums import print_top_albums
|
|
49
|
+
|
|
50
|
+
opts = _parse_args(argv, {"period": "overall", "limit": 10})
|
|
51
|
+
username = os.environ["LASTFM_USERNAME"]
|
|
52
|
+
print_top_albums(username, period=opts["period"], limit=opts["limit"])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def cmd_dump_albums(argv: list[str]):
|
|
56
|
+
import os
|
|
57
|
+
from scrobbles.albums import dump_top_albums
|
|
58
|
+
|
|
59
|
+
opts = _parse_args(argv, {"period": "overall", "limit": 100})
|
|
60
|
+
username = os.environ["LASTFM_USERNAME"]
|
|
61
|
+
dump_top_albums(username, period=opts["period"], limit=opts["limit"])
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def cmd_dashboard(argv: list[str]):
|
|
65
|
+
from scrobbles.albums import build_dashboard
|
|
66
|
+
|
|
67
|
+
build_dashboard()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def cmd_spotify_playlists(argv: list[str]):
|
|
71
|
+
from scrobbles.spotify import create_all_playlists
|
|
72
|
+
|
|
73
|
+
opts = _parse_args(argv, {"dry_run": False, "skip": []})
|
|
74
|
+
create_all_playlists(dry_run=opts["dry_run"], skip_years=set(opts["skip"]))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def main():
|
|
78
|
+
if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
|
|
79
|
+
print(USAGE)
|
|
80
|
+
sys.exit(0)
|
|
81
|
+
|
|
82
|
+
commands = {
|
|
83
|
+
"top-albums": cmd_top_albums,
|
|
84
|
+
"dump-albums": cmd_dump_albums,
|
|
85
|
+
"dashboard": cmd_dashboard,
|
|
86
|
+
"spotify-playlists": cmd_spotify_playlists,
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
cmd = sys.argv[1]
|
|
90
|
+
if cmd not in commands:
|
|
91
|
+
print(f"Unknown command: {cmd}\n")
|
|
92
|
+
print(USAGE)
|
|
93
|
+
sys.exit(1)
|
|
94
|
+
|
|
95
|
+
commands[cmd](sys.argv[2:])
|
scrobbles/spotify.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
# scrobbles/spotify.py
|
|
2
|
+
"""Create Spotify playlists from Last.fm top-album JSON data."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import spotipy
|
|
10
|
+
from spotipy.oauth2 import SpotifyOAuth
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_spotify_env():
|
|
14
|
+
"""Set SPOTIPY_* env vars from SPOTIFY_* if needed.
|
|
15
|
+
|
|
16
|
+
Spotipy reads SPOTIPY_CLIENT_ID / SPOTIPY_CLIENT_SECRET automatically,
|
|
17
|
+
but many users export SPOTIFY_CLIENT_ID / SPOTIFY_CLIENT_SECRET instead.
|
|
18
|
+
This bridges the gap so either naming convention works.
|
|
19
|
+
"""
|
|
20
|
+
mapping = {
|
|
21
|
+
"SPOTIPY_CLIENT_ID": "SPOTIFY_CLIENT_ID",
|
|
22
|
+
"SPOTIPY_CLIENT_SECRET": "SPOTIFY_CLIENT_SECRET",
|
|
23
|
+
}
|
|
24
|
+
for spotipy_key, alt_key in mapping.items():
|
|
25
|
+
if not os.environ.get(spotipy_key) and os.environ.get(alt_key):
|
|
26
|
+
os.environ[spotipy_key] = os.environ[alt_key]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def get_spotify_client() -> spotipy.Spotify:
|
|
30
|
+
"""Authenticate and return a Spotify client with playlist-modify scope."""
|
|
31
|
+
get_spotify_env()
|
|
32
|
+
return spotipy.Spotify(auth_manager=SpotifyOAuth(
|
|
33
|
+
scope="playlist-modify-public playlist-modify-private",
|
|
34
|
+
))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _truncate_query(query: str, max_len: int = 240) -> str:
|
|
38
|
+
"""Truncate a search query to fit Spotify's 250-char limit."""
|
|
39
|
+
if len(query) <= max_len:
|
|
40
|
+
return query
|
|
41
|
+
return query[:max_len]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def search_album_tracks(sp: spotipy.Spotify, artist: str, album: str) -> list[str]:
|
|
45
|
+
"""Search Spotify for an album and return its track URIs."""
|
|
46
|
+
try:
|
|
47
|
+
query = _truncate_query(f"album:{album} artist:{artist}")
|
|
48
|
+
results = sp.search(q=query, type="album", limit=5)
|
|
49
|
+
items = results["albums"]["items"]
|
|
50
|
+
if not items:
|
|
51
|
+
# Fallback: broader search without field prefixes
|
|
52
|
+
query = _truncate_query(f"{artist} {album}")
|
|
53
|
+
results = sp.search(q=query, type="album", limit=5)
|
|
54
|
+
items = results["albums"]["items"]
|
|
55
|
+
if not items:
|
|
56
|
+
return []
|
|
57
|
+
|
|
58
|
+
# Pick the best match (first result)
|
|
59
|
+
album_id = items[0]["id"]
|
|
60
|
+
tracks = sp.album_tracks(album_id)
|
|
61
|
+
return [t["uri"] for t in tracks["items"]]
|
|
62
|
+
except Exception:
|
|
63
|
+
return []
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def create_playlist_from_albums(
|
|
67
|
+
albums: list[dict],
|
|
68
|
+
name: str,
|
|
69
|
+
description: str = "",
|
|
70
|
+
dry_run: bool = False,
|
|
71
|
+
) -> dict:
|
|
72
|
+
"""Create a Spotify playlist from a list of album dicts.
|
|
73
|
+
|
|
74
|
+
Each dict should have ``artist``, ``album``, and ``plays`` keys.
|
|
75
|
+
Returns a summary dict with playlist URL, track count, and missed albums.
|
|
76
|
+
"""
|
|
77
|
+
sp = get_spotify_client()
|
|
78
|
+
user_id = sp.current_user()["id"]
|
|
79
|
+
|
|
80
|
+
all_uris: list[str] = []
|
|
81
|
+
missed: list[str] = []
|
|
82
|
+
|
|
83
|
+
for i, entry in enumerate(albums):
|
|
84
|
+
artist, album_name, plays = entry["artist"], entry["album"], entry["plays"]
|
|
85
|
+
print(f" [{i+1:3d}/{len(albums)}] {artist} - {album_name} ({plays} plays) ... ", end="", flush=True)
|
|
86
|
+
|
|
87
|
+
track_uris = search_album_tracks(sp, artist, album_name)
|
|
88
|
+
if track_uris:
|
|
89
|
+
all_uris.extend(track_uris)
|
|
90
|
+
print(f"{len(track_uris)} tracks")
|
|
91
|
+
else:
|
|
92
|
+
missed.append(f"{artist} - {album_name}")
|
|
93
|
+
print("NOT FOUND")
|
|
94
|
+
|
|
95
|
+
time.sleep(0.1)
|
|
96
|
+
|
|
97
|
+
if dry_run:
|
|
98
|
+
print(f" [DRY RUN] Would create '{name}' with {len(all_uris)} tracks ({len(missed)} albums not found)")
|
|
99
|
+
return {"name": name, "tracks": len(all_uris), "missed": missed, "url": None}
|
|
100
|
+
|
|
101
|
+
playlist = sp.user_playlist_create(user_id, name, public=False, description=description)
|
|
102
|
+
playlist_url = playlist["external_urls"]["spotify"]
|
|
103
|
+
print(f" Created playlist: {playlist_url}")
|
|
104
|
+
|
|
105
|
+
for batch_start in range(0, len(all_uris), 100):
|
|
106
|
+
batch = all_uris[batch_start:batch_start + 100]
|
|
107
|
+
sp.playlist_add_items(playlist["id"], batch)
|
|
108
|
+
|
|
109
|
+
print(f" Added {len(all_uris)} tracks ({len(missed)} albums not found)")
|
|
110
|
+
return {"name": name, "tracks": len(all_uris), "missed": missed, "url": playlist_url}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def create_year_playlist(
|
|
114
|
+
year: str,
|
|
115
|
+
albums: list[dict],
|
|
116
|
+
dry_run: bool = False,
|
|
117
|
+
) -> dict:
|
|
118
|
+
"""Create a Spotify playlist for one year of top albums.
|
|
119
|
+
|
|
120
|
+
Thin wrapper around :func:`create_playlist_from_albums`.
|
|
121
|
+
"""
|
|
122
|
+
name = f"Last.fm Top 100 Albums — {year}"
|
|
123
|
+
description = f"Top 100 most-played albums of {year} from Last.fm, all tracks included."
|
|
124
|
+
result = create_playlist_from_albums(albums, name, description, dry_run=dry_run)
|
|
125
|
+
result["year"] = year
|
|
126
|
+
return result
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def create_all_playlists(
|
|
130
|
+
data_dir: str | Path = "data/albums",
|
|
131
|
+
dry_run: bool = False,
|
|
132
|
+
skip_years: set[str] | None = None,
|
|
133
|
+
) -> list[dict]:
|
|
134
|
+
"""Create Spotify playlists for every top100-YYYY.json file."""
|
|
135
|
+
data_dir = Path(data_dir)
|
|
136
|
+
skip_years = skip_years or set()
|
|
137
|
+
|
|
138
|
+
results = []
|
|
139
|
+
for f in sorted(data_dir.glob("top100-*.json")):
|
|
140
|
+
year = f.stem.split("-")[1]
|
|
141
|
+
if year in skip_years:
|
|
142
|
+
print(f"\n Skipping {year} (already created)")
|
|
143
|
+
continue
|
|
144
|
+
albums = json.loads(f.read_text())
|
|
145
|
+
print(f"\n{'='*60}")
|
|
146
|
+
print(f" {year} — {len(albums)} albums")
|
|
147
|
+
print(f"{'='*60}")
|
|
148
|
+
result = create_year_playlist(year, albums, dry_run=dry_run)
|
|
149
|
+
results.append(result)
|
|
150
|
+
|
|
151
|
+
# Summary
|
|
152
|
+
print(f"\n{'='*60}")
|
|
153
|
+
print(" SUMMARY")
|
|
154
|
+
print(f"{'='*60}")
|
|
155
|
+
total_tracks = 0
|
|
156
|
+
total_missed = 0
|
|
157
|
+
for r in results:
|
|
158
|
+
status = r["url"] or "DRY RUN"
|
|
159
|
+
print(f" {r['year']}: {r['tracks']} tracks, {len(r['missed'])} missed — {status}")
|
|
160
|
+
total_tracks += r["tracks"]
|
|
161
|
+
total_missed += len(r["missed"])
|
|
162
|
+
print(f"\n Total: {total_tracks} tracks, {total_missed} albums not found")
|
|
163
|
+
|
|
164
|
+
return results
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: scrobbles
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fetch, export, and visualize Last.fm listening data — plus create Spotify playlists from your top albums
|
|
5
|
+
Project-URL: Homepage, https://github.com/saforem2/scrobbles
|
|
6
|
+
Project-URL: Repository, https://github.com/saforem2/scrobbles
|
|
7
|
+
Project-URL: Issues, https://github.com/saforem2/scrobbles/issues
|
|
8
|
+
Author-email: Sam Foreman <saforem2@gmail.com>
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: audioscrobbler,last.fm,lastfm,music,scrobble,spotify
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Multimedia :: Sound/Audio
|
|
17
|
+
Requires-Python: >=3.12
|
|
18
|
+
Requires-Dist: pylast>=7.0.2
|
|
19
|
+
Requires-Dist: spotipy>=2.26.0
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# scrobbles
|
|
23
|
+
|
|
24
|
+
Fetch, export, and visualize [Last.fm](https://www.last.fm/) listening data — plus create Spotify playlists from your top albums.
|
|
25
|
+
|
|
26
|
+
## Setup
|
|
27
|
+
|
|
28
|
+
### Prerequisites
|
|
29
|
+
|
|
30
|
+
- Python 3.12+
|
|
31
|
+
- [uv](https://docs.astral.sh/uv/) (recommended) or pip
|
|
32
|
+
|
|
33
|
+
### Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install scrobbles
|
|
37
|
+
# or
|
|
38
|
+
uv add scrobbles
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
#### From source
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
git clone https://github.com/saforem2/scrobbles.git
|
|
45
|
+
cd lastfm
|
|
46
|
+
uv sync
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### Environment Variables
|
|
50
|
+
|
|
51
|
+
#### Last.fm
|
|
52
|
+
|
|
53
|
+
Get API credentials at <https://www.last.fm/api/account>.
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
export LASTFM_API_KEY="..."
|
|
57
|
+
export LASTFM_API_SECRET="..."
|
|
58
|
+
export LASTFM_USERNAME="..."
|
|
59
|
+
export LASTFM_PASSWORD="..."
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
#### Spotify (optional — only needed for playlist creation)
|
|
63
|
+
|
|
64
|
+
1. Create an app at <https://developer.spotify.com/dashboard>
|
|
65
|
+
2. Add `http://127.0.0.1:8888/callback` as a Redirect URI in your app settings
|
|
66
|
+
3. Export your credentials:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
export SPOTIFY_CLIENT_ID="..." # or SPOTIPY_CLIENT_ID
|
|
70
|
+
export SPOTIFY_CLIENT_SECRET="..." # or SPOTIPY_CLIENT_SECRET
|
|
71
|
+
export SPOTIPY_REDIRECT_URI="http://127.0.0.1:8888/callback"
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Either `SPOTIFY_*` or `SPOTIPY_*` naming works — the library maps them automatically.
|
|
75
|
+
|
|
76
|
+
## Usage
|
|
77
|
+
|
|
78
|
+
### CLI
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
# Via entry point (after install)
|
|
82
|
+
scrobbles top-albums overall --limit 25
|
|
83
|
+
scrobbles top-albums 2024
|
|
84
|
+
scrobbles dashboard
|
|
85
|
+
|
|
86
|
+
# Via main.py (development)
|
|
87
|
+
uv run python main.py top-albums overall --limit 25
|
|
88
|
+
uv run python main.py top-albums 2024
|
|
89
|
+
uv run python main.py top-albums last_month
|
|
90
|
+
|
|
91
|
+
# Export top albums to JSON
|
|
92
|
+
uv run python main.py dump-albums 2024 --limit 100
|
|
93
|
+
|
|
94
|
+
# Generate the HTML dashboard from existing JSON files
|
|
95
|
+
uv run python main.py dashboard
|
|
96
|
+
|
|
97
|
+
# Create Spotify playlists from all top100-YYYY.json files
|
|
98
|
+
uv run python main.py spotify-playlists --dry-run
|
|
99
|
+
uv run python main.py spotify-playlists --skip 2020 2021
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Python API
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
import scrobbles
|
|
106
|
+
|
|
107
|
+
# Recent tracks & now playing
|
|
108
|
+
scrobbles.get_recent_tracks("username", 10)
|
|
109
|
+
print(scrobbles.get_now_playing("username"))
|
|
110
|
+
|
|
111
|
+
# Top albums — predefined periods
|
|
112
|
+
scrobbles.print_top_albums("username", period="7day", limit=20)
|
|
113
|
+
|
|
114
|
+
# Top albums — arbitrary date ranges
|
|
115
|
+
scrobbles.print_top_albums("username", period="2024") # full year
|
|
116
|
+
scrobbles.print_top_albums("username", period="2024-06") # single month
|
|
117
|
+
scrobbles.print_top_albums("username", period="last_week")
|
|
118
|
+
|
|
119
|
+
# Export to JSON
|
|
120
|
+
scrobbles.dump_top_albums("username", period="2024", limit=100)
|
|
121
|
+
|
|
122
|
+
# Generate interactive HTML dashboard
|
|
123
|
+
from scrobbles.albums import build_dashboard
|
|
124
|
+
build_dashboard() # reads data/albums/top100-*.json → data/albums/index.html
|
|
125
|
+
|
|
126
|
+
# Spotify: create a playlist from any album list
|
|
127
|
+
from scrobbles.spotify import create_playlist_from_albums
|
|
128
|
+
albums = [{"artist": "Radiohead", "album": "OK Computer", "plays": 50}]
|
|
129
|
+
create_playlist_from_albums(albums, "My Playlist", dry_run=True)
|
|
130
|
+
|
|
131
|
+
# Spotify: bulk-create yearly playlists
|
|
132
|
+
from scrobbles.spotify import create_all_playlists
|
|
133
|
+
create_all_playlists(dry_run=True)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Supported Period Strings
|
|
137
|
+
|
|
138
|
+
| Period | Description |
|
|
139
|
+
|---|---|
|
|
140
|
+
| `overall` | All time |
|
|
141
|
+
| `7day`, `1month`, `3month`, `6month`, `12month` | Rolling windows |
|
|
142
|
+
| `today`, `yesterday`, `last_week`, `last_month`, `last_year` | Calendar-relative |
|
|
143
|
+
| `2024` | Full calendar year |
|
|
144
|
+
| `2024-06` | Single month |
|
|
145
|
+
| `2024-06-15` | Single day |
|
|
146
|
+
|
|
147
|
+
## Project Structure
|
|
148
|
+
|
|
149
|
+
```
|
|
150
|
+
lastfm/
|
|
151
|
+
├── src/scrobbles/
|
|
152
|
+
│ ├── __init__.py # Network setup, track utils, re-exports
|
|
153
|
+
│ ├── albums.py # Top albums: fetch, format, export, dashboard
|
|
154
|
+
│ ├── cli.py # CLI entry point
|
|
155
|
+
│ └── spotify.py # Spotify playlist creation
|
|
156
|
+
├── data/albums/ # Generated JSON + HTML dashboard
|
|
157
|
+
│ ├── top100-YYYY.json
|
|
158
|
+
│ └── index.html
|
|
159
|
+
├── main.py # Thin shim (calls scrobbles.cli:main)
|
|
160
|
+
├── pyproject.toml
|
|
161
|
+
└── README.md
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## Publishing
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
# Bump version
|
|
168
|
+
uv version --bump patch
|
|
169
|
+
|
|
170
|
+
# Build
|
|
171
|
+
uv build
|
|
172
|
+
|
|
173
|
+
# Publish to PyPI
|
|
174
|
+
uv publish
|
|
175
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
scrobbles/__init__.py,sha256=9h8uGXoGsIGBZqID8be9xuo7LxN0HHn1sWkcKh48Ma0,2232
|
|
2
|
+
scrobbles/albums.py,sha256=OUbru-be9OqD96FnS0v2nR0OvdLiWGq7DGgyL8fl324,16515
|
|
3
|
+
scrobbles/cli.py,sha256=rGEtr52obYI0QdQpZKwyxFlwFG29lcrrD7vNeXSjhO0,2727
|
|
4
|
+
scrobbles/spotify.py,sha256=BYAS1CPwO1BmhSW4Hhj6A49Yv9jz8VbtRJRISDBoEeg,5619
|
|
5
|
+
scrobbles-0.1.0.dist-info/METADATA,sha256=q51NtQBohpXXI5tytrfLbhO5m1mHOlZMoAj6xC_HtAY,4834
|
|
6
|
+
scrobbles-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
7
|
+
scrobbles-0.1.0.dist-info/entry_points.txt,sha256=Sr4FPiEuyIWpA43jS0O4hUbosF3Q7S3bpN8ovoSbPjY,49
|
|
8
|
+
scrobbles-0.1.0.dist-info/licenses/LICENSE,sha256=XdTXLjEKBNTBqjyjVWs1MIQBryn4Fq5lPvzMMW9biKo,1068
|
|
9
|
+
scrobbles-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sam Foreman
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|