| 1 |
package KinoSearch1::Highlight::Highlighter; |
| 2 |
use strict; |
| 3 |
use warnings; |
| 4 |
use KinoSearch1::Util::ToolSet; |
| 5 |
use base qw( KinoSearch1::Util::Class ); |
| 6 |
use locale; |
| 7 |
|
| 8 |
BEGIN { |
| 9 |
__PACKAGE__->init_instance_vars( |
| 10 |
# constructor params / members |
| 11 |
excerpt_field => undef, |
| 12 |
analyzer => undef, |
| 13 |
formatter => undef, |
| 14 |
encoder => undef, |
| 15 |
terms => undef, |
| 16 |
excerpt_length => 200, |
| 17 |
pre_tag => undef, # back compat |
| 18 |
post_tag => undef, # back compat |
| 19 |
token_re => qr/\b\w+(?:'\w+)?\b/, |
| 20 |
|
| 21 |
# members |
| 22 |
limit => undef, |
| 23 |
); |
| 24 |
__PACKAGE__->ready_get_set(qw( terms )); |
| 25 |
} |
| 26 |
|
| 27 |
use KinoSearch1::Highlight::SimpleHTMLFormatter; |
| 28 |
use KinoSearch1::Highlight::SimpleHTMLEncoder; |
| 29 |
|
| 30 |
sub init_instance { |
| 31 |
my $self = shift; |
| 32 |
croak("Missing required arg 'excerpt_field'") |
| 33 |
unless defined $self->{excerpt_field}; |
| 34 |
$self->{terms} = []; |
| 35 |
|
| 36 |
# assume HTML |
| 37 |
if ( !defined $self->{encoder} ) { |
| 38 |
$self->{encoder} = KinoSearch1::Highlight::SimpleHTMLEncoder->new; |
| 39 |
} |
| 40 |
if ( !defined $self->{formatter} ) { |
| 41 |
my ( $pre_tag, $post_tag ) = @{$self}{qw( pre_tag post_tag )}; |
| 42 |
$pre_tag = '<strong>' unless defined $pre_tag; |
| 43 |
$post_tag = '</strong>' unless defined $post_tag; |
| 44 |
$self->{formatter} = KinoSearch1::Highlight::SimpleHTMLFormatter->new( |
| 45 |
pre_tag => $pre_tag, |
| 46 |
post_tag => $post_tag, |
| 47 |
); |
| 48 |
} |
| 49 |
|
| 50 |
# scoring window is 1.66 * excerpt_length, with the loc in the middle |
| 51 |
$self->{limit} = int( $self->{excerpt_length} / 3 ); |
| 52 |
} |
| 53 |
|
| 54 |
sub generate_excerpt { |
| 55 |
my ( $self, $doc ) = @_; |
| 56 |
my $excerpt_length = $self->{excerpt_length}; |
| 57 |
my $limit = $self->{limit}; |
| 58 |
my $token_re = $self->{token_re}; |
| 59 |
|
| 60 |
# retrieve the text from the chosen field |
| 61 |
my $field = $doc->get_field( $self->{excerpt_field} ); |
| 62 |
my $text = $field->get_value; |
| 63 |
my $text_length = bytes::length $text; |
| 64 |
return '' unless $text_length; |
| 65 |
|
| 66 |
# determine the rough boundaries of the excerpt |
| 67 |
my $posits = $self->_starts_and_ends($field); |
| 68 |
my $best_location = $self->_calc_best_location($posits); |
| 69 |
my $top = $best_location - $limit; |
| 70 |
|
| 71 |
# expand the excerpt if the best location is near the end |
| 72 |
$top |
| 73 |
= $text_length - $excerpt_length < $top |
| 74 |
? $text_length - $excerpt_length |
| 75 |
: $top; |
| 76 |
|
| 77 |
# if the best starting point is the very beginning, cool... |
| 78 |
if ( $top <= 0 ) { |
| 79 |
$top = 0; |
| 80 |
} |
| 81 |
# ... otherwise ... |
| 82 |
else { |
| 83 |
# lop off $top bytes |
| 84 |
$text = bytes::substr( $text, $top ); |
| 85 |
|
| 86 |
# try to start the excerpt at a sentence boundary |
| 87 |
if ($text =~ s/ |
| 88 |
\A |
| 89 |
( |
| 90 |
\C{0,$limit}? |
| 91 |
\.\s+ |
| 92 |
) |
| 93 |
//xsm |
| 94 |
) |
| 95 |
{ |
| 96 |
$top += bytes::length($1); |
| 97 |
} |
| 98 |
# no sentence boundary, so we'll need an ellipsis |
| 99 |
else { |
| 100 |
# skip past possible partial tokens, prepend an ellipsis |
| 101 |
if ($text =~ s/ |
| 102 |
\A |
| 103 |
( |
| 104 |
\C{0,$limit}? # don't go outside the window |
| 105 |
$token_re # match possible partial token |
| 106 |
.*? # ... and any junk following that token |
| 107 |
) |
| 108 |
(?=$token_re) # just before the start of a full token... |
| 109 |
/... /xsm # ... insert an ellipsis |
| 110 |
) |
| 111 |
{ |
| 112 |
$top += bytes::length($1); |
| 113 |
$top -= 4 # three dots and a space |
| 114 |
} |
| 115 |
} |
| 116 |
} |
| 117 |
|
| 118 |
# remove possible partial tokens from the end of the excerpt |
| 119 |
$text = bytes::substr( $text, 0, $excerpt_length + 1 ); |
| 120 |
if ( bytes::length($text) > $excerpt_length ) { |
| 121 |
my $extra_char = chop $text; |
| 122 |
# if the extra char wasn't part of a token, we aren't splitting one |
| 123 |
if ( $extra_char =~ $token_re ) { |
| 124 |
$text =~ s/$token_re$//; # if this is unsuccessful, that's fine |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
# if the excerpt doesn't end with a full stop, end with an an ellipsis |
| 129 |
if ( $text !~ /\.\s*\Z/xsm ) { |
| 130 |
$text =~ s/\W+\Z//xsm; |
| 131 |
while ( bytes::length($text) + 4 > $excerpt_length ) { |
| 132 |
my $extra_char = chop $text; |
| 133 |
if ( $extra_char =~ $token_re ) { |
| 134 |
$text =~ s/\W+$token_re\Z//xsm; # if unsuccessful, that's fine |
| 135 |
} |
| 136 |
$text =~ s/\W+\Z//xsm; |
| 137 |
} |
| 138 |
$text .= ' ...'; |
| 139 |
} |
| 140 |
|
| 141 |
# remap locations now that we know the starting and ending bytes |
| 142 |
$text_length = bytes::length($text); |
| 143 |
my @relative_starts = map { $_->[0] - $top } @$posits; |
| 144 |
my @relative_ends = map { $_->[1] - $top } @$posits; |
| 145 |
|
| 146 |
# get rid of pairs with at least one member outside the text |
| 147 |
while ( @relative_starts and $relative_starts[0] < 0 ) { |
| 148 |
shift @relative_starts; |
| 149 |
shift @relative_ends; |
| 150 |
} |
| 151 |
while ( @relative_ends and $relative_ends[-1] > $text_length ) { |
| 152 |
pop @relative_starts; |
| 153 |
pop @relative_ends; |
| 154 |
} |
| 155 |
|
| 156 |
# insert highlight tags |
| 157 |
my $formatter = $self->{formatter}; |
| 158 |
my $encoder = $self->{encoder}; |
| 159 |
my $output_text = ''; |
| 160 |
my ( $start, $end, $last_start, $last_end ) = ( undef, undef, 0, 0 ); |
| 161 |
while (@relative_starts) { |
| 162 |
$end = shift @relative_ends; |
| 163 |
$start = shift @relative_starts; |
| 164 |
$output_text .= $encoder->encode( |
| 165 |
bytes::substr( $text, $last_end, $start - $last_end ) ); |
| 166 |
$output_text |
| 167 |
.= $formatter->highlight( |
| 168 |
$encoder->encode( bytes::substr( $text, $start, $end - $start ) ) |
| 169 |
); |
| 170 |
$last_end = $end; |
| 171 |
} |
| 172 |
$output_text .= $encoder->encode( bytes::substr( $text, $last_end ) ); |
| 173 |
|
| 174 |
return $output_text; |
| 175 |
} |
| 176 |
|
| 177 |
=for comment |
| 178 |
Find all points in the text where a relevant term begins and ends. For terms |
| 179 |
that are part of a phrase, only include points that are part of the phrase. |
| 180 |
|
| 181 |
=cut |
| 182 |
|
| 183 |
sub _starts_and_ends { |
| 184 |
my ( $self, $field ) = @_; |
| 185 |
my @posits; |
| 186 |
my %done; |
| 187 |
|
| 188 |
TERM: for my $term ( @{ $self->{terms} } ) { |
| 189 |
if ( a_isa_b( $term, 'KinoSearch1::Index::Term' ) ) { |
| 190 |
my $term_text = $term->get_text; |
| 191 |
|
| 192 |
next TERM if $done{$term_text}; |
| 193 |
$done{$term_text} = 1; |
| 194 |
|
| 195 |
# add all starts and ends |
| 196 |
my $term_vector = $field->term_vector($term_text); |
| 197 |
next TERM unless defined $term_vector; |
| 198 |
my $starts = $term_vector->get_start_offsets; |
| 199 |
my $ends = $term_vector->get_end_offsets; |
| 200 |
while (@$starts) { |
| 201 |
push @posits, [ shift @$starts, shift @$ends, 1 ]; |
| 202 |
} |
| 203 |
} |
| 204 |
# intersect positions for phrase terms |
| 205 |
else { |
| 206 |
# if not a Term, it's an array of Terms representing a phrase |
| 207 |
my @term_texts = map { $_->get_text } @$term; |
| 208 |
|
| 209 |
my $phrase_text = join( ' ', @term_texts ); |
| 210 |
next TERM if $done{$phrase_text}; |
| 211 |
$done{$phrase_text} = 1; |
| 212 |
|
| 213 |
my $posit_vec = KinoSearch1::Util::BitVector->new; |
| 214 |
my @term_vectors = map { $field->term_vector($_) } @term_texts; |
| 215 |
|
| 216 |
# make sure all terms are present |
| 217 |
next TERM unless scalar @term_vectors == scalar @term_texts; |
| 218 |
|
| 219 |
my $i = 0; |
| 220 |
for my $tv (@term_vectors) { |
| 221 |
# one term missing, ergo no phrase |
| 222 |
next TERM unless defined $tv; |
| 223 |
if ( $i == 0 ) { |
| 224 |
$posit_vec->set( @{ $tv->get_positions } ); |
| 225 |
} |
| 226 |
else { |
| 227 |
# filter positions using logical "and" |
| 228 |
my $other_posit_vec = KinoSearch1::Util::BitVector->new; |
| 229 |
$other_posit_vec->set( |
| 230 |
grep { $_ >= 0 } |
| 231 |
map { $_ - $i } @{ $tv->get_positions } |
| 232 |
); |
| 233 |
$posit_vec->logical_and($other_posit_vec); |
| 234 |
} |
| 235 |
$i++; |
| 236 |
} |
| 237 |
|
| 238 |
# add only those starts/ends that belong to a valid position |
| 239 |
my $tv_start_positions = $term_vectors[0]->get_positions; |
| 240 |
my $tv_starts = $term_vectors[0]->get_start_offsets; |
| 241 |
my $tv_end_positions = $term_vectors[-1]->get_positions; |
| 242 |
my $tv_ends = $term_vectors[-1]->get_end_offsets; |
| 243 |
$i = 0; |
| 244 |
my $j = 0; |
| 245 |
my $last_token_index = $#term_vectors; |
| 246 |
for my $valid_position ( @{ $posit_vec->to_arrayref } ) { |
| 247 |
|
| 248 |
while ( $i <= $#$tv_start_positions ) { |
| 249 |
last if ( $tv_start_positions->[$i] >= $valid_position ); |
| 250 |
$i++; |
| 251 |
} |
| 252 |
$valid_position += $last_token_index; |
| 253 |
while ( $j <= $#$tv_end_positions ) { |
| 254 |
last if ( $tv_end_positions->[$j] >= $valid_position ); |
| 255 |
$j++; |
| 256 |
} |
| 257 |
push @posits, |
| 258 |
[ $tv_starts->[$i], $tv_ends->[$j], scalar @$term ]; |
| 259 |
$i++; |
| 260 |
$j++; |
| 261 |
} |
| 262 |
} |
| 263 |
} |
| 264 |
|
| 265 |
# sort, uniquify and return |
| 266 |
@posits = sort { $a->[0] <=> $b->[0] || $b->[1] <=> $a->[1] } @posits; |
| 267 |
my @unique; |
| 268 |
my $last = ~0; |
| 269 |
for (@posits) { |
| 270 |
push @unique, $_ if $_->[0] != $last; |
| 271 |
$last = $_->[0]; |
| 272 |
} |
| 273 |
return \@unique; |
| 274 |
} |
| 275 |
|
| 276 |
=for comment |
| 277 |
Select the byte address representing the greatest keyword density. Because |
| 278 |
the algorithm counts bytes rather than characters, it will degrade if the |
| 279 |
number of bytes per character is larger than 1. |
| 280 |
|
| 281 |
=cut |
| 282 |
|
| 283 |
sub _calc_best_location { |
| 284 |
my ( $self, $posits ) = @_; |
| 285 |
my $window = $self->{limit} * 2; |
| 286 |
|
| 287 |
# if there aren't any keywords, take the excerpt from the top of the text |
| 288 |
return 0 unless @$posits; |
| 289 |
|
| 290 |
my %locations = map { ( $_->[0] => 0 ) } @$posits; |
| 291 |
|
| 292 |
# if another keyword is in close proximity, add to the loc's score |
| 293 |
for my $loc_index ( 0 .. $#$posits ) { |
| 294 |
# only score positions that are in range |
| 295 |
my $location = $posits->[$loc_index][0]; |
| 296 |
my $other_loc_index = $loc_index - 1; |
| 297 |
while ( $other_loc_index > 0 ) { |
| 298 |
my $diff = $location - $posits->[$other_loc_index][0]; |
| 299 |
last if $diff > $window; |
| 300 |
my $num_tokens_at_pos = $posits->[$other_loc_index][2]; |
| 301 |
$locations{$location} |
| 302 |
+= ( 1 / ( 1 + log($diff) ) ) * $num_tokens_at_pos; |
| 303 |
--$other_loc_index; |
| 304 |
} |
| 305 |
$other_loc_index = $loc_index + 1; |
| 306 |
while ( $other_loc_index <= $#$posits ) { |
| 307 |
my $diff = $posits->[$other_loc_index] - $location; |
| 308 |
last if $diff > $window; |
| 309 |
my $num_tokens_at_pos = $posits->[$other_loc_index][2]; |
| 310 |
$locations{$location} |
| 311 |
+= ( 1 / ( 1 + log($diff) ) ) * $num_tokens_at_pos; |
| 312 |
++$other_loc_index; |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
# return the highest scoring position |
| 317 |
return ( sort { $locations{$b} <=> $locations{$a} } keys %locations )[0]; |
| 318 |
} |
| 319 |
|
| 320 |
1; |
| 321 |
|
| 322 |
__END__ |
| 323 |
|
| 324 |
=head1 NAME |
| 325 |
|
| 326 |
KinoSearch1::Highlight::Highlighter - create and highlight excerpts |
| 327 |
|
| 328 |
=head1 SYNOPSIS |
| 329 |
|
| 330 |
my $highlighter = KinoSearch1::Highlight::Highlighter->new( |
| 331 |
excerpt_field => 'bodytext', |
| 332 |
); |
| 333 |
$hits->create_excerpts( highlighter => $highlighter ); |
| 334 |
|
| 335 |
=head1 DESCRIPTION |
| 336 |
|
| 337 |
KinoSearch1's Highlighter can be used to select a relevant snippet from a |
| 338 |
document, and to surround search terms with highlighting tags. It handles |
| 339 |
both stems and phrases correctly and efficiently, using special-purpose data |
| 340 |
generated at index-time. |
| 341 |
|
| 342 |
=head1 METHODS |
| 343 |
|
| 344 |
=head2 new |
| 345 |
|
| 346 |
my $highlighter = KinoSearch1::Highlight::Highlighter->new( |
| 347 |
excerpt_field => 'bodytext', # required |
| 348 |
excerpt_length => 150, # default: 200 |
| 349 |
formatter => $formatter, # default: SimpleHTMLFormatter |
| 350 |
encoder => $encoder, # default: SimpleHTMLEncoder |
| 351 |
); |
| 352 |
|
| 353 |
Constructor. Takes hash-style parameters: |
| 354 |
|
| 355 |
=over |
| 356 |
|
| 357 |
=item * |
| 358 |
|
| 359 |
B<excerpt_field> - the name of the field from which to draw the excerpt. This |
| 360 |
field B<must> be C<vectorized>. |
| 361 |
|
| 362 |
=item * |
| 363 |
|
| 364 |
B<excerpt_length> - the length of the excerpt, in I<bytes>. This should |
| 365 |
probably use characters as a unit instead of bytes, and the behavior is likely |
| 366 |
to change in the future. |
| 367 |
|
| 368 |
=item * |
| 369 |
|
| 370 |
B<formatter> - an object which subclasses L<KinoSearch1::Highlight::Formatter>, |
| 371 |
used to perform the actual highlighting. |
| 372 |
|
| 373 |
=item * |
| 374 |
|
| 375 |
B<encoder> - an object which subclasses L<KinoSearch1::Highlight::Encoder>. |
| 376 |
All excerpt text gets passed through the encoder, including highlighted terms. |
| 377 |
By default, this is a SimpleHTMLEncoder, which encodes HTML entities. |
| 378 |
|
| 379 |
=item * |
| 380 |
|
| 381 |
B<pre_tag> - deprecated. |
| 382 |
|
| 383 |
=item * |
| 384 |
|
| 385 |
B<post_tag> - deprecated. |
| 386 |
|
| 387 |
=back |
| 388 |
|
| 389 |
=head1 COPYRIGHT |
| 390 |
|
| 391 |
Copyright 2005-2010 Marvin Humphrey |
| 392 |
|
| 393 |
=head1 LICENSE, DISCLAIMER, BUGS, etc. |
| 394 |
|
| 395 |
See L<KinoSearch1> version 1.01. |
| 396 |
|
| 397 |
=cut |