| •1 |
#!/usr/bin/perl |
| 2 |
use v5.14; |
| 3 |
|
| 4 |
use Getopt::Long; |
| 5 |
use Scalar::Util qw(blessed); |
| 6 |
use Encode qw(decode_utf8 encode_utf8); |
| 7 |
use JSON; |
| 8 |
|
| 9 |
our $VERSION = '0.4.4'; |
| 10 |
|
| 11 |
# Assume everything outside is UTF-8 |
| 12 |
binmode( STDIN, ":encoding(UTF-8)" ); |
| 13 |
binmode( STDOUT, ":encoding(UTF-8)" ); |
| 14 |
binmode( STDERR, ":encoding(UTF-8)" ); |
| 15 |
@ARGV = map { decode_utf8($_) } @ARGV; |
| 16 |
|
| 17 |
# get command line options |
| 18 |
my %OPT; |
| 19 |
Getopt::Long::Configure('bundling'); |
| 20 |
GetOptions( |
| 21 |
\%OPT, |
| 22 |
'help|h|?', 'version|V', 'man', 'ontology', |
| 23 |
'api=s', |
| 24 |
'format|f=s', |
| 25 |
'query|q=s', |
| 26 |
'ids|i!', |
| 27 |
'language|g=s', |
| 28 |
'label|l=s@', |
| 29 |
'description|d=s@', |
| 30 |
'text|t=s@', |
| 31 |
'enumerate|e!', |
| 32 |
'color|C!', |
| 33 |
'monochrome|M', |
| 34 |
'count|c=s', |
| 35 |
'header!', 'H!', |
| 36 |
'no-execute|n!', |
| 37 |
'no-mediawiki|m!', |
| 38 |
'N!', |
| 39 |
'ignore!', |
| 40 |
'limit=i', '1!', '2!', '3!', '4!', '5!', '6!', '7!', '8!', '9!', |
| 41 |
'default-prefixes!', |
| 42 |
'response=s', # not documented, does not respect --limit |
| 43 |
'export=s', |
| 44 |
'force!', |
| 45 |
) or exit 1; |
| 46 |
|
| 47 |
# use color by default if output is terminal |
| 48 |
$OPT{color} = 0 if $OPT{monochrome}; |
| 49 |
$OPT{color_stderr} = $OPT{color} // -t STDERR; ## no critic |
| 50 |
$OPT{color} //= -t STDOUT; ## no critic |
| 51 |
|
| 52 |
my %COLORS = ( |
| 53 |
t => "\e[1;39m", # title : bold |
| 54 |
v => "\e[0;32m", # value: green |
| 55 |
n => "\e[0;34m", # name: blue |
| 56 |
i => "\e[0;33m", # identifier: yellow |
| 57 |
e => "\e[1;31m", # error: bold red |
| 58 |
); |
| 59 |
|
| 60 |
sub cBold { |
| 61 |
$OPT{color} ? "$COLORS{t}$_[0]\e[0m" : $_[0]; |
| 62 |
} |
| 63 |
|
| 64 |
sub cValue { |
| 65 |
$OPT{color} ? "$COLORS{v}$_[0]\e[0m" : $_[0]; |
| 66 |
} |
| 67 |
|
| 68 |
sub cName { |
| 69 |
$OPT{color} ? "$COLORS{n}$_[0]\e[0m" : $_[0]; |
| 70 |
} |
| 71 |
|
| 72 |
sub cIdentifier { |
| 73 |
$OPT{color} ? "$COLORS{i}$_[0]\e[0m" : $_[0]; |
| 74 |
} |
| 75 |
|
| 76 |
sub warning { |
| 77 |
say STDERR $OPT{color_stderr} ? "$COLORS{e}$_[0]\e[0m" : $_[0]; |
| 78 |
} |
| 79 |
|
| 80 |
my %NAMESPACES = ( |
| 81 |
|
| 82 |
# standard ontologies |
| 83 |
rdf => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', |
| 84 |
xsd => 'http://www.w3.org/2001/XMLSchema#', |
| 85 |
rdfs => 'http://www.w3.org/2000/01/rdf-schema#', |
| 86 |
owl => 'http://www.w3.org/2002/07/owl#', |
| 87 |
skos => 'http://www.w3.org/2004/02/skos/core#', |
| 88 |
schema => 'http://schema.org/', |
| 89 |
geo => 'http://www.opengis.net/ont/geosparql#', |
| 90 |
prov => 'http://www.w3.org/ns/prov#', |
| 91 |
|
| 92 |
# Wikibase ontology |
| 93 |
wikibase => 'http://wikiba.se/ontology#', |
| 94 |
wd => 'http://www.wikidata.org/entity/', |
| 95 |
wdt => 'http://www.wikidata.org/prop/direct/', |
| 96 |
wds => 'http://www.wikidata.org/entity/statement/', |
| 97 |
p => 'http://www.wikidata.org/prop/', |
| 98 |
wdref => 'http://www.wikidata.org/reference/', |
| 99 |
wdv => 'http://www.wikidata.org/value/', |
| 100 |
ps => 'http://www.wikidata.org/prop/statement/', |
| 101 |
psv => 'http://www.wikidata.org/prop/statement/value/', |
| 102 |
pq => 'http://www.wikidata.org/prop/qualifier/', |
| 103 |
pqv => 'http://www.wikidata.org/prop/qualifier/value/', |
| 104 |
pr => 'http://www.wikidata.org/prop/reference/', |
| 105 |
prv => 'http://www.wikidata.org/prop/reference/value/', |
| 106 |
wdno => 'http://www.wikidata.org/prop/novalue/', |
| 107 |
|
| 108 |
# blazegraph SPARQL extensions |
| 109 |
hint => 'http://www.bigdata.com/queryHints#', |
| 110 |
bd => 'http://www.bigdata.com/rdf#', |
| 111 |
bds => 'http://www.bigdata.com/rdf/search#', |
| 112 |
fts => 'http://www.bigdata.com/rdf/fts#', |
| 113 |
|
| 114 |
# not used in Wikidata Query Service |
| 115 |
wdata => 'http://www.wikidata.org/wiki/Special:EntityData/', |
| 116 |
cc => 'http://creativecommons.org/ns#', |
| 117 |
); |
| 118 |
|
| 119 |
my $LANGUAGE_PATTERN = qr{^([a-z]+(-[a-zA-Z0-9]+)*)$}; |
| 120 |
|
| 121 |
my $ENTITY_PATTERN = qr{^ |
| 122 |
(https?://www\.wikidata\.org/ |
| 123 |
(wiki|entity|wiki/Special:EntityData)/)? |
| 124 |
(?<id>(q|(Property:)?p)\d+) |
| 125 |
$}ix; |
| 126 |
|
| 127 |
my $WIKIDATA_ID_PATTERN = qr{^ |
| 128 |
http://www\.wikidata\.org/ |
| 129 |
( entity (/statement)? | reference | value | |
| 130 |
prop (/(statement|qualifier|reference)/value)?) |
| 131 |
/(?<id>.+) |
| 132 |
$}x; |
| 133 |
|
| 134 |
my $SITELINK_PATTERN = qr{^ |
| 135 |
https?:// |
| 136 |
(?<base> |
| 137 |
( [^.]+. ( wikipedia | wiktionary | wikibooks | wikiquote | |
| 138 |
wikisource | wikinews | wikiversity | wikivoyage ) |
| 139 |
| ( commons | species )\.wikimedia |
| 140 |
)\.org) |
| 141 |
/wiki/ |
| 142 |
(?<title>.+) |
| 143 |
}x; |
| 144 |
|
| 145 |
sub pod_text { |
| 146 |
require Pod::Usage; |
| 147 |
my $text; |
| 148 |
open my $out, '>', \$text; |
| 149 |
Pod::Usage::pod2usage( |
| 150 |
-exit => 'NOEXIT', |
| 151 |
-output => $out, |
| 152 |
-verbose => 99, |
| 153 |
indent => 2, |
| 154 |
@_ |
| 155 |
); |
| 156 |
$text =~ s/^(.[^\s].+:)$/cBold($1)/mge; # headers |
| 157 |
$text =~ s/("[^"\n]+")/cValue($1)/mge; # strings |
| 158 |
$text =~ s/(<[^->\n][^>\n]+>)/cIdentifier($1)/mge; # URLs |
| 159 |
$text; |
| 160 |
} |
| 161 |
|
| 162 |
# help mode |
| 163 |
if ( $OPT{help} ) { |
| 164 |
@ARGV = qw(help); |
| 165 |
} |
| 166 |
elsif ( $OPT{version} ) { |
| 167 |
@ARGV = qw(help version); |
| 168 |
} |
| 169 |
elsif ( $OPT{namespaces} ) { |
| 170 |
warning("--namespaces is deprecated. Use 'wdq help prefixes' instead!"); |
| 171 |
@ARGV = qw(help prefixes); |
| 172 |
} |
| 173 |
elsif ( $OPT{ontology} ) { |
| 174 |
warning("--ontology is deprecated. Use 'wdq help ontology' instead!"); |
| 175 |
@ARGV = qw(help ontology); |
| 176 |
} |
| 177 |
|
| 178 |
if ( @ARGV and $ARGV[0] eq 'help' ) { |
| 179 |
shift @ARGV; |
| 180 |
my $topic = lc( shift @ARGV ); |
| 181 |
|
| 182 |
my $help; |
| 183 |
if ( $topic =~ /^ver(sion)?$/ ) { |
| 184 |
$help = cBold('wdq') . " $VERSION\n"; |
| 185 |
} |
| 186 |
elsif ( $topic =~ /^pref?(ix(es)?)?$/ ) { |
| 187 |
$help = join( "\n", |
| 188 |
map { sprintf "%8s: %s", $_, cIdentifier( $NAMESPACES{$_} ); } |
| 189 |
sort keys %NAMESPACES ) |
| 190 |
. "\n"; |
| 191 |
$help =~ s/^([^:]+):/cName($1).":"/mge; |
| 192 |
} |
| 193 |
elsif ( $topic =~ /^out(put)?$/ ) { |
| 194 |
$help = pod_text( -sections => ['OUTPUT'] ); |
| 195 |
$help =~ |
| 196 |
s/( (name|value|identifier|title|error))/$COLORS{substr $2, 0,1}.$1."\e[0m"/mge |
| 197 |
if $OPT{color}; |
| 198 |
} |
| 199 |
elsif ( $topic eq 'pretty' ) { |
| 200 |
$help = pod_text( -sections => ['OUTPUT/Pretty'] ); |
| 201 |
$help =~ |
| 202 |
s/( (name|value|identifier|title|error))/$COLORS{substr $2, 0,1}.$1."\e[0m"/mge |
| 203 |
if $OPT{color}; |
| 204 |
} |
| 205 |
elsif ( $topic =~ /^formats?$/ ) { |
| 206 |
$help = pod_text( -sections => ['OUTPUT/Formats'] ); |
| 207 |
} |
| 208 |
elsif ( $topic =~ /^modes?$/ ) { |
| 209 |
$help = pod_text( -sections => ['MODES'] ); |
| 210 |
} |
| 211 |
elsif ( $topic =~ /^exp?(ort)?$/ ) { |
| 212 |
$help = pod_text( -sections => ['OUTPUT/Export'] ); |
| 213 |
} |
| 214 |
elsif ( $topic =~ /^ont(ology)?$/ ) { |
| 215 |
$help = pod_text( -sections => ['WIKIDATA ONTOLOGY'] ); |
| 216 |
$help =~ s/^.*Wikidata Ontology:.*\n//; |
| 217 |
$help =~ s/^( | )//mg; |
| 218 |
$help =~ s/^([a-z]+)/cBold($1)/mgei; |
| 219 |
$help =~ s/ ([A-Z][A-Za-z]+)/" ".cBold($1)/mge; |
| 220 |
$help =~ s/ ([a-z]+:([a-zA-Z_]+)?|[a-z][a-zA-Z]+)/" ".cName($1)/mge; |
| 221 |
$help =~ s/(@[a-z_]+)/cIdentifier($1)/mge; |
| 222 |
} |
| 223 |
elsif ( $topic =~ /^opt(ions?)?$/ ) { |
| 224 |
$help = pod_text( -sections => ['OPTIONS'] ); |
| 225 |
$help =~ s/^( *--?[^ ]+( [^ ].*)?)$/cName($1)/mge; # options |
| 226 |
$help =~ s/^\n//gm; # remove empty lines |
| 227 |
} |
| 228 |
else { |
| 229 |
$help = pod_text( |
| 230 |
-msg => 'wdq' . ' [ ' |
| 231 |
. join( ' ] [ ', |
| 232 |
cName('MODE'), cName('OPTIONS'), |
| 233 |
cName('REQUEST') . ' | ' . cName('< REQUEST_FILE') ) |
| 234 |
. " ]\n", |
| 235 |
-sections => ['SYNOPSIS'], |
| 236 |
); |
| 237 |
$help =~ s/\n\n -/\n -/gm; |
| 238 |
$help =~ s/^ / /mg; |
| 239 |
} |
| 240 |
print $help; |
| 241 |
exit; |
| 242 |
} |
| 243 |
|
| 244 |
if ( $OPT{man} ) { |
| 245 |
my $module = $OPT{color} ? 'Pod::Text::Color' : 'Pod::Text'; |
| 246 |
|
| 247 |
# may fail if pure script installed by hand |
| 248 |
eval "require $module; require App::wdq"; ## no critic |
| 249 |
$module->new->parse_from_file( $INC{'App/wdq.pm'} // $0 ); |
| 250 |
exit; |
| 251 |
} |
| 252 |
|
| 253 |
# default SPARQL endpoint |
| 254 |
$OPT{api} //= 'https://query.wikidata.org/bigdata/namespace/wdq/sparql'; |
| 255 |
|
| 256 |
# add default prefixes by default |
| 257 |
$OPT{'default-prefixes'} //= 1; |
| 258 |
|
| 259 |
# include header in output |
| 260 |
$OPT{header} //= $OPT{H} ? 0 : 1; |
| 261 |
|
| 262 |
# limit given as single digit option |
| 263 |
foreach ( grep { $OPT{$_} } 1 .. 9 ) { |
| 264 |
$OPT{limit} = $_ if !$OPT{limit} or $OPT{limit} > $_; |
| 265 |
} |
| 266 |
|
| 267 |
# validate language and set default value if missing |
| 268 |
$OPT{language} //= do { my $l = $ENV{LANG} // 'en'; $l =~ s/_.*//; $l }; |
| 269 |
$OPT{language} = lc( $OPT{language} ); |
| 270 |
if ( grep { $_ !~ $LANGUAGE_PATTERN } split ",", $OPT{language} ) { |
| 271 |
warning("invalid language(s): $OPT{language}"); |
| 272 |
exit 1; |
| 273 |
} |
| 274 |
|
| 275 |
# disable all requests |
| 276 |
if ( $OPT{N} ) { |
| 277 |
$OPT{'no-mediawiki'} = 1; |
| 278 |
$OPT{'no-execute'} = 1; |
| 279 |
} |
| 280 |
|
| 281 |
my $MODE = !@ARGV ? 'query' : do { |
| 282 |
my $arg = $ARGV[0]; |
| 283 |
$arg =~ s/^\s*|\s*$//g; |
| 284 |
if ( $arg =~ /^(query|lookup|p?search)$/ ) { |
| 285 |
lc( shift @ARGV ); |
| 286 |
} |
| 287 |
elsif ( $arg =~ $ENTITY_PATTERN or $arg =~ $SITELINK_PATTERN ) { |
| 288 |
'lookup'; |
| 289 |
} |
| 290 |
else { |
| 291 |
my $guess = () = $arg =~ /[a-z]+:[^\s]/gi; |
| 292 |
$guess += () = $arg =~ /<[^>]+>/g; |
| 293 |
$guess += () = $arg =~ /[?\$][^\s]/g; |
| 294 |
if ( $guess > 2 ) { |
| 295 |
warning("ignoring additional command line argument") |
| 296 |
if $OPT{query} or @ARGV > 1; |
| 297 |
'query'; |
| 298 |
} |
| 299 |
else { |
| 300 |
'search'; |
| 301 |
} |
| 302 |
} |
| 303 |
}; |
| 304 |
|
| 305 |
# default output format |
| 306 |
if ( $OPT{format} =~ /{[^}]+}/ ) { |
| 307 |
$OPT{pretty} = $OPT{format}; |
| 308 |
$OPT{format} = 'text'; |
| 309 |
} |
| 310 |
else { |
| 311 |
$OPT{format} = |
| 312 |
lc( $OPT{format} // ( $MODE =~ /^p?search$/ ? 'text' : 'simple' ) ); |
| 313 |
if ( $OPT{format} eq 'text' ) { |
| 314 |
$OPT{pretty} //= |
| 315 |
$OPT{count} |
| 316 |
? "{count|style=v}" |
| 317 |
: "{id|style=i}{label|style=v|pre=: }" |
| 318 |
. "{alias|pre= (|post=)|style=v}" |
| 319 |
. "{description|length=78|pre=\n }"; |
| 320 |
$OPT{ids} //= 1; |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
# require only if actually needed |
| 325 |
require RDF::Query; |
| 326 |
|
| 327 |
# monkey-patch RDF::Query to keep minimum required version at Ubuntu 14.04 LTS |
| 328 |
require version; |
| 329 |
if ( version->parse($RDF::Query::VERSION) < version->parse('2.915_01') ) { |
| 330 |
require RDF::Query::Parser::SPARQL; |
| 331 |
*RDF::Query::Node::Resource::as_sparql = sub { |
| 332 |
my $self = shift; |
| 333 |
my $context = shift || {}; |
| 334 |
my $uri = $self->uri_value; |
| 335 |
my $ns = $context->{namespaces} || {}; |
| 336 |
my %ns = %$ns; |
| 337 |
foreach my $k ( keys %ns ) { |
| 338 |
no warnings 'uninitialized'; |
| 339 |
if ( $k eq '__DEFAULT__' ) { |
| 340 |
$k = ''; |
| 341 |
} |
| 342 |
my $v = $ns{$k}; |
| 343 |
if ( index( $uri, $v ) == 0 ) { |
| 344 |
my $local = substr( $uri, length($v) ); |
| 345 |
if ( $local =~ $RDF::Query::Parser::SPARQL::r_PN_LOCAL ) { |
| 346 |
my $qname = join( ':', $k, $local ); |
| 347 |
return $qname; |
| 348 |
} |
| 349 |
} |
| 350 |
} |
| 351 |
'<' . URI->new( encode_utf8( $self->uri_value ) )->canonical . '>'; |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
my $EXPORTER; |
| 356 |
if ( $OPT{export} || $OPT{format} eq 'export' ) { |
| 357 |
$EXPORTER = eval { |
| 358 |
require Catmandu; |
| 359 |
Catmandu->exporter( $OPT{export} // 'JSON', header => $OPT{header} ); |
| 360 |
}; |
| 361 |
if ($@) { |
| 362 |
warning("option export requires Perl module " |
| 363 |
. "Catmandu::Exporter::$OPT{export}" ); |
| 364 |
exit 1; |
| 365 |
} |
| 366 |
elsif ( $OPT{format} !~ /^(ldjson|simple)$/ ) { |
| 367 |
warning("option export overrides option format"); |
| 368 |
Catmandu->load(); |
| 369 |
} |
| 370 |
$OPT{format} = 'export'; |
| 371 |
} |
| 372 |
|
| 373 |
# output formats |
| 374 |
package App::wdq::Output { |
| 375 |
|
| 376 |
sub add { |
| 377 |
my ( $self, $row ) = @_; |
| 378 |
$self->{format}{row}->( $self, $row ); |
| 379 |
} |
| 380 |
|
| 381 |
sub end { |
| 382 |
my ($self) = @_; |
| 383 |
return unless $self->{format}{post}; |
| 384 |
$self->{format}{post}->($self); |
| 385 |
} |
| 386 |
|
| 387 |
sub print { |
| 388 |
my $self = shift; |
| 389 |
print { $self->{out} } @_; |
| 390 |
} |
| 391 |
|
| 392 |
sub say { |
| 393 |
my $self = shift; |
| 394 |
say { $self->{out} } @_; |
| 395 |
} |
| 396 |
} |
| 397 |
|
| 398 |
package App::wdq::Format { |
| 399 |
|
| 400 |
sub new { |
| 401 |
my $class = shift; |
| 402 |
bless {@_}, $class; |
| 403 |
} |
| 404 |
|
| 405 |
sub start { |
| 406 |
my ( $self, $vars, $out ) = @_; |
| 407 |
my $output = bless { format => $self, vars => $vars, out => $out }, |
| 408 |
'App::wdq::Output'; |
| 409 |
$self->{pre}->($output) if $self->{pre}; |
| 410 |
return $output; |
| 411 |
} |
| 412 |
} |
| 413 |
|
| 414 |
sub simple_node { |
| 415 |
if ( !blessed( $_[0] ) ) { |
| 416 |
''; |
| 417 |
} |
| 418 |
elsif ( $_[0]->is_resource ) { |
| 419 |
$_[0]->uri_value; |
| 420 |
} |
| 421 |
elsif ( $_[0]->is_literal ) { |
| 422 |
$_[0]->literal_value; |
| 423 |
} |
| 424 |
else { |
| 425 |
$_[0]->sse; |
| 426 |
} |
| 427 |
} |
| 428 |
|
| 429 |
sub simple_row { |
| 430 |
my ( $row, $vars ) = @_; |
| 431 |
my $simple = { |
| 432 |
map { $_ => simple_node( $row->{$_} ) } |
| 433 |
grep { defined $row->{$_} } @$vars |
| 434 |
}; |
| 435 |
|
| 436 |
# TODO: add language |
| 437 |
#if (blessed $row->{label} && $row->{label}->is_literal) { |
| 438 |
# $simple->{language} = $row->{label}->literal_value_language; |
| 439 |
#} |
| 440 |
$simple; |
| 441 |
} |
| 442 |
|
| 443 |
sub json { |
| 444 |
( state $JSON= JSON->new->canonical->allow_nonref )->encode( $_[0] ); |
| 445 |
} |
| 446 |
|
| 447 |
sub pretty_json { |
| 448 |
( state $JSON= JSON->new->pretty->canonical )->encode( $_[0] ); |
| 449 |
} |
| 450 |
|
| 451 |
sub xml { |
| 452 |
my $text = shift; |
| 453 |
$text =~ s/&/&/gm; |
| 454 |
$text =~ s/</</gm; |
| 455 |
$text =~ s/>/>/gm; |
| 456 |
$text; |
| 457 |
} |
| 458 |
|
| 459 |
sub xmlattr { |
| 460 |
my $text = xml(shift); |
| 461 |
$text =~ s/"/"/gm; |
| 462 |
$text; |
| 463 |
} |
| 464 |
|
| 465 |
sub expand_format_string { |
| 466 |
my ( $string, $vars ) = @_; |
| 467 |
|
| 468 |
$string =~ s!{\s*([^}]+)}! |
| 469 |
my @a = split /\|/, $1; |
| 470 |
my $s = $vars->{shift @a}; |
| 471 |
my %o = map { /([^=]+)(=(.*))?/s; ($1 => $3) } @a; |
| 472 |
pretty_variable( $s, \%o ); |
| 473 |
!eg; |
| 474 |
|
| 475 |
$string; |
| 476 |
} |
| 477 |
|
| 478 |
sub pretty_variable { |
| 479 |
my ( $value, $p ) = @_; |
| 480 |
|
| 481 |
if ( !defined $value or $value eq '' ) { |
| 482 |
$value = $p->{default} // return ''; |
| 483 |
} |
| 484 |
|
| 485 |
if ( defined $p->{length} ) { |
| 486 |
if ( length $value > $p->{length} ) { |
| 487 |
$value = substr( $value, 0, $p->{length} - 1 ) . "\x{2026}"; |
| 488 |
} |
| 489 |
elsif ( defined $p->{align} ) { |
| 490 |
my $f = $p->{length} . 's'; |
| 491 |
$value = sprintf( $p->{align} eq 'right' ? "%$f" : "%-$f", $value ); |
| 492 |
} |
| 493 |
} |
| 494 |
|
| 495 |
if ( $OPT{color} && $COLORS{ $p->{style} } ) { |
| 496 |
$value = $COLORS{ $p->{style} } . $value . "\e[0m"; |
| 497 |
} |
| 498 |
|
| 499 |
$value = $p->{pre} . $value if defined $p->{pre}; |
| 500 |
$value = $value . $p->{post} if defined $p->{post}; |
| 501 |
|
| 502 |
$value; |
| 503 |
} |
| 504 |
|
| 505 |
my %FORMATS = ( |
| 506 |
|
| 507 |
# SPARQL Query Results JSON |
| 508 |
json => App::wdq::Format->new( |
| 509 |
pre => sub { |
| 510 |
my $o = shift; |
| 511 |
$o->print( |
| 512 |
"{\n \"head\": {\n \"vars\": [", |
| 513 |
join( ", ", map { cName( json($_) ) } @{ $o->{vars} } ), |
| 514 |
"]\n },\n \"results\": {\n \"bindings\": [" |
| 515 |
); |
| 516 |
}, |
| 517 |
row => sub { |
| 518 |
my ( $o, $row ) = @_; |
| 519 |
$o->print( $o->{count}++ ? ", {\n" : " {\n" ); |
| 520 |
my $delim = 0; |
| 521 |
foreach my $v ( @{ $o->{vars} } ) { |
| 522 |
next unless defined $row->{$v}; |
| 523 |
$o->say(",") if $delim++; |
| 524 |
$o->print( " " . cName( json($v) ) . ": " ); |
| 525 |
my $node = $row->{$v}->as_hashref; |
| 526 |
$node->{'xml:lang'} = delete $node->{lang} if $node->{lang}; |
| 527 |
my $json = pretty_json($node); |
| 528 |
$json =~ s/^ / /mg; |
| 529 |
$json =~ s/}\n$/ }/; |
| 530 |
$json =~ |
| 531 |
s/^(\s+"[a-z:]+")\s*:(.*")(,)?$/"$1:".cValue($2).$3/mge; |
| 532 |
$o->print($json); |
| 533 |
} |
| 534 |
$o->print("\n }"); |
| 535 |
}, |
| 536 |
post => sub { |
| 537 |
$_[0]->print(" ]\n }\n}\n"); |
| 538 |
} |
| 539 |
), |
| 540 |
|
| 541 |
# SPARQL Query Results XML |
| 542 |
xml => App::wdq::Format->new( |
| 543 |
pre => sub { |
| 544 |
my $o = shift; |
| 545 |
$o->say('<?xml version="1.0"?>'); |
| 546 |
$o->say('<sparql xmlns="http://www.w3.org/2005/sparql-results#">'); |
| 547 |
$o->say(' <head>'); |
| 548 |
foreach ( @{ $o->{vars} } ) { |
| 549 |
my $name = cName( xmlattr($_) ); |
| 550 |
$o->say(" <variable name=\"$name\"/>"); |
| 551 |
} |
| 552 |
$o->say(' </head>'); |
| 553 |
$o->say(' <results>'); |
| 554 |
}, |
| 555 |
row => sub { |
| 556 |
my ( $o, $row ) = @_; |
| 557 |
$o->say(' <result>'); |
| 558 |
foreach ( @{ $o->{vars} } ) { |
| 559 |
my $node = $row->{$_} // next; |
| 560 |
my $name = cName( xmlattr($_) ); |
| 561 |
$o->say(" <binding name=\"$name\">"); |
| 562 |
if ( $node->is_blank ) { |
| 563 |
$o->say( |
| 564 |
" <bnode>" . xml( $node->value ) . '</node>' ); |
| 565 |
} |
| 566 |
elsif ( $node->is_resource ) { |
| 567 |
$o->say(" <uri>" |
| 568 |
. cIdentifier( xml( $node->uri_value ) ) |
| 569 |
. '</uri>' ); |
| 570 |
} |
| 571 |
else { |
| 572 |
my $literal = " <literal"; |
| 573 |
if ( $node->literal_value_language ) { |
| 574 |
$literal .= |
| 575 |
' xml:lang="' |
| 576 |
. cIdentifier( |
| 577 |
xmlattr( $node->literal_value_language ) ) |
| 578 |
. '"'; |
| 579 |
} |
| 580 |
elsif ( $node->literal_datatype ) { |
| 581 |
$literal .= |
| 582 |
' datatype="' |
| 583 |
. cIdentifier( xmlattr( $node->literal_datatype ) ) |
| 584 |
. '"'; |
| 585 |
} |
| 586 |
$o->say("$literal>" |
| 587 |
. cValue( xml( $node->literal_value ) ) |
| 588 |
. "</literal>" ); |
| 589 |
} |
| 590 |
$o->say(' </binding>'); |
| 591 |
} |
| 592 |
$o->say(' </result>'); |
| 593 |
}, |
| 594 |
post => sub { |
| 595 |
$_[0]->say(' </results>'); |
| 596 |
$_[0]->say('</sparql>'); |
| 597 |
} |
| 598 |
), |
| 599 |
|
| 600 |
# SPARQL TSV |
| 601 |
tsv => App::wdq::Format->new( |
| 602 |
pre => sub { |
| 603 |
my $o = shift; |
| 604 |
$o->say( join( "\t", map { "?$_" } @{ $o->{vars} } ) ); |
| 605 |
}, |
| 606 |
row => sub { |
| 607 |
my ( $o, $row ) = @_; |
| 608 |
$o->say( |
| 609 |
join "\t", |
| 610 |
map { blessed($_) ? $_->as_ntriples : '' } |
| 611 |
map { $row->{$_} } @{ $o->{vars} } |
| 612 |
); |
| 613 |
} |
| 614 |
), |
| 615 |
|
| 616 |
# SPARQL CSV |
| 617 |
csv => App::wdq::Format->new( |
| 618 |
pre => sub { |
| 619 |
my $o = shift; |
| 620 |
$o->say( join ',', map { cName($_) } @{ $o->{vars} } ) |
| 621 |
if $OPT{header}; |
| 622 |
}, |
| 623 |
row => sub { |
| 624 |
my ( $o, $row ) = @_; |
| 625 |
$o->say( |
| 626 |
join ',', |
| 627 |
map { |
| 628 |
my $s = simple_node( $row->{$_} ); |
| 629 |
if ( $s =~ /[",\x0A\x0D]/ ) { |
| 630 |
$s =~ s/"/""/g; |
| 631 |
$s = "\"$s\""; |
| 632 |
} |
| 633 |
cValue($s) |
| 634 |
} @{ $o->{vars} } |
| 635 |
); |
| 636 |
} |
| 637 |
), |
| 638 |
|
| 639 |
# simple JSON key-value structure |
| 640 |
simple => App::wdq::Format->new( |
| 641 |
pre => sub { |
| 642 |
my $o = shift; |
| 643 |
$o->{count} = 0; |
| 644 |
$o->print("[ "); |
| 645 |
}, |
| 646 |
row => sub { |
| 647 |
my ( $o, $row ) = @_; |
| 648 |
my $json = pretty_json( simple_row( $row, $o->{vars} ) ); |
| 649 |
chomp $json; |
| 650 |
$json =~ s/^\s+("[^"]+") : (".*")(,)?$/ |
| 651 |
' '.cName($1).': '.cValue($2).$3/mge; |
| 652 |
$o->print(",") if $o->{count}++; |
| 653 |
$o->print($json); |
| 654 |
}, |
| 655 |
post => sub { |
| 656 |
my $o = shift; |
| 657 |
$o->say( $o->{count} ? " ]" : "]" ); |
| 658 |
} |
| 659 |
), |
| 660 |
|
| 661 |
# simple line-delimited JSON key-value structure |
| 662 |
ldjson => App::wdq::Format->new( |
| 663 |
row => sub { |
| 664 |
my ( $o, $row ) = @_; |
| 665 |
$o->say( json( simple_row( $row, $o->{vars} ) ) ); |
| 666 |
} |
| 667 |
), |
| 668 |
|
| 669 |
# pipe to Catmandu exporter |
| 670 |
export => App::wdq::Format->new( |
| 671 |
pre => sub { |
| 672 |
$_[0]->{exporter} = $EXPORTER; |
| 673 |
}, |
| 674 |
row => sub { |
| 675 |
my ( $o, $row ) = @_; |
| 676 |
$o->{exporter}->add( simple_row( $row, $o->{vars} ) ); |
| 677 |
}, |
| 678 |
post => sub { |
| 679 |
$_[0]->{exporter}->commit; |
| 680 |
} |
| 681 |
), |
| 682 |
|
| 683 |
# format string |
| 684 |
text => App::wdq::Format->new( |
| 685 |
row => sub { |
| 686 |
my ( $o, $row ) = @_; |
| 687 |
$row = { map { $_ => simple_node( $row->{$_} ) } keys %$row }; |
| 688 |
$o->say( expand_format_string( $OPT{pretty}, $row ) ); |
| 689 |
} |
| 690 |
), |
| 691 |
); |
| 692 |
|
| 693 |
if ( $MODE =~ /^p?search$/ ) { |
| 694 |
$OPT{ids} //= 1; |
| 695 |
} |
| 696 |
|
| 697 |
my $format = $FORMATS{ $OPT{format} } // do { |
| 698 |
warning("unknown format: $OPT{format}"); |
| 699 |
exit 1; |
| 700 |
}; |
| 701 |
|
| 702 |
sub expand_query { |
| 703 |
my $query = shift; |
| 704 |
|
| 705 |
my $select = "*"; |
| 706 |
|
| 707 |
# TODO: only in query mode |
| 708 |
if ( $OPT{count} ) { |
| 709 |
fatal("cannot expand query with COUNT") if $query =~ /^\s*SELECT/i; |
| 710 |
$select = "(COUNT(DISTINCT ?$OPT{count}) AS ?count)"; |
| 711 |
} |
| 712 |
|
| 713 |
if ( $query =~ /^\s*{/m ) { |
| 714 |
$query = "SELECT $select WHERE $query"; |
| 715 |
} |
| 716 |
elsif ( $query !~ /^[^{]*SELECT/ ) { |
| 717 |
$query = "SELECT $select WHERE { $query }"; |
| 718 |
} |
| 719 |
|
| 720 |
# LIMIT and OFFSET are always last so we can safely use regexp here |
| 721 |
if ( $OPT{limit} ) { |
| 722 |
$query =~ s/\n*LIMIT\s+\d+(\s+OFFSET\s+\d+)?\s*$/$1/sm; |
| 723 |
$query .= "\nLIMIT $OPT{limit}"; |
| 724 |
} |
| 725 |
|
| 726 |
my %namespace; |
| 727 |
if ( $OPT{'default-prefixes'} ) { |
| 728 |
|
| 729 |
# Add PREFIX for actually used and known prefixes |
| 730 |
my $ps = join '|', keys %NAMESPACES; |
| 731 |
$namespace{$_} = $NAMESPACES{$_} for $query =~ /($ps):[^\/]/mg; |
| 732 |
} |
| 733 |
|
| 734 |
# TODO: only in query mode. |
| 735 |
# TODO: test this |
| 736 |
my %textvar; |
| 737 |
|
| 738 |
# allow repeated and/or comma/space separated argument |
| 739 |
foreach my $field (qw(label description text)) { |
| 740 |
$OPT{$field} = |
| 741 |
[ map { split /\s*,\s*|\s+/, $_ } @{ $OPT{$field} // [] } ]; |
| 742 |
} |
| 743 |
|
| 744 |
$textvar{$_}{label} = 1 for @{ $OPT{label} }; |
| 745 |
$textvar{$_}{description} = 1 for @{ $OPT{description} }; |
| 746 |
$textvar{$_}{label} = $textvar{$_}{description} = 1 for @{ $OPT{text} }; |
| 747 |
|
| 748 |
if (%textvar) { |
| 749 |
if ( $OPT{count} ) { |
| 750 |
warning("Option --text/label/description only slow down --count"); |
| 751 |
} |
| 752 |
my @services; |
| 753 |
foreach my $var ( sort keys %textvar ) { |
| 754 |
my $s = <<SPARQL; |
| 755 |
SERVICE wikibase:label { |
| 756 |
bd:serviceParam wikibase:language "$OPT{language}" . |
| 757 |
SPARQL |
| 758 |
|
| 759 |
if ( $textvar{$var}{label} ) { |
| 760 |
my $label = $var eq 'id' ? 'label' : $var . 'Label'; |
| 761 |
$s .= " ?$var rdfs:label ?$label .\n"; |
| 762 |
} |
| 763 |
if ( $textvar{$var}{description} ) { |
| 764 |
my $descr = $var eq 'id' ? 'description' : $var . 'Description'; |
| 765 |
$s .= " ?$var schema:description ?$descr .\n"; |
| 766 |
} |
| 767 |
push @services, "$s }"; |
| 768 |
} |
| 769 |
|
| 770 |
my $service = join "\n", @services; |
| 771 |
$query =~ s/}([^}]*)$/$service}\1/m; |
| 772 |
|
| 773 |
$namespace{$_} = $NAMESPACES{$_} for qw(bd rdfs schema wikibase); |
| 774 |
} |
| 775 |
|
| 776 |
my @prefixes = map { "PREFIX $_: <$namespace{$_}>" } sort keys %namespace; |
| 777 |
$query = join "\n", @prefixes, $query; |
| 778 |
|
| 779 |
my $sparql = RDF::Query->new($query); |
| 780 |
if ( !$sparql ) { |
| 781 |
if ( $OPT{'force'} ) { |
| 782 |
warning("SPARQL query seems invalid"); |
| 783 |
} |
| 784 |
else { |
| 785 |
warning("invalid SPARQL query"); |
| 786 |
exit 1; |
| 787 |
} |
| 788 |
} |
| 789 |
else { |
| 790 |
$query = $sparql->as_sparql; |
| 791 |
$query =~ s/^\s*{}\s*$//mg; # BUG IN RDF::Query |
| 792 |
$query =~ s/\n$//mg; |
| 793 |
$query =~ s/LANG\(LANG\(\?/LANGMATCHES(LANG(?/mg; # BUG in RDF::Query |
| 794 |
$query =~ s/\t/ /mg; |
| 795 |
} |
| 796 |
|
| 797 |
if ( $OPT{'no-execute'} ) { |
| 798 |
say $query; |
| 799 |
return; |
| 800 |
} |
| 801 |
|
| 802 |
return $sparql |
| 803 |
? ( $query, [ map { $_->name } @{ $sparql->parsed->{variables} } ] ) |
| 804 |
: ($query); |
| 805 |
} |
| 806 |
|
| 807 |
sub http_get { |
| 808 |
my ( $url, %query ) = @_; |
| 809 |
|
| 810 |
if ( $OPT{response} ) { |
| 811 |
local ( @ARGV, $/ ) = $OPT{response}; |
| 812 |
return <>; |
| 813 |
} |
| 814 |
|
| 815 |
require HTTP::Tiny; |
| 816 |
my $http = HTTP::Tiny->new( |
| 817 |
default_headers => { agent => "wdq/$VERSION" }, |
| 818 |
timeout => 30, |
| 819 |
); |
| 820 |
|
| 821 |
$query{format} = 'json'; |
| 822 |
|
| 823 |
$url .= '?' . $http->www_form_urlencode( \%query ); |
| 824 |
my $res = $http->get($url); |
| 825 |
|
| 826 |
if ( !$res->{success} ) { |
| 827 |
if ( $OPT{ignore} ) { |
| 828 |
return; |
| 829 |
} |
| 830 |
else { |
| 831 |
warning("HTTP request failed"); |
| 832 |
say STDERR $res->{content}; |
| 833 |
exit 1; |
| 834 |
} |
| 835 |
} |
| 836 |
|
| 837 |
$res->{content}; |
| 838 |
} |
| 839 |
|
| 840 |
sub get_qid_from_sitelink { |
| 841 |
my $api = "https://$_[0]/w/api.php"; |
| 842 |
my $title = $_[1]; |
| 843 |
|
| 844 |
my $res = http_get( |
| 845 |
$api, |
| 846 |
action => 'query', |
| 847 |
prop => 'pageprops', |
| 848 |
titles => $title, |
| 849 |
redirects => 1 |
| 850 |
); |
| 851 |
|
| 852 |
my $data = JSON->new->decode($res); |
| 853 |
my ($page) = values %{ $data->{query}->{pages} }; |
| 854 |
return unless $page->{pageprops}; |
| 855 |
return $page->{pageprops}->{wikibase_item}; |
| 856 |
} |
| 857 |
|
| 858 |
sub get_lookup_query { |
| 859 |
my $id = shift; |
| 860 |
|
| 861 |
my $entity_id; |
| 862 |
|
| 863 |
if ( $id =~ $ENTITY_PATTERN ) { |
| 864 |
$entity_id = $+{id}; |
| 865 |
$entity_id =~ s/Property://i; |
| 866 |
} |
| 867 |
else { |
| 868 |
# URL could be percent-encoded or not, so normalize |
| 869 |
my $uri = URI->new($id); |
| 870 |
if ( $uri and $uri->canonical =~ $SITELINK_PATTERN ) { |
| 871 |
my ( $base, $title ) = ( $+{base}, $+{title} ); |
| 872 |
|
| 873 |
# unescape to UTF-8 octets |
| 874 |
$title =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg; |
| 875 |
$title = decode_utf8($title); |
| 876 |
|
| 877 |
if ( $OPT{'no-mediawiki'} ) { |
| 878 |
warning("MediaWiki API disabled"); |
| 879 |
exit 1; |
| 880 |
} |
| 881 |
$entity_id = get_qid_from_sitelink( $base, $title ); |
| 882 |
unless ($entity_id) { |
| 883 |
warning("Wikidata item not found: $id"); |
| 884 |
return; |
| 885 |
} |
| 886 |
} |
| 887 |
} |
| 888 |
|
| 889 |
unless ($entity_id) { |
| 890 |
warning("unknown identifier: $id"); |
| 891 |
return; |
| 892 |
} |
| 893 |
|
| 894 |
my $uri = "http://www.wikidata.org/entity/" . uc($entity_id); |
| 895 |
|
| 896 |
return <<SPARQL; |
| 897 |
SELECT ?id ?label ?description WHERE { |
| 898 |
BIND(<$uri> AS ?id) |
| 899 |
SERVICE wikibase:label { |
| 900 |
bd:serviceParam wikibase:language "$OPT{language}" . |
| 901 |
?id rdfs:label ?label ; schema:description ?description |
| 902 |
} |
| 903 |
} |
| 904 |
SPARQL |
| 905 |
} |
| 906 |
|
| 907 |
sub literal { RDF::Trine::Node::Literal->new(@_) } |
| 908 |
|
| 909 |
sub map_ids { |
| 910 |
my $row = shift; |
| 911 |
foreach my $name ( keys %$row ) { |
| 912 |
my $v = $row->{$name}; |
| 913 |
next unless $v->isa('RDF::Trine::Node::Resource'); |
| 914 |
my $id; |
| 915 |
$id = $+{id} if $v->uri_value =~ $ENTITY_PATTERN; |
| 916 |
$id = $+{id} if $v->uri_value =~ $WIKIDATA_ID_PATTERN; |
| 917 |
$row->{$name} = literal($id) if $id; |
| 918 |
} |
| 919 |
$row; |
| 920 |
} |
| 921 |
|
| 922 |
sub get_sparql { |
| 923 |
my $json = http_get( $OPT{api}, query => shift ); |
| 924 |
require RDF::Trine::Iterator::JSONHandler; |
| 925 |
$json |
| 926 |
? RDF::Trine::Iterator::JSONHandler->new->parse($json) |
| 927 |
: RDF::Trine::Iterator->new( [], 'bindings', [] ); |
| 928 |
} |
| 929 |
|
| 930 |
sub map_searchresponse_to_row { |
| 931 |
my $res = shift; |
| 932 |
my $language = $OPT{language}; # TODO: only first |
| 933 |
|
| 934 |
my $row = { |
| 935 |
id => RDF::Trine::Node::Resource->new( $res->{concepturi} ), |
| 936 |
label => literal( $res->{label}, $language ), |
| 937 |
}; |
| 938 |
if ( defined $res->{description} ) { |
| 939 |
$row->{description} = literal( $res->{description}, $language ); |
| 940 |
} |
| 941 |
if ( $res->{match}{type} eq 'alias' ) { |
| 942 |
$row->{alias} = literal( $res->{match}{text}, $language ); |
| 943 |
} |
| 944 |
|
| 945 |
$row; |
| 946 |
} |
| 947 |
|
| 948 |
sub perform_search { |
| 949 |
my $query = shift; |
| 950 |
|
| 951 |
if ( $OPT{'no-mediawiki'} ) { |
| 952 |
warning("MediaWiki API disabled"); |
| 953 |
exit 1; |
| 954 |
} |
| 955 |
|
| 956 |
my $language = $OPT{language}; # TODO: only first |
| 957 |
my $api = "https://www.wikidata.org/w/api.php"; |
| 958 |
my $res = http_get( |
| 959 |
$api, |
| 960 |
action => 'wbsearchentities', |
| 961 |
language => $language, |
| 962 |
uselang => $language, |
| 963 |
strictlanguage => '1', |
| 964 |
type => $MODE eq 'search' ? 'item' : 'property', |
| 965 |
search => $query, |
| 966 |
$OPT{limit} ? ( limit => $OPT{limit} ) : (), |
| 967 |
); |
| 968 |
my $data = JSON->new->decode($res); |
| 969 |
|
| 970 |
$data = [ map { map_searchresponse_to_row($_) } @{ $data->{search} } ]; |
| 971 |
|
| 972 |
require RDF::Trine::Iterator::Bindings; |
| 973 |
RDF::Trine::Iterator::Bindings->new($data); |
| 974 |
} |
| 975 |
|
| 976 |
sub postprocess_iterator { |
| 977 |
my ( $iterator, @map ) = @_; |
| 978 |
|
| 979 |
# abbreviate identifiers |
| 980 |
push @map, \&map_ids if $OPT{ids}; |
| 981 |
|
| 982 |
# enumerate results |
| 983 |
my $n = 1; |
| 984 |
if ( $OPT{enumerate} ) { |
| 985 |
push @map, sub { |
| 986 |
my $row = shift; |
| 987 |
$row->{n} = literal( $n++ ); |
| 988 |
$row; |
| 989 |
} |
| 990 |
} |
| 991 |
|
| 992 |
# apply postprocessing |
| 993 |
if (@map) { |
| 994 |
$iterator = RDF::Trine::Iterator::smap( |
| 995 |
sub { |
| 996 |
my $row = shift; |
| 997 |
$row = $_->($row) for @map; |
| 998 |
$row; |
| 999 |
}, |
| 1000 |
$iterator |
| 1001 |
); |
| 1002 |
} |
| 1003 |
|
| 1004 |
$iterator; |
| 1005 |
} |
| 1006 |
|
| 1007 |
my ( $variables, $iterator, $query ); |
| 1008 |
|
| 1009 |
# query mode |
| 1010 |
if ( $MODE eq 'query' ) { |
| 1011 |
$OPT{query} //= shift @ARGV if @ARGV; |
| 1012 |
$OPT{query} //= '-'; |
| 1013 |
|
| 1014 |
my $query = do { |
| 1015 |
local $/ = undef; |
| 1016 |
if ( $OPT{query} eq '-' ) { |
| 1017 |
<STDIN>; |
| 1018 |
} |
| 1019 |
elsif ( -f $OPT{query} or $OPT{query} !~ /[$\?\{]/ ) { |
| 1020 |
open my $fh, '<', $OPT{query} |
| 1021 |
or die "failed to open file " . $OPT{query}; |
| 1022 |
<$fh>; |
| 1023 |
} |
| 1024 |
else { |
| 1025 |
$OPT{query}; |
| 1026 |
} |
| 1027 |
}; |
| 1028 |
|
| 1029 |
( $query, $variables ) = expand_query($query); |
| 1030 |
exit unless $query; |
| 1031 |
|
| 1032 |
$iterator = get_sparql($query); |
| 1033 |
} |
| 1034 |
|
| 1035 |
# lookup mode |
| 1036 |
elsif ( $MODE eq 'lookup' ) { |
| 1037 |
require URI; |
| 1038 |
my $output; |
| 1039 |
|
| 1040 |
my $lookup = sub { |
| 1041 |
my $id = shift; |
| 1042 |
$id =~ s/^\s+|\s+$//g; # trim whitespace |
| 1043 |
return if $id eq ''; # skip empty lines |
| 1044 |
|
| 1045 |
my $query = get_lookup_query($id) or return; |
| 1046 |
|
| 1047 |
($query) = expand_query($query); |
| 1048 |
return unless $query; |
| 1049 |
|
| 1050 |
my $iterator = get_sparql($query); |
| 1051 |
$iterator = postprocess_iterator($iterator); |
| 1052 |
|
| 1053 |
my $vars = [qw(id label description)]; |
| 1054 |
unshift( @$vars, 'n' ) if $OPT{enumerate}; |
| 1055 |
|
| 1056 |
$output //= $format->start( $vars, \*STDOUT ); |
| 1057 |
|
| 1058 |
while ( my $row = $iterator->next ) { |
| 1059 |
$output->add($row); |
| 1060 |
} |
| 1061 |
}; |
| 1062 |
|
| 1063 |
my $limit = $OPT{limit} // 0; |
| 1064 |
if (@ARGV) { |
| 1065 |
foreach (@ARGV) { |
| 1066 |
$lookup->($_); |
| 1067 |
last if !--$limit; |
| 1068 |
} |
| 1069 |
} |
| 1070 |
else { |
| 1071 |
while (<>) { |
| 1072 |
$lookup->($_); |
| 1073 |
last if !--$limit; |
| 1074 |
} |
| 1075 |
} |
| 1076 |
|
| 1077 |
$output->end() if $output; |
| 1078 |
|
| 1079 |
exit; |
| 1080 |
} |
| 1081 |
|
| 1082 |
# search mode |
| 1083 |
elsif ( $MODE =~ /^p?search$/ ) { |
| 1084 |
$query = join ' ', @ARGV; |
| 1085 |
$variables = [qw(id label alias description)]; |
| 1086 |
$iterator = perform_search($query); |
| 1087 |
} |
| 1088 |
|
| 1089 |
unless ( $OPT{ignore} || $iterator->peek ) { |
| 1090 |
warning( $query ? "not found: $query" : "not found" ); |
| 1091 |
exit 1; |
| 1092 |
} |
| 1093 |
|
| 1094 |
# postprocess results |
| 1095 |
unshift( @$variables, 'n' ) if $OPT{enumerate} and $variables; |
| 1096 |
$iterator = postprocess_iterator($iterator); |
| 1097 |
|
| 1098 |
# emit results |
| 1099 |
{ |
| 1100 |
my $vars = $variables // sort keys %{ $iterator->peek }; |
| 1101 |
my $output = $format->start( $vars, \*STDOUT ); |
| 1102 |
my $n = 0; |
| 1103 |
while ( my $row = $iterator->next ) { |
| 1104 |
last if $OPT{limit} and $n++ >= $OPT{limit}; |
| 1105 |
$output->add($row); |
| 1106 |
} |
| 1107 |
$output->end; |
| 1108 |
} |
| 1109 |
|
| 1110 |
__END__ |
| 1111 |
|
| 1112 |
=head1 NAME |
| 1113 |
|
| 1114 |
wdq - command line access to Wikidata Query Service |
| 1115 |
|
| 1116 |
=begin markdown |
| 1117 |
|
| 1118 |
# STATUS |
| 1119 |
|
| 1120 |
[](https://travis-ci.org/nichtich/wdq) |
| 1121 |
[](https://coveralls.io/r/nichtich/App-wdq) |
| 1122 |
[](http://cpants.cpanauthors.org/dist/App-wdq) |
| 1123 |
|
| 1124 |
=end markdown |
| 1125 |
|
| 1126 |
=head1 SYNOPSIS |
| 1127 |
|
| 1128 |
Access L<Wikidata Query Service|https://query.wikidata.org/> via command line |
| 1129 |
to perform SPARQL queries (C<query> mode), lookup entities (C<lookup>), or |
| 1130 |
search items and properties (C<search> or C<psearch>): |
| 1131 |
|
| 1132 |
wdq -g en solar system # search 'solar system' in English |
| 1133 |
wdq psearch -g es parte # search property 'parte' in Spanish |
| 1134 |
wdq P361 Q544 # lookup properties and items |
| 1135 |
wdq '?c wdt:P361 wd:Q544' # query parts of the solar system |
| 1136 |
|
| 1137 |
See the manual for details or get help via C<wdq help>: |
| 1138 |
|
| 1139 |
wdq help options # list and explain command line options |
| 1140 |
wdq help modes # list and explain request modes |
| 1141 |
wdq help output # explain output control |
| 1142 |
wdq help formats # list and explain output formats |
| 1143 |
wdq help ontology # show Wikidata ontology in a nutshell |
| 1144 |
wdq help prefixes # list RDF prefixes allowed in queries |
| 1145 |
wdq help version # show version of wdq |
| 1146 |
|
| 1147 |
=head1 DESCRIPTION |
| 1148 |
|
| 1149 |
The command line script C<wdq>, included in CPAN module L<App::wdq>, provides a |
| 1150 |
tool to access L<Wikidata Query Service|https://query.wikidata.org/>. It |
| 1151 |
supports formulation and execution of L<SPARQL SELECT |
| 1152 |
queries|http://www.w3.org/TR/sparql11-query/#select> to extract selected |
| 1153 |
information from Wikidata or other Wikibase instances. |
| 1154 |
|
| 1155 |
=head1 INSTALLATION |
| 1156 |
|
| 1157 |
Perl should already installed at most operating systems. Otherwise |
| 1158 |
L<get Perl!|https://www.perl.org/get.html> |
| 1159 |
|
| 1160 |
=head2 FROM CPAN |
| 1161 |
|
| 1162 |
Install sources from CPAN including all dependencies: |
| 1163 |
|
| 1164 |
cpanm App::wdq |
| 1165 |
|
| 1166 |
First L<install cpanm|https://github.com/miyagawa/cpanminus/#installation> if |
| 1167 |
missing. If installation of C<App::wdq> fails try cpanm option C<--notest> or |
| 1168 |
install dependencies as packages as described below. |
| 1169 |
|
| 1170 |
=head2 PREBUILD PACKAGES |
| 1171 |
|
| 1172 |
Install dependencies as prebuild packages for your operating system: |
| 1173 |
|
| 1174 |
# Debian based systems e.g. Ubuntu (>= 14.04) |
| 1175 |
sudo apt-get install libhttp-tiny-perl librdf-query-perl |
| 1176 |
|
| 1177 |
# Windows/ActiveState |
| 1178 |
ppm install HTTP-Tiny |
| 1179 |
ppm install RDF-Query |
| 1180 |
|
| 1181 |
Then install C<wdq> from CPAN as described above or copy the script to some |
| 1182 |
place in your C<$PATH>: |
| 1183 |
|
| 1184 |
wget https://github.com/nichtich/wdq/raw/master/script/wdq |
| 1185 |
chmod +x wdq |
| 1186 |
|
| 1187 |
The latter method will not install this documentation. |
| 1188 |
|
| 1189 |
|
| 1190 |
=head1 MODES |
| 1191 |
|
| 1192 |
Request mode C<query> (default), C<lookup>, C<serch>, or C<psearch> can |
| 1193 |
explicitly be set via first argument or it's guessed from arguments. |
| 1194 |
|
| 1195 |
=head2 query |
| 1196 |
|
| 1197 |
Read SPARQL query from STDIN, option C<--query|-q>, or argument. Namespace |
| 1198 |
definitions and C<SELECT> clause are added if missing. |
| 1199 |
|
| 1200 |
wdq '?c wdt:P361 wd:Q544' |
| 1201 |
wdq '{ ?c wdt:P361 wd:Q544 }' # equivalent |
| 1202 |
wdq 'SELECT * WHERE { ?c wdt:P361 wd:Q544 }' # equivalent |
| 1203 |
wdq < queryfile |
| 1204 |
|
| 1205 |
=head2 lookup |
| 1206 |
|
| 1207 |
Read Wikidata entity ids, URLs, or Wikimedia project URLs from STDIN or |
| 1208 |
arguments. Result fields are C<label>, C<description>, and C<id>: |
| 1209 |
|
| 1210 |
wdq Q1 |
| 1211 |
wdq lookup Q1 # equivalent |
| 1212 |
echo Q1 | wdq lookup # equivalent |
| 1213 |
wdq http://de.wikipedia.org/wiki/Universum # same result |
| 1214 |
|
| 1215 |
=encoding utf8 |
| 1216 |
|
| 1217 |
=head2 search / psearch |
| 1218 |
|
| 1219 |
Search for items or properties. Result fields are C<label>, C<id>, |
| 1220 |
C<description>, and possibly matched C<alias>. Search and result language is |
| 1221 |
read from environment or option C<--language>/C<-g>: |
| 1222 |
|
| 1223 |
wdq search -g sv Pippi Långstrump |
| 1224 |
|
| 1225 |
Default output format in search mode is C<text>. |
| 1226 |
|
| 1227 |
=head1 OPTIONS |
| 1228 |
|
| 1229 |
=over |
| 1230 |
|
| 1231 |
=item --query|-q QUERY |
| 1232 |
|
| 1233 |
Query or query file (C<-> for STDIN as default) |
| 1234 |
|
| 1235 |
=item --format|-f FORMAT|TEMPLATE |
| 1236 |
|
| 1237 |
Output format or string template. Call C<wdq help formats> for details. |
| 1238 |
|
| 1239 |
=item --export EXPORTER |
| 1240 |
|
| 1241 |
Use a L<Catmandu> exporter as output format. |
| 1242 |
|
| 1243 |
=item --no-header|-H |
| 1244 |
|
| 1245 |
Exclude header in CSV output or other exporter. |
| 1246 |
|
| 1247 |
=item --enumerate|-e |
| 1248 |
|
| 1249 |
Enumerate results by adding a counter variable C<n> |
| 1250 |
|
| 1251 |
=item --limit INTEGER |
| 1252 |
|
| 1253 |
Add or override a LIMIT clause to limitate the number of results. Single-digit |
| 1254 |
options such as C<-1> can also be used to also set a limit. |
| 1255 |
|
| 1256 |
=item --ids|-i |
| 1257 |
|
| 1258 |
Abbreviate Wikidata identifier URIs as strings. |
| 1259 |
|
| 1260 |
=item --language|-g |
| 1261 |
|
| 1262 |
Language to query labels and descriptions in. Set to the locale by default. |
| 1263 |
This option is currentl only used on lookup mode. |
| 1264 |
|
| 1265 |
=item --count|-c VARS |
| 1266 |
|
| 1267 |
Prepend SPARQL QUERY to count distinct values |
| 1268 |
|
| 1269 |
=item --label|-l VARS |
| 1270 |
|
| 1271 |
=item --description|-d VARS |
| 1272 |
|
| 1273 |
=item --text|-t VARS |
| 1274 |
|
| 1275 |
Add label, description, or both. Adds C<label>/C<description> for variable C<id> |
| 1276 |
or C<xLabel>/C<xDescription> for any C<x>. |
| 1277 |
|
| 1278 |
=item --ignore |
| 1279 |
|
| 1280 |
Ignore empty results instead of issuing warning and exit code. |
| 1281 |
|
| 1282 |
=item --color|-C |
| 1283 |
|
| 1284 |
By default output is colored if writing to a terminal. Disable this with |
| 1285 |
C<--no-color>, C<--monochrome>, or C<-M>. Force color with C<--color> or C<-C>. |
| 1286 |
|
| 1287 |
=item --api URL |
| 1288 |
|
| 1289 |
SPARQL endpoint. Default value: |
| 1290 |
C<https://query.wikidata.org/bigdata/namespace/wdq/sparql> |
| 1291 |
|
| 1292 |
=item --no-mediawiki|-m |
| 1293 |
|
| 1294 |
Don't query MediaWiki API to map URLs to Wikidata items. |
| 1295 |
|
| 1296 |
=item --no-execute|-n |
| 1297 |
|
| 1298 |
Don't execute SPARQL queries but show them in expanded form. Useful to |
| 1299 |
validate and pretty-print queries. MediaWiki API requests may be |
| 1300 |
|
| 1301 |
=item -N |
| 1302 |
|
| 1303 |
Don't execute any queries. Same as C<--no-mediawiki --no-execute>. |
| 1304 |
|
| 1305 |
=item --help|-h|-? |
| 1306 |
|
| 1307 |
Show usage help |
| 1308 |
|
| 1309 |
=item --ontology |
| 1310 |
|
| 1311 |
Show information about the Wikidata Ontology |
| 1312 |
|
| 1313 |
=item --no-default-prefixes |
| 1314 |
|
| 1315 |
Don't add default namespace prefixes to the SPARQL query |
| 1316 |
|
| 1317 |
=item --man |
| 1318 |
|
| 1319 |
Show detailled manual |
| 1320 |
|
| 1321 |
=item --version|-V |
| 1322 |
|
| 1323 |
Show version if this script |
| 1324 |
|
| 1325 |
=back |
| 1326 |
|
| 1327 |
=head1 OUTPUT |
| 1328 |
|
| 1329 |
Output can be controlled with options C<--format>/C<-f>, C<--export>, |
| 1330 |
C<--header>/C<--no-header>/C<-H>, and C<--color>/C<--no-color>/C<-C>. |
| 1331 |
|
| 1332 |
=head2 Formats |
| 1333 |
|
| 1334 |
Option C<--format>/C<-f> sets an output format or string template: |
| 1335 |
|
| 1336 |
=over |
| 1337 |
|
| 1338 |
=item C<simple> (default in query and lookup mode) |
| 1339 |
|
| 1340 |
Flat JSON without language tags |
| 1341 |
|
| 1342 |
=item C<text> (default in search mode) |
| 1343 |
|
| 1344 |
Print C<label>, C<alias>, C<id> and C<description> or C<count> when counting. |
| 1345 |
Also sets option C<--ids>. |
| 1346 |
|
| 1347 |
=item C<ldjson> |
| 1348 |
|
| 1349 |
Line delimited Flat JSON |
| 1350 |
|
| 1351 |
=item C<csv> |
| 1352 |
|
| 1353 |
SPARQL Query Results CSV Format. Suppress header with option |
| 1354 |
C<--no-header>/C<-H>. Use Catmandu CSV exporter for more options |
| 1355 |
|
| 1356 |
=item C<tsv> |
| 1357 |
|
| 1358 |
SPARQL Query Results TSV Format |
| 1359 |
|
| 1360 |
=item C<xml> |
| 1361 |
|
| 1362 |
SPARQL Query Results XML Format |
| 1363 |
|
| 1364 |
=item C<json> |
| 1365 |
|
| 1366 |
SPARQL Query Results JSON Format |
| 1367 |
|
| 1368 |
=item C<...> |
| 1369 |
|
| 1370 |
String template. Call C<wdq help pretty> for details |
| 1371 |
|
| 1372 |
=back |
| 1373 |
|
| 1374 |
=head2 Pretty |
| 1375 |
|
| 1376 |
Option C<--format> can be set to a string template with bracket expressions |
| 1377 |
with optional template parameters (for instance C<{id|pre= (|post=)}>). |
| 1378 |
|
| 1379 |
=over |
| 1380 |
|
| 1381 |
=item style |
| 1382 |
|
| 1383 |
Highlight C<n> name, C<v> value, C<i> identifier, C<t> title, or C<e> error |
| 1384 |
|
| 1385 |
=item length |
| 1386 |
|
| 1387 |
Abbreviate long values |
| 1388 |
|
| 1389 |
=item align |
| 1390 |
|
| 1391 |
Use C<left> or C<right> to align short values to a given C<length> |
| 1392 |
|
| 1393 |
=item pre/post |
| 1394 |
|
| 1395 |
Add string before/after value |
| 1396 |
|
| 1397 |
=back |
| 1398 |
|
| 1399 |
=head2 Export |
| 1400 |
|
| 1401 |
Option C<--export> sets a L<Catmandu> exporter to create output with. Given |
| 1402 |
the corresponding exporter modules installed, one can write results as C<YAML>, |
| 1403 |
Excel (C<XLS>), and Markdown table (C<Table>) among other formats: |
| 1404 |
|
| 1405 |
wdq --export YAML # short form |
| 1406 |
wdq --format ldjson | catmandu convert to YAML # equivalent |
| 1407 |
|
| 1408 |
Use Catmandu config file (C<catmandu.yml>) to further configure export. See |
| 1409 |
also tools such as L<jq|http://stedolan.github.io/jq/> and |
| 1410 |
L<miller|http://johnkerl.org/miller/> for processing results. |
| 1411 |
|
| 1412 |
=head1 EXAMPLES |
| 1413 |
|
| 1414 |
# search "solar system" in English (=> Q544) |
| 1415 |
wdq -g en solar system |
| 1416 |
|
| 1417 |
# search part-of property (=> P361) |
| 1418 |
wdq psearch -g en part |
| 1419 |
|
| 1420 |
# get all parts of the solar system |
| 1421 |
wdq '?c wdt:P361 wd:Q544' |
| 1422 |
|
| 1423 |
# look up label and description |
| 1424 |
wdq Q42 P9 |
| 1425 |
|
| 1426 |
# look up German Wikipedia article and get label description in French |
| 1427 |
wdq -g fr http://de.wikipedia.org/wiki/Argon |
| 1428 |
|
| 1429 |
# get all references used at an item |
| 1430 |
wdq 'wd:Q1 ?prop [ prov:wasDerivedFrom ?ref ]' |
| 1431 |
|
| 1432 |
# get doctoral advisor graph (academic genealogy) as CSV |
| 1433 |
wdq '?student wdt:P184 ?advisor' --ids --format csv |
| 1434 |
|
| 1435 |
# print expanded SPARQL query |
| 1436 |
wdq -n '?c wdt:P361 wd:Q544' |
| 1437 |
|
| 1438 |
# execute query and return first 10 tab-separated values |
| 1439 |
wdq -f tsv --limit 10 < query |
| 1440 |
|
| 1441 |
# print result as Markdown Table (requires Catmandu::Exporter::Table) |
| 1442 |
wdq --export Table < query |
| 1443 |
|
| 1444 |
# count instances (P31) of books (Q571) |
| 1445 |
wdq --count x '?x wdt:P31 wd:Q571' |
| 1446 |
|
| 1447 |
# list types (P279) of Exoplanets (Q44559) with label and description |
| 1448 |
wdq '?id wdt:P279 wd:Q44559:' --text id --format text |
| 1449 |
|
| 1450 |
=head1 WIKIDATA ONTOLOGY |
| 1451 |
|
| 1452 |
Entity (item/property) |
| 1453 |
wd:Q* <-- owl:sameAs --> wd:Q* |
| 1454 |
--> rdfs:label, skos:altLabel, schema:description "*"@* |
| 1455 |
--> schema:dateModified, schema:version |
| 1456 |
--> wdt:P* "*", URI, _:blank |
| 1457 |
--> p:P* Statement |
| 1458 |
|
| 1459 |
Item |
| 1460 |
wd:Q* <-- schema:about <http://*.wikipedia.org/wiki/*> |
| 1461 |
--> schema:inLanguage, wikibase:badge |
| 1462 |
|
| 1463 |
Property |
| 1464 |
wd:P* --> wikibase:propertyType PropertyType |
| 1465 |
--> wkibase:directClaim wdt:P* |
| 1466 |
--> wikibase:claim p:P* |
| 1467 |
--> wikibase:statementProperty ps:P* |
| 1468 |
--> wikibase:statementValue psv:P* |
| 1469 |
--> wikibase:qualifier pq:P* |
| 1470 |
--> wikibase:qualifierValue pqv:P* |
| 1471 |
--> wikibase:reference pr:P* |
| 1472 |
--> wikibase:referenceValue prv:P* |
| 1473 |
--> wikibase:novalue wdno:P* |
| 1474 |
|
| 1475 |
PropertyType |
| 1476 |
wikibase: String, Url, WikibaseItem, WikibaseProperty, CommonsMedia, Math, |
| 1477 |
Monolingualtext, GlobeCoordinate, Quantity, Time, ExternalId |
| 1478 |
|
| 1479 |
|
| 1480 |
Statement |
| 1481 |
wds:* --> wikibase:rank Rank |
| 1482 |
--> a wdno:P* |
| 1483 |
--> ps:P* "*", URI, _:blank |
| 1484 |
--> psv:P* Value |
| 1485 |
--> pq:P* "*", URI, _:blank |
| 1486 |
--> pqv:P* Value |
| 1487 |
--> prov:wasDerivedFrom Reference |
| 1488 |
|
| 1489 |
Reference |
| 1490 |
wdref:* --> pr:P* "*", URI |
| 1491 |
--> prv:P* Value |
| 1492 |
|
| 1493 |
Rank |
| 1494 |
wikibase: NormalRank, PreferredRank, DeprecatedRank, BestRank |
| 1495 |
|
| 1496 |
Value (GlobecoordinateValue/QuantityValue/TimeValue) |
| 1497 |
wdv:* --> wikibase: geoLatitude, geoLongitude, geoPrecision, geoGlobe URI |
| 1498 |
--> wikibase: timeValue, timePrecision, timeTimezone, timeCalendarModel |
| 1499 |
--> wikibase: quantityAmount, quantityUpperBound, quantityLowerBound, |
| 1500 |
quantityUnit URI |
| 1501 |
|
| 1502 |
=head1 COPYRIGHT AND LICENSE |
| 1503 |
|
| 1504 |
Copyright by Jakob Voss C<[email protected]> |
| 1505 |
|
| 1506 |
Based on a PHP script by Marius Hoch C<[email protected]> |
| 1507 |
at L<https://github.com/mariushoch/asparagus>. |
| 1508 |
|
| 1509 |
Licensed under GPL 2.0+ |
| 1510 |
|
| 1511 |
=cut |