Skip to content

Instantly share code, notes, and snippets.

@hoehrmann
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hoehrmann/09bd7caf977697583d24 to your computer and use it in GitHub Desktop.
Save hoehrmann/09bd7caf977697583d24 to your computer and use it in GitHub Desktop.
For a given last.fm user, retrieves all their top tracks, and for each track, all tags for the track, and then prints out the 7 most-used tags for each track.
#!/usr/bin/env perl -w
use strict;
use warnings;
use JSON;
use LWP::UserAgent;
use URI;
use URI::QueryParam;
my $ua = LWP::UserAgent->new;
my $base = 'http://ws.audioscrobbler.com/2.0/';
my %params = (
'method' => 'user.gettoptracks',
'page' => 1,
'limit' => 10,
'format' => 'json',
'user' => '...',
'api_key' => '...',
);
my $url = URI->new($base);
$url->query_form(%params);
$|++;
while (1) {
my $res = $ua->get($url);
sleep 1;
my $d = JSON->new->decode($res->decoded_content);
for my $track (@{ $d->{toptracks}{track} }) {
warn sprintf "# Tags for %s -- %s\n", $track->{artist}{name}, $track->{name};
my %params2 = (
'method' => 'track.gettoptags',
'format' => 'json',
'artist' => $track->{artist}{name},
'track' => $track->{name},
'api_key' => '...',
);
my $url2 = URI->new($base);
$url2->query_form(%params2);
my $res2 = $ua->get($url2);
sleep 1;
my $d2 = JSON->new->decode($res2->decoded_content);
next unless ref($d2->{toptags}{tag}) eq 'ARRAY';
for my $tag (@{ $d2->{toptags}{tag} }[0 .. 6]) {
next unless defined $tag;
printf "%s\n", $tag->{name};
}
}
last if $d->{toptracks}{'@attr'}{'page'} == $d->{toptracks}{'@attr'}{'totalPages'};
$url->query_param('page', $url->query_param('page') + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment