-
Notifications
You must be signed in to change notification settings - Fork 0
/
wdtree
executable file
·209 lines (166 loc) · 4.69 KB
/
wdtree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env perl
use v5.14;
use Pod::Usage;
use Getopt::Long;
use Catmandu -all;
use HTTP::Tiny;
use RDF::Trine::Iterator::JSONHandler;
use Graph;
my %opt;
my ($input);
# get options
{
Getopt::Long::Configure('bundling');
GetOptions(\%opt,
'language|g|l=s',
'root|Q=s',
'property|prop|p|P=s',
'help|h|?',
'from|f=s',
'size|s=s',
'field=s',
'dry',
) or pod2usage(2);
pod2usage(1) if $opt{help};
# root item as first argument
if ( @ARGV and $ARGV[0] =~ /^Q?(\d+)(\.[a-z]+)?$/i) {
$opt{root} = "Q$1";
shift @ARGV;
}
# input file as argument
if ( @ARGV ) {
$opt{from} = shift @ARGV;
}
# default values
$opt{language} ||= 'en';
$opt{property} ||= 'P279'; # subclass of
$opt{size} ||= 'P31';
}
# validate and normalize options
{
$opt{root} or pod2usage("missing root item");
$opt{root} =~ /^Q?(\d+)$/i or pod2usage("invalid root item");
$opt{root} = "Q$1";
foreach (qw(property size field)) {
if (defined $opt{$_}) {
$opt{$_} =~ /^P?(\d+)$/i or pod2usage("invalid $_");
$opt{$_} = "P$1";
}
}
}
my $root = $opt{root};
if ($opt{from}) {
open($input, '<', $opt{from}) or die "Failed to open $opt{from}\n";
} else {
my $property = $opt{property};
my $size = $opt{size};
my $vars = "?item ?itemLabel ?broader ?parents ?size ?sites";
my $sparql = <<SPARQL;
{
{
SELECT ?item (count(distinct ?parent)-1 as ?parents) {
?item wdt:$property* wd:$root
OPTIONAL { ?item wdt:$property ?parent }
} GROUP BY ?item
}
{
SELECT ?item (count(distinct ?element) as ?size) {
?item wdt:$property* wd:$root
OPTIONAL { ?element wdt:$size ?item }
} GROUP BY ?item
}
{
SELECT ?item (count(distinct ?site) as ?sites) {
?item wdt:$property* wd:$root
OPTIONAL { ?site schema:about ?item }
} GROUP BY ?item
}
OPTIONAL { ?item wdt:$property ?broader }
SPARQL
if ($opt{field}) {
$sparql .= "OPTIONAL { ?item wdt:$opt{field} ?field }";
$vars .= " ?field";
}
$sparql = $sparql . <<SPARQL;
SERVICE wikibase:label {
bd:serviceParam wikibase:language "$opt{language}" .
}
}
SPARQL
$sparql = "SELECT $vars $sparql";
$sparql =~ s/\n/ /mg;
my $cmd = "wdq -i -g$opt{language} -lid '$sparql'";
#my $cmd = "wdq -i '$sparql'";
open($input, "$cmd |") ## no critic
or die "wdq execution failed!\n";
}
sub wikidata_query {
my $sparql = shift;
say($sparql) && exit if $opt{dry};
my $query = { query => $sparql, format => 'json' };
my $http = HTTP::Tiny->new(timeout => 30);
my $url = 'https://query.wikidata.org/bigdata/namespace/wdq/sparql?'
. '?' . $http->www_form_urlencode($query);
my $res = $http->get($url);
die "SPARQL query failed\n" unless $res->{success};
my $rdf = RDF::Trine::Iterator::JSONHandler->new->parse($res->{content});
while ( my $row = $rdf->next ) {
...
}
}
# parse SPARQL query result
my %items;
my $g = Graph->new;
importer( 'JSON', fh => $input )->each(sub{
my $id = $_[0]->{item};
$_[0]->{label} = delete $_[0]->{itemLabel};
$items{$id} = $_[0];
warn "$id is no item!\n" if $id !~ /^Q\d+$/;
if ( $_[0]->{broader} ) {
if ( $id eq $_[0]->{broader} ) {
warn "$id is subclass of itself!\n"
} else {
$g->add_edge( $_[0]->{item}, $_[0]->{broader} );
}
}
});
unless ($items{$root}) {
die "Wikidata item $root not found!\n";
}
# emit classification in CSV format
use Text::CSV;
use autodie;
my $csv = Text::CSV->new({ binary => 1, sep_char => ',', quote_char => '"', eol => "\n" });
open my $csvfile, '>', "$root.csv";
binmode $csvfile, ':encoding(UTF-8)';
my @fields = qw(level item label parents size sites);
push @fields, 'field' if $opt{field};
sub make_tree {
my ($node, $level) = @_;
my $item = $items{$node};
my $recurse = 1;
if ( defined $item->{level} ) {
$item->{level} = '=' x $level;
$recurse = 0;
} else {
$item->{level} = '-' x $level;
}
# TODO: qualifier
$csv->print( $csvfile, [ map { $item->{$_} } @fields ] );
if ( $recurse ) {
my @children = map { $_->[0] } $g->edges_to($node);
foreach (sort { substr($a,1) cmp substr($b,1) } @children) {
make_tree($_, $level+1);
}
}
}
$csv->print( $csvfile, \@fields );
make_tree($root);
__END__
=head1 NAME
wdtree - extract tree structures from Wikidata
=head1 USAGE
wdtree [options] [ [Qitem] | file.json ]
For instance C<wdtree Q6423319> extracts a classification of Knowledge
Organization Systems (Q6423319) and its subclasses (P279).
=cut