Created
February 23, 2010 08:48
-
-
Save lukec/312009 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# This code uses the CKAN API and the GoogleChart API to generate an image showing the top ministries by # of packages. | |
# Example: http://chart.apis.google.com/chart?cht=bhg&chs=600x300&chco=FF0000,008000,0000FF,FFFF00,800080&chdl=Natural+Resources+Canada%7CTreasury+Board+Secretariat%7CEngineering+Services&chd=t:100%7C33.3%7C33.3 | |
use strict; | |
use warnings; | |
use JSON qw/decode_json/; | |
use LWP::UserAgent; | |
use URI::GoogleChart; | |
my $MAX_MINISTRIES = 5; | |
# Get the list of all packages | |
my $base_url = 'http://ca.ckan.net/api/rest'; | |
my $packages = get_json("$base_url/package"); | |
# Find out how many packages each ministry has | |
my %pkg_count; | |
for my $pkg_name (@$packages) { | |
warn "Fetching $pkg_name\n"; | |
my $pkg = get_json("$base_url/package/$pkg_name"); | |
if (my $ministry = $pkg->{extras}{Ministry}) { | |
$pkg_count{$ministry}++; | |
} | |
} | |
# Sort the ministries by number of packages | |
my @ministries = sort { $pkg_count{$b} <=> $pkg_count{$a} } keys %pkg_count; | |
# Create a GoogleChart with the data | |
my @data; | |
my @x_labels; | |
my $max = 1; | |
for my $ministry (splice @ministries, 0, $MAX_MINISTRIES) { | |
my $count = $pkg_count{$ministry}; | |
$max = $count if $max < $count; | |
push @data, [$count]; | |
push @x_labels, $ministry; | |
} | |
print URI::GoogleChart->new("vertical-grouped-bars", 600, 300, | |
data => \@data, | |
label => \@x_labels, | |
chxt => 'y', | |
chxr => "0,0,$max,1", color => [qw/red green blue yellow purple/], | |
), "\n"; | |
exit; | |
# Make a HTTP Request to the CKAN API, as documented here: http://ca.ckan.net/api | |
sub get_json { | |
my $url = shift; | |
my $ua = LWP::UserAgent->new; | |
$ua->default_header(Authorization => '53c7b7cb-b771-45f0-86f3-e7613e760ddb'); | |
my $resp = $ua->get($url); | |
warn "Could not fetch $url: ", $resp->status_line, "\n" | |
if $resp->code != 200; | |
return decode_json($resp->content); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment