| 1 | package CWB::Web::Search; | ||
| 2 | ## -*-cperl-*- | ||
| 3 | |||
| 4 | 1 | ▶ | use Carp; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 1 | ▶ | use CWB::CL; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 6 | use HTML::Entities; | ||
| 7 | |||
| 8 | |||
| 9 | # | ||
| 10 | # CWB::Web::Search::MatchList objects (used internally) | ||
| 11 | # | ||
| 12 | |||
| 13 | package CWB::Web::Search::MatchList; | ||
| 14 | use Carp; | ||
| 15 | use HTML::Entities; | ||
| 16 | use CWB::CL; | ||
| 17 | |||
| 18 | # CWB::Web::Search::MatchList object = reference to list of structs: | ||
| 19 | # $ml->[$i]->{'center'} = center of match (mean of keywords) | ||
| 20 | # $ml->[$i]->{'variance'} = variance of match (-> quality) | ||
| 21 | # $ml->[$i]->{'n'} = number of keywords in this match | ||
| 22 | # $ml->[$i]->{'first'} = first corpus position of minimal match | ||
| 23 | # $ml->[$i]->{'last'} = last corpus position of minimal match | ||
| 24 | # $ml->[$i]->{'keyword'}->{$cpos} = code of keyword at c.p. $cpos | ||
| 25 | # $ml->[$i]->{'quality'} = relevance of match (must be explicitly recomputed) | ||
| 26 | |||
| 27 | sub new { | ||
| 28 | my $class = shift; | ||
| 29 | my $self = []; | ||
| 30 | bless $self, $class; | ||
| 31 | $self->add(@_); # optional initialisation | ||
| 32 | return $self; | ||
| 33 | } | ||
| 34 | |||
| 35 | # find insertion point by 'center' value (this _would_ be correct | ||
| 36 | # if the match list were ordered); returns index into list | ||
| 37 | sub find_point { | ||
| 38 | my $self = shift; | ||
| 39 | my $center = shift; # center of element to insert | ||
| 40 | my $i = shift; # optional arg: start index | ||
| 41 | $i = 0 unless defined $i; | ||
| 42 | my $size = @$self; | ||
| 43 | $i++ | ||
| 44 | while ($i < $size and $center > $self->[$i]->{'center'}); | ||
| 45 | $i-- | ||
| 46 | while ($i > 0 and $center < $self->[$i-1]->{'center'}); | ||
| 47 | return $i; | ||
| 48 | } | ||
| 49 | |||
| 50 | # add new matches to list, initialised to size 1, variance 0 | ||
| 51 | # Usage: $self->add($keyword, @cpos); | ||
| 52 | sub add { | ||
| 53 | my $self = shift; | ||
| 54 | my $keyword = shift; # code of keyword | ||
| 55 | my $i = 0; | ||
| 56 | foreach my $center (@_) { | ||
| 57 | $i = $self->find_point($center, $i); # should be fast if cpos list is ordered | ||
| 58 | splice @$self, $i, 0, { | ||
| 59 | 'center' => $center, | ||
| 60 | 'variance' => 0, | ||
| 61 | 'n' => 1, | ||
| 62 | 'first' => $center, | ||
| 63 | 'last' => $center, | ||
| 64 | 'keyword' => { $center => $keyword }, | ||
| 65 | 'quality' => 0, | ||
| 66 | }; | ||
| 67 | } | ||
| 68 | } | ||
| 69 | |||
| 70 | # returns matchlist size | ||
| 71 | sub size { | ||
| 72 | my $self = shift; | ||
| 73 | return scalar @$self; | ||
| 74 | } | ||
| 75 | |||
| 76 | # retrieve single match: returns | ||
| 77 | # (first, last, center, variance, quality, %keyword [as cpos => keycode pairs]) | ||
| 78 | sub match { | ||
| 79 | my $self = shift; | ||
| 80 | my $n = shift; | ||
| 81 | my $m = $self->[$n]; | ||
| 82 | return ($m->{'first'}, $m->{'last'}, $m->{'center'}, $m->{'variance'}, $m->{'quality'}, %{$m->{'keyword'}}); | ||
| 83 | } | ||
| 84 | |||
| 85 | # summarize (single) match (maximal length defaults to 160 words) | ||
| 86 | # Usage: $summary = $ml->summarize($n, $word_att, $start_tag, $end_tag [, $maximal_length]); | ||
| 87 | sub summarize { | ||
| 88 | my $self = shift; | ||
| 89 | my $n = shift; | ||
| 90 | my $word_att = shift; | ||
| 91 | my $start_tag = shift; | ||
| 92 | my $end_tag = shift; | ||
| 93 | my $maximal_length = shift; | ||
| 94 | $maximal_length = 160 unless defined $maximal_length; | ||
| 95 | $maximal_length = int ($maximal_length / 2) + 1; # summary is symmetric to center of match | ||
| 96 | my $match = $self->[$n]; | ||
| 97 | my $length = int(sqrt($match->{'variance'})*2 + 15); # default summary extends 2 * s.d. + 15 tokens to each side from center | ||
| 98 | $length = $maximal_length if $length > $maximal_length; | ||
| 99 | $length = 5 if $length < 5; # minimum size is 11 words | ||
| 100 | my @words = (); # summary as word list | ||
| 101 | # summary must be contained in context, i.e. use this matches 'first' and 'last' as hard boundaries | ||
| 102 | my $first = $match->{'center'} - $length; | ||
| 103 | my $pre_ell = "... "; # ellipsis before summary if not start of document | ||
| 104 | if ($first < $match->{'first'}) { | ||
| 105 | $first = $match->{'first'}; | ||
| 106 | $pre_ell = ""; | ||
| 107 | } | ||
| 108 | my $last = $match->{'center'} + $length; | ||
| 109 | my $post_ell = " ..."; # ellipsis after summary if not end of document | ||
| 110 | if ($last > $match->{'last'}) { | ||
| 111 | $last = $match->{'last'}; | ||
| 112 | $post_ell = ""; | ||
| 113 | } | ||
| 114 | |||
| 115 | foreach my $cpos ($first .. $last) { | ||
| 116 | my $token = encode_entities($word_att->cpos2str($cpos)); | ||
| 117 | $token = $start_tag.$token.$end_tag | ||
| 118 | if (defined $match->{'keyword'}->{$cpos}); | ||
| 119 | push @words, $token; | ||
| 120 | } | ||
| 121 | return $pre_ell."@words".$post_ell; | ||
| 122 | } | ||
| 123 | |||
| 124 | # (re-)compute quality values of matches | ||
| 125 | # Usage: $ml->compute_quality($no_of_keywords [, @preferred ]); | ||
| 126 | sub compute_quality { | ||
| 127 | my $self = shift; | ||
| 128 | my $no_of_keywords = shift; | ||
| 129 | my @preferred = @_; # list of s-attribute handles for preferred regions -> higher quality score | ||
| 130 | # each keyword present in the match scores 1 point; proximity of the | ||
| 131 | # keywords scores up to $proximity_points points (scaled by standard deviation) | ||
| 132 | my $proximity_points = # we'll probably want to make that configurable | ||
| 133 | ($no_of_keywords > 2) ? 2 : 1; | ||
| 134 | my $preferred_points = (@preferred) ? # ... and that as well | ||
| 135 | (($no_of_keywords > 3) ? 2 : 1) : 0; | ||
| 136 | my $total_points = ($no_of_keywords - 1) + $proximity_points + $preferred_points; | ||
| 137 | |||
| 138 | foreach my $match (@$self) { | ||
| 139 | my $variance = $match->{'variance'}; | ||
| 140 | $variance = 4 if $variance < 4; # scale proximity score to 0 .. $proximity_points range | ||
| 141 | my $sd = sqrt($variance/4); | ||
| 142 | my $cnt_preferred = 0; # a match gets higher score, if one or more of its keywords fall into preferred environments | ||
| 143 | foreach my $keyword (keys %{$match->{'keyword'}}) { | ||
| 144 | $cnt_preferred++ | ||
| 145 | if grep { defined $_->cpos2struc($keyword) } @preferred; | ||
| 146 | } | ||
| 147 | my $quality = | ||
| 148 | (($match->{'n'} - 1) + ($proximity_points / $sd) + ($preferred_points * $cnt_preferred / $no_of_keywords)) | ||
| 149 | / $total_points; | ||
| 150 | $match->{'quality'} = int ($quality*100 + 0.5); # rounded percentage | ||
| 151 | } | ||
| 152 | } | ||
| 153 | |||
| 154 | # sort matchlist by one the fields | ||
| 155 | # 'first' ... sort by first position in match | ||
| 156 | # 'quality' ... sort by quality values (make sure you've called compute_quality() beforehand!) | ||
| 157 | sub sort { | ||
| 158 | my $self = shift; | ||
| 159 | my $method = shift; | ||
| 160 | my %sort = ( | ||
| 161 | 'first' => sub {return sort {$a->{'first'} <=> $b->{'first'}} @_}, | ||
| 162 | 'quality' => sub {return sort {$b->{'quality'} <=> $a->{'quality'}} @_}, | ||
| 163 | ); | ||
| 164 | croak "Usage: \$ml->sort('".join("' | '", keys %sort)."');" | ||
| 165 | unless defined $sort{$method}; | ||
| 166 | @$self = &{$sort{$method}}(@$self); | ||
| 167 | } | ||
| 168 | |||
| 169 | # remove overlapping matches ("cull" the one with highest quality rating) | ||
| 170 | # NB don't forget to $ml->compute_quality; $ml->sort('first') before! | ||
| 171 | sub cull { | ||
| 172 | my $self = shift; | ||
| 173 | I_LOOP: | ||
| 174 | for (my $i = 0; $i < @$self; $i++) { | ||
| 175 | my $i_first = $self->[$i]->{'first'}; | ||
| 176 | my $i_last = $self->[$i]->{'last'}; | ||
| 177 | J_LOOP: | ||
| 178 | for (my $j = $i+1; $j < @$self; $j++) { | ||
| 179 | last unless $j < @$self; # check again for 'redo' | ||
| 180 | my $j_first = $self->[$j]->{'first'}; | ||
| 181 | my $j_last = $self->[$j]->{'last'}; | ||
| 182 | # compare i-th and j-th element of match list | ||
| 183 | last J_LOOP # assume ml is ordered by 'first' -> no more overlaps possible after this point | ||
| 184 | if $j_first > $i_last; | ||
| 185 | if ($i_last >= $j_first) { | ||
| 186 | if ($self->[$i]->{'quality'} >= $self->[$j]->{'quality'}) { | ||
| 187 | # i-th match is better -> keep it, delete j-th match | ||
| 188 | splice @$self, $j, 1; | ||
| 189 | redo J_LOOP; # must re-consider j-th match | ||
| 190 | } | ||
| 191 | else { | ||
| 192 | # j-th match is better -> delete i-th match and restart outer loop | ||
| 193 | splice @$self, $i, 1; | ||
| 194 | redo I_LOOP; | ||
| 195 | } | ||
| 196 | } | ||
| 197 | } | ||
| 198 | } | ||
| 199 | # meself had better be culled nicely now ... | ||
| 200 | } | ||
| 201 | |||
| 202 | |||
| 203 | # ** | ||
| 204 | # cleanup: to be done | ||
| 205 | # find overlapping matches & select the one with higher quality | ||
| 206 | # ** | ||
| 207 | |||
| 208 | |||
| 209 | # expand to desired context setting | ||
| 210 | # template for the context_expansion_func() function: | ||
| 211 | # ($first, $last) = context_expansion_func($first, $last); | ||
| 212 | sub expand { | ||
| 213 | my $self = shift; | ||
| 214 | my $context_expansion = shift; | ||
| 215 | croak 'Usage: $ml->expand(\&context_expansion_func);' | ||
| 216 | unless defined $context_expansion and ref $context_expansion eq 'CODE'; | ||
| 217 | |||
| 218 | foreach my $match (@$self) { | ||
| 219 | ($match->{'first'}, $match->{'last'}) = | ||
| 220 | &{$context_expansion}($match->{'first'}, $match->{'last'}); | ||
| 221 | } | ||
| 222 | } | ||
| 223 | |||
| 224 | # this is the big one: check positive/negative constraint on matches; or join keyword list | ||
| 225 | # template for the check_match_size() function: | ||
| 226 | # $ok = check_match_size($first, $last); | ||
| 227 | sub constraint { | ||
| 228 | my $self = shift; | ||
| 229 | my $mode = lc shift; # mode is positive, negative, or join | ||
| 230 | croak "Usage: \$ml->constraint('positive'|'negative'|'optional'|'join', \$keyword, \\&check_match_size, \@cpos_list);" | ||
| 231 | unless $mode =~ /^((posi|nega)tive|join|optional)$/ and @_ >= 2; | ||
| 232 | my $keyword = shift; # code of keyword (unused for negative constraint) | ||
| 233 | my $check_match_size = shift; # pointer to function used for checking match size | ||
| 234 | # @_ now contains the list of corpus positions for the constraint | ||
| 235 | |||
| 236 | my %used = (); # in join mode, remember which positions from list have been used | ||
| 237 | |||
| 238 | # apply constraint to all matches in list | ||
| 239 | my ($i, $j) = (0, 0); | ||
| 240 | while ($i < @$self) { # list size may changed (negative constraint) | ||
| 241 | |||
| 242 | my $match = $self->[$i]; | ||
| 243 | $j = find_closest(\@_, $match->{'center'}, $j); | ||
| 244 | # $first .. $last is minimal match region with the new keyword included | ||
| 245 | my $ok = (defined $j) ? 1 : 0; # if @_ == 0, can't find closest -> not ok -> proceed as if check_match_size() had returned false | ||
| 246 | my ($new_position, $first, $last); | ||
| 247 | if ($ok) { | ||
| 248 | $new_position = $_[$j]; | ||
| 249 | ($first, $last) = new_boundaries($match->{'first'}, $match->{'last'}, $new_position); | ||
| 250 | $ok = &{$check_match_size}($first, $last); | ||
| 251 | } | ||
| 252 | if ($ok) { | ||
| 253 | if ($mode eq 'negative') { | ||
| 254 | # negative constraint -> remove match if keyword is within range | ||
| 255 | splice @$self, $i, 1; | ||
| 256 | next; # don't increment $i when we've removed a match | ||
| 257 | } | ||
| 258 | else { | ||
| 259 | # positive constraint / join -> adjoin new keyword to match | ||
| 260 | $match->{'first'} = $first; | ||
| 261 | $match->{'last'} = $last; | ||
| 262 | my $n = $match->{'n'}; # adjust center and variance values | ||
| 263 | my $center = $match->{'center'}; | ||
| 264 | my $variance = $match->{'variance'}; | ||
| 265 | # I believe that the equations below are correct ... ;o) | ||
| 266 | $match->{'center'} = ($n * $center + $new_position) / ($n+1); | ||
| 267 | $match->{'variance'} = ($n/($n+1)) * | ||
| 268 | ($variance + (1/($n+1)) * ($new_position - $center)**2); | ||
| 269 | $match->{'n'} = $n + 1; | ||
| 270 | $match->{'keyword'}->{$new_position} = $keyword; | ||
| 271 | |||
| 272 | # in join mode, don't add keyword later if it was 'used up' now | ||
| 273 | $used{$new_position} = 1; | ||
| 274 | } | ||
| 275 | } | ||
| 276 | else { | ||
| 277 | # no keyword within range -> remove match if positive constraint | ||
| 278 | if ($mode eq 'positive') { | ||
| 279 | splice @$self, $i, 1; | ||
| 280 | next; # don't increment $i after removing match | ||
| 281 | } | ||
| 282 | } | ||
| 283 | |||
| 284 | $i++; # go to next match in list | ||
| 285 | } | ||
| 286 | |||
| 287 | # in join mode, add unused keywords as new matches to list | ||
| 288 | if ($mode eq 'join') { | ||
| 289 | foreach my $cpos (grep {not defined $used{$_}} @_) { | ||
| 290 | $self->add($keyword, $cpos) # check match size (e.g. 'header') for new single-keyword matches | ||
| 291 | if &{$check_match_size}($cpos, $cpos); | ||
| 292 | } | ||
| 293 | } | ||
| 294 | } | ||
| 295 | |||
| 296 | # internal function: modify boundaries so that $pos is included in $start .. $end interval | ||
| 297 | # Usage: ($start, $end) = new_boundaries($start, $end, $pos); | ||
| 298 | sub new_boundaries { | ||
| 299 | my ($start, $end, $pos) = @_; | ||
| 300 | $start = ($pos < $start) ? $pos : $start; | ||
| 301 | $end = ($pos > $end) ? $pos : $end; | ||
| 302 | return ($start, $end); | ||
| 303 | } | ||
| 304 | |||
| 305 | |||
| 306 | # internal function: find element in sorted list closest to given value; returns index | ||
| 307 | # Usage: $index = find_closest(\@list, $val [, $index]); | ||
| 308 | sub find_closest { | ||
| 309 | my $listref = shift; # reference to list | ||
| 310 | my $value = shift; # comparison value | ||
| 311 | my $i = shift; # optional: start index (may speed up search) | ||
| 312 | $i = 0 unless defined $i; | ||
| 313 | my $size = @$listref; | ||
| 314 | $i = $size - 1 if $i >= $size; | ||
| 315 | return undef if $size == 0; # can't find anything in empty list | ||
| 316 | while (1) { | ||
| 317 | if ($i > 0 and $i < $size | ||
| 318 | and abs($listref->[$i-1] - $value) < abs($listref->[$i] - $value)) { | ||
| 319 | $i--; | ||
| 320 | } | ||
| 321 | elsif ($i < ($size - 1) | ||
| 322 | and abs($listref->[$i+1] - $value) < abs($listref->[$i] - $value)) { | ||
| 323 | $i++; | ||
| 324 | } | ||
| 325 | else { | ||
| 326 | last; # found local minimum | ||
| 327 | } | ||
| 328 | } | ||
| 329 | return $i; | ||
| 330 | } | ||
| 331 | |||
| 332 | # debugging ... | ||
| 333 | sub print { | ||
| 334 | my $self = shift; | ||
| 335 | my $match; | ||
| 336 | for (my $i = 0; $i < @$self; $i++) { | ||
| 337 | $match = $self->[$i]; | ||
| 338 | print "MatchList entry #",($i+1)," [",$match->{'n'}," keywords]\n"; | ||
| 339 | print " center: ",(int $match->{'center'}),"\n"; | ||
| 340 | print " variance: ",(int $match->{'variance'}),"\n"; | ||
| 341 | print " first: ",$match->{'first'},"\n"; | ||
| 342 | print " last: ",$match->{'last'},"\n"; | ||
| 343 | my @keys = map {$_."(".$match->{'keyword'}->{$_}.")"} sort keys %{$match->{'keyword'}}; | ||
| 344 | print " keys: @keys\n"; | ||
| 345 | print " quality: ",$match->{'quality'},"%\n"; | ||
| 346 | } | ||
| 347 | } | ||
| 348 | |||
| 349 | |||
| 350 | |||
| 351 | # | ||
| 352 | # the main CWB::Web::Search package | ||
| 353 | # | ||
| 354 | package CWB::Web::Search; | ||
| 355 | |||
| 356 | # error handler: print to STDERR and exit :or: user-defined callback | ||
| 357 | sub error { | ||
| 358 | my $self = shift; | ||
| 359 | if (defined $self->{'error_handler'}) { | ||
| 360 | &{$self->{'error_handler'}}(@_); | ||
| 361 | exit 1; # user-defined error handler should exit | ||
| 362 | } | ||
| 363 | else { | ||
| 364 | print STDERR "\nCWB::Web::Search Error:\n"; | ||
| 365 | grep { chomp(my $l=$_); print STDERR "\t$l\n"; } @_; | ||
| 366 | exit 1; | ||
| 367 | } | ||
| 368 | } | ||
| 369 | |||
| 370 | |||
| 371 | # CWB::Web::Search object struct: | ||
| 372 | # { | ||
| 373 | # 'error_handler' => user-defined error handler (standard fallback if undefined) | ||
| 374 | # 'corpus' => name of query corpus | ||
| 375 | # 'ch' => CWB::CL::Corpus object | ||
| 376 | # 'word' => CWB::CL::Attribute object (word attribute) | ||
| 377 | # 'lemma' => CWB::CL::Attribute object (lemma attribute) | ||
| 378 | # 'check_size' => reference to subroutine | ||
| 379 | # that checks whether all keywords fall within specified range | ||
| 380 | # 'expand' => reference to subroutine | ||
| 381 | # that expands match to full context (textual representation/HTML) | ||
| 382 | # with keywords highlighted | ||
| 383 | # 'cull' => remove overlapping matches 'never', 'before' or 'after' context expansion | ||
| 384 | # 'hlstart' => HTML tag (with attributes) used for keyword highlighting (default: <B>) | ||
| 385 | # 'hlend' => closing tag for keyword highlighting (default: </B>) | ||
| 386 | # 'data' => s-attributes whose values will be returned (separately) | ||
| 387 | # { | ||
| 388 | # <attribute> => CL::Attribute object, | ||
| 389 | # ... | ||
| 390 | # } | ||
| 391 | # 'ignore_case' => 'always', 'auto', 'never' (ignore case) | ||
| 392 | # 'ignore_diac' => 'always', 'auto', 'never' (ignore diacritics) | ||
| 393 | # 'preferred' => [ CL::Attribute object, ... ] (list of preferred environments, | ||
| 394 | # such as <title> or <header>, which increase match relevance) | ||
| 395 | # 'ml' => CWB::Web::Search::MatchList object | ||
| 396 | # } | ||
| 397 | # object constructor: opens CL corpus/attributes & initialises variables | ||
| 398 | sub new { | ||
| 399 | croak "Usage: \$s = new CWB::Web::Search 'HGC';" | ||
| 400 | unless @_ == 2; | ||
| 401 | my $class = shift; | ||
| 402 | my $corpus = lc shift; | ||
| 403 | my $self = {}; | ||
| 404 | bless($self, $class); # so we can use object methods for initialisation | ||
| 405 | $self->{'error_handler'} = undef; | ||
| 406 | # open specified corpus | ||
| 407 | my $ch = new CWB::CL::Corpus $corpus; | ||
| 408 | $self->error("Can't open corpus '$corpus'.") | ||
| 409 | unless defined $ch; | ||
| 410 | $self->{'ch'} = $ch; | ||
| 411 | # open word & lemma attributes | ||
| 412 | my $word = $ch->attribute("word", 'p'); | ||
| 413 | $self->error("Can't access 'word' attribute of corpus '$corpus'.") | ||
| 414 | unless defined $word; | ||
| 415 | $self->{'word'} = $word; | ||
| 416 | my $lemma = $ch->attribute("lemma", 'p'); | ||
| 417 | $self->error("Can't access 'lemma' attribute of corpus '$corpus'.") | ||
| 418 | unless defined $lemma; | ||
| 419 | $self->{'lemma'} = $lemma; | ||
| 420 | # init some variables to default values | ||
| 421 | $self->{'check_size'} = $self->make_check_size_sub("30 tokens"); | ||
| 422 | $self->{'expand'} = $self->make_expand_sub("50 tokens"); | ||
| 423 | $self->{'data'} = {}; # by default, no data is returned | ||
| 424 | $self->{'ignore_case'} = 'auto'; # ignore case/diacritics set to automatic by default | ||
| 425 | $self->{'ignore_diac'} = 'auto'; | ||
| 426 | $self->{'ml'} = new CWB::Web::Search::MatchList; # empty match list | ||
| 427 | $self->{'cull'} = 'never'; # don't cull() by default | ||
| 428 | $self->highlight("<B>"); # default highlighting is <B> .. </B> | ||
| 429 | $self->preferred(); # preferred environments depend on specific corpus | ||
| 430 | |||
| 431 | return $self; | ||
| 432 | } | ||
| 433 | |||
| 434 | # object destructor: undef backends | ||
| 435 | sub DESTROY { | ||
| 436 | my $self = shift; | ||
| 437 | delete $self->{'data'}; # undef's attribute handles | ||
| 438 | delete $self->{'word'}; | ||
| 439 | delete $self->{'lemma'}; | ||
| 440 | delete $self->{'check_size'}; | ||
| 441 | delete $self->{'expand'}; | ||
| 442 | delete $self->{'ch'}; | ||
| 443 | delete $self->{'ml'}; | ||
| 444 | } | ||
| 445 | |||
| 446 | # error handler | ||
| 447 | sub on_error { | ||
| 448 | my $self = shift; | ||
| 449 | my $handler = shift; | ||
| 450 | croak 'Usage: $s->on_error(\&my_error_handler);' | ||
| 451 | unless (not defined $handler or ref $handler eq 'CODE') and @_ == 0; | ||
| 452 | $self->{'error_handler'} = $handler; | ||
| 453 | } | ||
| 454 | |||
| 455 | # create match size checking subroutine | ||
| 456 | # Usage: $coderef = make_check_size_sub("2 s"); | ||
| 457 | # ok() if &$coderef($first, $last); | ||
| 458 | sub make_check_size_sub { | ||
| 459 | my ($self, $context) = @_; | ||
| 460 | if ($context =~ /^\s*([0-9]+)\s*(words?|tokens?)?\s*$/) { | ||
| 461 | my $words = $1; | ||
| 462 | return sub { | ||
| 463 | my ($first, $last) = @_; | ||
| 464 | return ($last-$first) <= $words; | ||
| 465 | } | ||
| 466 | } | ||
| 467 | elsif ($context =~ /^\s*([0-9]*)\s*([A-Za-z\xc0-\xff_-]+)\s*$/) { | ||
| 468 | my ($nr, $env) = ($1, $2); # size is $nr <$env>...</$env> regions | ||
| 469 | $nr = 1 if $nr eq ""; # "s" means "1 s" | ||
| 470 | my $att = $self->{'ch'}->attribute($env, 's'); | ||
| 471 | $self->error("Invalid match size '$context'.", "(no <$env> regions in corpus)") | ||
| 472 | unless defined $att; | ||
| 473 | return sub { | ||
| 474 | my ($first, $last) = $att->cpos2struc(@_); | ||
| 475 | return (defined $first and defined $last and ($last-$first) < $nr); | ||
| 476 | } | ||
| 477 | } | ||
| 478 | else { | ||
| 479 | $self->error("Invalid match size '$context'."); | ||
| 480 | } | ||
| 481 | } | ||
| 482 | |||
| 483 | # create context expansion subroutine | ||
| 484 | # Usage: $coderef = make_expand_sub("s"); | ||
| 485 | # ($from, $to) = &$coderef($first, $last); | ||
| 486 | sub make_expand_sub { | ||
| 487 | my ($self, $context) = @_; | ||
| 488 | if ($context =~ /^\s*([0-9]+)\s*(words?|tokens?)?\s*$/) { | ||
| 489 | my $words = $1; | ||
| 490 | my $size = $self->{'word'}->max_cpos; | ||
| 491 | return sub { | ||
| 492 | my ($first, $last) = @_; | ||
| 493 | $first -= $words; $last += $words; | ||
| 494 | $first = 0 if $first < 0; | ||
| 495 | $last = $size - 1 if $last >= $size; | ||
| 496 | return ($first, $last); | ||
| 497 | } | ||
| 498 | } | ||
| 499 | elsif ($context =~ /^\s*([0-9]*)\s*([A-Za-z\xc0-\xff_-]+)\s*$/) { | ||
| 500 | my ($nr, $env) = ($1, $2); # size is $nr <$env>...</$env> regions | ||
| 501 | $nr = 1 if $nr eq ""; # "s" means "1 s" | ||
| 502 | my $att = $self->{'ch'}->attribute($env, 's'); | ||
| 503 | my $size = $att->max_struc; | ||
| 504 | $self->error("Invalid context size '$context'.", "(no <$env> regions in corpus)") | ||
| 505 | unless defined $att; | ||
| 506 | return sub { | ||
| 507 | my ($first, $last) = @_; | ||
| 508 | my $dummy; | ||
| 509 | my $struc = $att->cpos2struc($first); | ||
| 510 | if (defined $struc) { | ||
| 511 | $struc -= $nr - 1; | ||
| 512 | $struc = 0 if $struc < 0; | ||
| 513 | ($first, $dummy) = $att->struc2cpos($struc); | ||
| 514 | } | ||
| 515 | $struc = $att->cpos2struc($last); | ||
| 516 | if (defined $struc) { | ||
| 517 | $struc += $nr - 1; | ||
| 518 | $struc = $size - 1 if $struc >= $size; | ||
| 519 | ($dummy, $last) = $att->struc2cpos($struc); | ||
| 520 | } | ||
| 521 | return ($first, $last); | ||
| 522 | } | ||
| 523 | } | ||
| 524 | else { | ||
| 525 | $self->error("Invalid context size '$context'."); | ||
| 526 | } | ||
| 527 | } | ||
| 528 | |||
| 529 | # search engine settings: search window | ||
| 530 | sub window { | ||
| 531 | my $self = shift; | ||
| 532 | croak 'Usage: $s->window($window_size);' | ||
| 533 | unless @_ == 1; | ||
| 534 | my $window = shift; | ||
| 535 | $self->{'check_size'} = $self->make_check_size_sub($window); | ||
| 536 | } | ||
| 537 | |||
| 538 | # search engine settings: context returned | ||
| 539 | sub context { | ||
| 540 | my $self = shift; | ||
| 541 | croak 'Usage: $s->context($context_size);' | ||
| 542 | unless @_ == 1; | ||
| 543 | my $context = shift; | ||
| 544 | $self->{'expand'} = $self->make_expand_sub($context); | ||
| 545 | } | ||
| 546 | |||
| 547 | # regex flags settings: ignore case / ignore diacritics | ||
| 548 | sub ignore_case { | ||
| 549 | my $self = shift; | ||
| 550 | my $val = lc shift; | ||
| 551 | if ($val =~ /^[01]$/) { | ||
| 552 | carp "Usage is now: \$s->ignore_case('always'|'auto'|'never');"; | ||
| 553 | $val = ($val) ? 'always' : 'never'; | ||
| 554 | } | ||
| 555 | croak "Usage: \$s->ignore_case('always'|'auto'|'never');" | ||
| 556 | unless $val =~ /^(always|auto|never)$/; | ||
| 557 | $self->{'ignore_case'} = $val; | ||
| 558 | } | ||
| 559 | |||
| 560 | sub ignore_diacritics { | ||
| 561 | my $self = shift; | ||
| 562 | my $val = lc shift; | ||
| 563 | if ($val =~ /^[01]$/) { | ||
| 564 | carp "Usage is now: \$s->ignore_diacritics('always'|'auto'|'never');"; | ||
| 565 | $val = ($val) ? 'always' : 'never'; | ||
| 566 | } | ||
| 567 | croak "Usage: \$s->ignore_diacritics('always'|'auto'|'never');" | ||
| 568 | unless $val =~ /^(always|auto|never)$/; | ||
| 569 | $self->{'ignore_diac'} = $val; | ||
| 570 | } | ||
| 571 | |||
| 572 | # select culling strategy | ||
| 573 | sub cull { | ||
| 574 | my $self = shift; | ||
| 575 | my $method = shift; | ||
| 576 | croak "Usage: \$search->cull('never' | 'before' | 'after');" | ||
| 577 | unless defined $method and ($method = lc $method) =~ /^(never|before|after)$/; | ||
| 578 | $self->{'cull'} = $method; | ||
| 579 | } | ||
| 580 | |||
| 581 | # set preferred environments | ||
| 582 | sub preferred { | ||
| 583 | my $self = shift; | ||
| 584 | my $ch = $self->{'ch'}; | ||
| 585 | my @env = @_; | ||
| 586 | my @att = (); # compile list of s-attribute handles | ||
| 587 | foreach my $env (@env) { | ||
| 588 | croak "Usage: \$search->preferred(\$region_name, ... );" | ||
| 589 | unless $env =~ /^[A-Za-z0-9_-]+$/; | ||
| 590 | my $att = $ch->attribute($env, 's'); | ||
| 591 | $self->error("Preferred environment: no <$env>..</$env> regions in corpus.") | ||
| 592 | unless defined $att; | ||
| 593 | push @att, $att; | ||
| 594 | } | ||
| 595 | $self->{'preferred'} = [@att]; | ||
| 596 | } | ||
| 597 | |||
| 598 | # HTML tag used for keyword highlighting (open tag, with optional attributes) | ||
| 599 | sub highlight { | ||
| 600 | my $self = shift; | ||
| 601 | my $tag = shift; | ||
| 602 | croak 'Usage: $search->highlight($open_tag);' | ||
| 603 | unless defined $tag and $tag =~ /^<([A-Za-z0-9_-]+)(\s.*>|>)$/; | ||
| 604 | my $name = $1; | ||
| 605 | $self->{'hlstart'} = $tag; | ||
| 606 | $self->{'hlend'} = "</$name>"; | ||
| 607 | } | ||
| 608 | |||
| 609 | # search engine settings: data (region values) | ||
| 610 | sub data { | ||
| 611 | my $self = shift; | ||
| 612 | croak 'Usage: $search->data($att1, ...);' | ||
| 613 | unless @_ > 0; | ||
| 614 | my %atts = (); # will be stored in $self->{'data'} field | ||
| 615 | foreach my $att (@_) { | ||
| 616 | my $att_handle = $self->{'ch'}->attribute($att, 's'); | ||
| 617 | $self->error("Data attribute '$att' does not exist.") | ||
| 618 | unless defined $att_handle; | ||
| 619 | $self->error("Data attribute '$att' has no annotated values.") | ||
| 620 | unless $att_handle->struc_values; | ||
| 621 | $atts{$att} = $att_handle; | ||
| 622 | } | ||
| 623 | $self->{'data'} = \%atts; | ||
| 624 | } | ||
| 625 | |||
| 626 | # return number of matches found | ||
| 627 | sub size { | ||
| 628 | my $self = shift; | ||
| 629 | return $self->{'ml'}->size; | ||
| 630 | } | ||
| 631 | |||
| 632 | # return data for match (returns result struct) | ||
| 633 | sub match { | ||
| 634 | my $self = shift; | ||
| 635 | my $n = shift; | ||
| 636 | my $flag = shift; | ||
| 637 | croak "Usage: \$search->match(\$n [, 'context']);" | ||
| 638 | if defined $flag and (lc $flag ne 'context'); | ||
| 639 | |||
| 640 | my $word_att = $self->{'word'}; | ||
| 641 | my $start_tag = $self->{'hlstart'}; | ||
| 642 | my $end_tag = $self->{'hlend'}; | ||
| 643 | my $ml = $self->{'ml'}; | ||
| 644 | my $size = $ml->size; | ||
| 645 | return undef | ||
| 646 | unless $n >= 0 and $n < $size; | ||
| 647 | |||
| 648 | my $result = {}; # build result struct | ||
| 649 | my ($first, $last, $center, $variance, $quality, %keyword) = $ml->match($n); | ||
| 650 | $result->{'cpos'} = int ($center + 0.5); | ||
| 651 | $result->{'quality'} = $quality; | ||
| 652 | $result->{'summary'} = $ml->summarize($n, $word_att, $start_tag, $end_tag); | ||
| 653 | if (defined $flag) { | ||
| 654 | # build full match text (including context) | ||
| 655 | my @words = (); | ||
| 656 | foreach my $cpos ($first .. $last) { | ||
| 657 | my $token = encode_entities($word_att->cpos2str($cpos)); | ||
| 658 | $token = $start_tag.$token.$end_tag | ||
| 659 | if defined $keyword{$cpos}; | ||
| 660 | push @words, $token; | ||
| 661 | } | ||
| 662 | $result->{'context'} = "@words"; | ||
| 663 | } | ||
| 664 | foreach my $att (keys %{$self->{'data'}}) { | ||
| 665 | my $data = $self->{'data'}->{$att}->cpos2struc2str($center); | ||
| 666 | $result->{'data'}->{$att} = (defined $data) ? $data : ""; | ||
| 667 | } | ||
| 668 | |||
| 669 | return $result; | ||
| 670 | } | ||
| 671 | |||
| 672 | # front-end to the query function; parses query string entered by user | ||
| 673 | sub query_string { | ||
| 674 | my $self = shift; | ||
| 675 | croak "Usage \$search->query_string(\$string);" | ||
| 676 | unless @_ == 1; | ||
| 677 | my $query = shift; | ||
| 678 | |||
| 679 | # double quotes ("...") mark multi-word keys (exact match) | ||
| 680 | # -> convert spaces to underlines, so we don't split them when tokenising the string | ||
| 681 | while ($query =~ /(^|[^\\])\"(.*?[^\\])\"/) { | ||
| 682 | my ($pre, $multiword, $post) = ($`.$1, $2, $'); | ||
| 683 | # print "SUBST '$query' -> ($pre | $multiword | $post)\n"; | ||
| 684 | # if either one of the quot | ||
| 685 | $multiword =~ tr[ ][_]; | ||
| 686 | $query = $pre.$multiword.$post; | ||
| 687 | } | ||
| 688 | |||
| 689 | my @keywords = split " ", $query; | ||
| 690 | |||
| 691 | # a single keyword is implicitly required -- make that explicit (because of the | ||
| 692 | # special tricks for multi-word keys below) | ||
| 693 | if (@keywords == 1 and $keywords[0] !~ /^[+-]/) { | ||
| 694 | $keywords[0] = "+".$keywords[0]; | ||
| 695 | } | ||
| 696 | |||
| 697 | # now convert _ to SPC in multi-word keys, with extra post-processing | ||
| 698 | my @extra = (); | ||
| 699 | foreach my $keyword (@keywords) { | ||
| 700 | if ($keyword =~ /_/) { | ||
| 701 | $keyword =~ tr[_][ ]; | ||
| 702 | my @components = split " ", $keyword; | ||
| 703 | if ($keyword =~ /^\+/) { | ||
| 704 | # only the last token in a multi-word key is added to the set of keywords | ||
| 705 | # (for highlighting and match relevance); however, for required multi-word keys, | ||
| 706 | # we can add the other tokens as additional required keywords to the query | ||
| 707 | pop @components; # last token get's listed anyway | ||
| 708 | push @keywords, map {(/^\+/) ? "$_" : "+$_"} @components; # add other tokens explicitly | ||
| 709 | } | ||
| 710 | } | ||
| 711 | } | ||
| 712 | |||
| 713 | # now we can run the query with the tokenised list of keywords | ||
| 714 | return $self->query(@keywords); | ||
| 715 | } | ||
| 716 | |||
| 717 | # the search query function ... | ||
| 718 | sub query { | ||
| 719 | my $self = shift; | ||
| 720 | $self->error("No search keywords specified.") | ||
| 721 | unless @_; | ||
| 722 | my @required_keywords = grep {/^\+/} @_; # +computer => required keyword | ||
| 723 | my @excluded_keywords = grep {/^-/} @_; # -windows => must _not_ be in match | ||
| 724 | my @optional_keywords = grep {not /^[-+]/} @_; # the remaining keywords are optional | ||
| 725 | map {s/^\+//;} @required_keywords; # remove '+' and '-' marks | ||
| 726 | map {s/^-//;} @excluded_keywords; | ||
| 727 | my $no_of_keywords = @required_keywords + @optional_keywords; # max. no of keywords in a match | ||
| 728 | $self->error("Query containing only negative constraints not allowed.") | ||
| 729 | unless $no_of_keywords > 0; | ||
| 730 | |||
| 731 | # reset matchlist | ||
| 732 | my $ml = $self->{'ml'} = new CWB::Web::Search::MatchList; | ||
| 733 | my @list = (); # list of current keyword's corpus positions | ||
| 734 | my $keyword = ""; # keyword we're currently processing | ||
| 735 | |||
| 736 | my $has_required_keywords = @required_keywords > 0; | ||
| 737 | |||
| 738 | # start with required keywords (if there are any) | ||
| 739 | if ($has_required_keywords) { | ||
| 740 | $keyword = shift @required_keywords; | ||
| 741 | $ml->constraint("join", $keyword, $self->{'check_size'}, | ||
| 742 | $self->get_positions($keyword)); # initial matchlist (add to empty list) | ||
| 743 | foreach $keyword (@required_keywords) { | ||
| 744 | $ml->constraint('positive', $keyword, $self->{'check_size'}, | ||
| 745 | $self->get_positions($keyword)); | ||
| 746 | } | ||
| 747 | } | ||
| 748 | # add optional keywords now | ||
| 749 | foreach $keyword (@optional_keywords) { | ||
| 750 | if ($has_required_keywords) { | ||
| 751 | # if there were any required keywords, optional keywords can | ||
| 752 | # only be adjoined to the existing matches | ||
| 753 | $ml->constraint('optional', $keyword, $self->{'check_size'}, | ||
| 754 | $self->get_positions($keyword)); | ||
| 755 | } | ||
| 756 | else { | ||
| 757 | # otherwise, optional keywords may introduce new matches | ||
| 758 | $ml->constraint('join', $keyword, $self->{'check_size'}, | ||
| 759 | $self->get_positions($keyword)); | ||
| 760 | } | ||
| 761 | } | ||
| 762 | # finally, apply excluded keywords | ||
| 763 | foreach $keyword (@excluded_keywords) { | ||
| 764 | $ml->constraint('negative', $keyword, $self->{'check_size'}, | ||
| 765 | $self->get_positions($keyword)); | ||
| 766 | } | ||
| 767 | |||
| 768 | # now, compute quality, expand the match list & sort it | ||
| 769 | $ml->compute_quality($no_of_keywords, @{$self->{'preferred'}}); | ||
| 770 | if ($self->{'cull'} eq 'before') { | ||
| 771 | $ml->sort('first'); | ||
| 772 | $ml->cull; | ||
| 773 | } | ||
| 774 | $ml->expand($self->{'expand'}); | ||
| 775 | if ($self->{'cull'} eq 'after') { | ||
| 776 | $ml->sort('first'); | ||
| 777 | $ml->cull; | ||
| 778 | } | ||
| 779 | $ml->sort('quality'); | ||
| 780 | |||
| 781 | # finally, return number of matches | ||
| 782 | return $ml->size; | ||
| 783 | } | ||
| 784 | |||
| 785 | # internal method: get IDs (word OR lemma) matching given keyword | ||
| 786 | # returns ($attribute, @id_list) | ||
| 787 | sub get_IDs { | ||
| 788 | my $self = shift; | ||
| 789 | my $keyword = shift; | ||
| 790 | |||
| 791 | my $word_att = $self->{'word'}; | ||
| 792 | my $lemma_att = $self->{'lemma'}; | ||
| 793 | my $flags = ''; # construct ignore case/diacritics flags for regex2id() | ||
| 794 | if (($self->{'ignore_case'} eq 'always') or | ||
| 795 | ($self->{'ignore_case'} eq 'auto' and $keyword !~ /[A-Z\xc0-\xd6\xd8-\xde]/)) { | ||
| 796 | $flags .= 'c'; | ||
| 797 | } | ||
| 798 | if (($self->{'ignore_diac'} eq 'always') or | ||
| 799 | ($self->{'ignore_diac'} eq 'auto' and $keyword !~ /[\xc0-\xd6\xd8-\xf6\xf8-\xff]/)) { | ||
| 800 | $flags .= 'd'; | ||
| 801 | } | ||
| 802 | |||
| 803 | if (not $flags and $keyword =~ /^[A-za-z0-9\xc0-\xff_-]+$/) { | ||
| 804 | # regular word -> look up in index (use lemma attribute if possible) | ||
| 805 | my $lemma_id = $lemma_att->str2id($keyword); | ||
| 806 | my $word_id = $word_att->str2id($keyword); | ||
| 807 | my $lemma_freq = (defined $lemma_id) ? $lemma_att->id2freq($lemma_id) : 0; | ||
| 808 | my $word_freq = (defined $word_id) ? $word_att->id2freq($word_id) : 0; | ||
| 809 | if ($lemma_freq > $word_freq) { | ||
| 810 | # user entered lemma form -> look up in lemma index | ||
| 811 | return ($lemma_att, $lemma_id); | ||
| 812 | # NB: $lemma_id must be defined because $lemma_freq > 0 | ||
| 813 | } | ||
| 814 | else { | ||
| 815 | if ($word_freq > 0) { | ||
| 816 | # user entered an inflected form or incorrect lemma | ||
| 817 | # the word form was found in the corpus, so let's try to lemmatise it | ||
| 818 | my @cpos = $word_att->idlist2cpos($word_id); | ||
| 819 | my %lemma_id = (); # collect lemma ID's cooccuring with word form | ||
| 820 | for (my $i = 0; $i < @cpos and $i < 100; $i++) { # try first 100 occurrences only | ||
| 821 | $lemma_id{$lemma_att->cpos2id($cpos[$i])} = 1; | ||
| 822 | } | ||
| 823 | my @lemma_ids = grep {$lemma_att->id2str($_) ne "<unknown>"} keys %lemma_id; | ||
| 824 | if (@lemma_ids) { | ||
| 825 | # we've found one or more possible lemmatisations -> pick most frequent one | ||
| 826 | ($lemma_id) = sort {$lemma_att->id2freq($b) <=> $lemma_att->id2freq($a)} @lemma_ids; | ||
| 827 | $lemma_freq = $lemma_att->id2freq($lemma_id); | ||
| 828 | # now check again if lemma is more 'general' than word form | ||
| 829 | if ($lemma_freq > $word_freq) { | ||
| 830 | return ($lemma_att, $lemma_id); | ||
| 831 | } | ||
| 832 | } | ||
| 833 | # if lemmatisation attempt failed, fall back on word form | ||
| 834 | return ($word_att, $word_id); | ||
| 835 | } | ||
| 836 | else { | ||
| 837 | # not in corpus; return word attribute with empty ID list | ||
| 838 | return ($word_att); | ||
| 839 | } | ||
| 840 | } | ||
| 841 | } | ||
| 842 | else { | ||
| 843 | # regular expression -> match on lemma or word forms | ||
| 844 | # (if ignore case/diacritics was requested, we must always use regexps) | ||
| 845 | my @lemma_ids = $lemma_att->regex2id($keyword, $flags); | ||
| 846 | my @word_ids = $word_att->regex2id($keyword, $flags); | ||
| 847 | my $lemma_freq = $lemma_att->idlist2freq(@lemma_ids); | ||
| 848 | my $word_freq = $word_att->idlist2freq(@word_ids); | ||
| 849 | if ($lemma_freq > $word_freq) { | ||
| 850 | return ($lemma_att, @lemma_ids); | ||
| 851 | } | ||
| 852 | else { | ||
| 853 | return ($word_att, @word_ids); | ||
| 854 | } | ||
| 855 | } | ||
| 856 | |||
| 857 | |||
| 858 | } | ||
| 859 | |||
| 860 | # internal method: get positions of a given keyword | ||
| 861 | sub get_positions { | ||
| 862 | my $self = shift; | ||
| 863 | my $keyword = shift; | ||
| 864 | my ($attribute, @id_list); | ||
| 865 | |||
| 866 | if ($keyword =~ /\s+/) { | ||
| 867 | # keyword contains blanks -> multi-word string | ||
| 868 | my (@keywords) = split /\s+/, $keyword; | ||
| 869 | $keyword = shift @keywords; # match first keyword | ||
| 870 | ($attribute, @id_list) = $self->get_IDs($keyword); | ||
| 871 | my @cpos_list = $attribute->idlist2cpos(@id_list); | ||
| 872 | foreach $keyword (@keywords) { | ||
| 873 | ($attribute, @id_list) = $self->get_IDs($keyword); | ||
| 874 | my %matches_keyword = map {($_ => 1)} @id_list; # make lookup hash for matching IDs | ||
| 875 | foreach my $cpos (@cpos_list) { | ||
| 876 | my $id = $attribute->cpos2id($cpos+1); | ||
| 877 | if (defined $id and $matches_keyword{$id}) { | ||
| 878 | $cpos = $cpos + 1; # tokens in multi-word string must be adjacent ... | ||
| 879 | } | ||
| 880 | else { | ||
| 881 | $id = $attribute->cpos2id($cpos+2); | ||
| 882 | if (defined $id and $matches_keyword{$id}) { | ||
| 883 | $cpos = $cpos + 2; # ... allowing at most 1 intervening corpus position | ||
| 884 | } | ||
| 885 | else { | ||
| 886 | $cpos = -1; # delete this candidate | ||
| 887 | } | ||
| 888 | } | ||
| 889 | } | ||
| 890 | @cpos_list = grep {$_ >= 0} @cpos_list; # remove deleted candidates from list | ||
| 891 | } | ||
| 892 | return @cpos_list; | ||
| 893 | } | ||
| 894 | else { | ||
| 895 | ($attribute, @id_list) = $self->get_IDs($keyword); | ||
| 896 | return $attribute->idlist2cpos(@id_list); | ||
| 897 | } | ||
| 898 | } | ||
| 899 | |||
| 900 | |||
| 901 | |||
| 902 | return 1; | ||
| 903 | |||
| 904 | __END__ | ||