--- trunk/lib/WebPAC/Normalize.pm 2005/12/05 17:48:08 219 +++ trunk/lib/WebPAC/Normalize.pm 2006/06/29 21:52:51 544 @@ -1,678 +1,438 @@ package WebPAC::Normalize; +use Exporter 'import'; +@EXPORT = qw/ + _set_rec _set_lookup + _get_ds _clean_ds + + tag search display + marc21 + + rec1 rec2 rec + regex prefix suffix surround + first lookup join_with +/; use warnings; use strict; -use base 'WebPAC::Common'; + +#use base qw/WebPAC::Common/; use Data::Dumper; +use Encode qw/from_to/; =head1 NAME -WebPAC::Normalize - data mungling for normalisation +WebPAC::Normalize - describe normalisaton rules using sets =head1 VERSION -Version 0.04 +Version 0.06 =cut -our $VERSION = '0.04'; +our $VERSION = '0.06'; =head1 SYNOPSIS -This package contains code that mungle data to produce normalized format. - -It contains several assumptions: - -=over - -=item * - -format of fields is defined using C notation for repeatable fields -or C for single (or first) value, where C<123> is field number and -C is subfield. - -=item * - -source data records (C<$rec>) have unique identifiers in field C<000> - -=item * - -optional C tag at B will be -perl code that is evaluated before producing output (value of field will be -interpolated before that) - -=item * - -optional C at B will apply perl -code defined as code ref on format after field substitution to producing -output - -=item * - -optional C will be then performed. See C. - -=item * - -at end, optional Cs rules are resolved. Format rules are similar to -C and can also contain C which is performed after -values are inserted in format. - -=back - -This also describes order in which transformations are applied (eval, -filter, lookup, format) which is important to undestand when deciding how to -solve your data mungling and normalisation process. - - - +This module uses C files to perform normalisation +from input records using perl functions which are specialized for set +processing. + +Sets are implemented as arrays, and normalisation file is valid perl, which +means that you check it's validity before running WebPAC using +C. + +Normalisation can generate multiple output normalized data. For now, supported output +types (on the left side of definition) are: C, C, C and +C. =head1 FUNCTIONS -=head2 new +Functions which start with C<_> are private and used by WebPAC internally. +All other functions are available for use within normalisation rules. -Create new normalisation object +=head2 data_structure - my $n = new WebPAC::Normalize::Something( - filter => { - 'filter_name_1' => sub { - # filter code - return length($_); - }, ... - }, - db => $db_obj, - lookup_regex => $lookup->regex, - lookup => $lookup_obj, - prefix => 'foobar', +Return data structure + + my $ds = WebPAC::Normalize::data_structure( + lookup => $lookup->lookup_hash, + row => $row, + rules => $normalize_pl_config, + marc_encoding => 'utf-8', ); -Parametar C defines user supplied snippets of perl code which can -be use with C notation. +Options C, C, C and C are mandatory while all +other are optional. -C is used to form filename for database record (to support multiple -source files which are joined in one database). +This function will B if normalizastion can't be evaled. -Recommended parametar C is used to enable parsing of lookups -in structures. If you pass this parametar, you must also pass C -which is C object. +Since this function isn't exported you have to call it with +C. =cut -sub new { - my $class = shift; - my $self = {@_}; - bless($self, $class); - - my $r = $self->{'lookup_regex'} ? 1 : 0; - my $l = $self->{'lookup'} ? 1 : 0; - - my $log = $self->_get_logger(); - - # those two must be in pair - if ( ($r & $l) != ($r || $l) ) { - my $log = $self->_get_logger(); - $log->logdie("lookup_regex and lookup must be in pair"); - } +sub data_structure { + my $arg = {@_}; - $log->logdie("lookup must be WebPAC::Lookup object") if ($self->{'lookup'} && ! $self->{'lookup'}->isa('WebPAC::Lookup')); + die "need row argument" unless ($arg->{row}); + die "need normalisation argument" unless ($arg->{rules}); - $log->warn("no prefix defined. please check that!") unless ($self->{'prefix'}); + no strict 'subs'; + _set_lookup( $arg->{lookup} ); + _set_rec( $arg->{row} ); + _clean_ds( %{ $arg } ); + eval "$arg->{rules}"; + die "error evaling $arg->{rules}: $@\n" if ($@); - $self ? return $self : return undef; + return _get_ds(); } +=head2 _set_rec -=head2 data_structure - -Create in-memory data structure which represents normalized layout from -C. +Set current record hash -This structures are used to produce output. - - my $ds = $webpac->data_structure($rec); + _set_rec( $rec ); =cut -sub data_structure { - my $self = shift; +my $rec; - my $log = $self->_get_logger(); +sub _set_rec { + $rec = shift or die "no record hash"; +} - my $rec = shift; - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); +=head2 _get_ds - $log->debug("data_structure rec = ", sub { Dumper($rec) }); +Return hash formatted as data structure - $log->logdie("need unique ID (mfn) in field 000 of record ", sub { Dumper($rec) } ) unless (defined($rec->{'000'})); + my $ds = _get_ds(); - my $id = $rec->{'000'}->[0] || $log->logdie("field 000 isn't array!"); +=cut - my $cache_file; +my $out; +my $marc21; +my $marc_encoding; - if ($self->{'db'}) { - my $ds = $self->{'db'}->load_ds( id => $id, prefix => $self->{prefix} ); - $log->debug("load_ds( rec = ", sub { Dumper($rec) }, ") = ", sub { Dumper($ds) }); - return $ds if ($ds); - $log->debug("cache miss, creating"); - } +sub _get_ds { + return $out; +} - undef $self->{'currnet_filename'}; - undef $self->{'headline'}; +=head2 _clean_ds - my @sorted_tags; - if ($self->{tags_by_order}) { - @sorted_tags = @{$self->{tags_by_order}}; - } else { - @sorted_tags = sort { $self->_sort_by_order } keys %{$self->{'import_xml'}->{'indexer'}}; - $self->{tags_by_order} = \@sorted_tags; - } +Clean data structure hash for next record - my $ds; + _clean_ds(); - $log->debug("tags: ",sub { join(", ",@sorted_tags) }); +=cut - foreach my $field (@sorted_tags) { +sub _clean_ds { + my $a = {@_}; + $out = undef; + $marc21 = undef; + $marc_encoding = $a->{marc_encoding}; +} - my $row; +=head2 _set_lookup -#print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}); +Set current lookup hash - foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) { - my $format; + _set_lookup( $lookup ); - $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH'); - $format = $tag->{'value'} || $tag->{'content'}; +=cut - $log->debug("format: $format"); +my $lookup; - my @v; - if ($self->{'lookup_regex'} && $format =~ $self->{'lookup_regex'}) { - @v = $self->fill_in_to_arr($rec,$format); - } else { - @v = $self->parse_to_arr($rec,$format); - } - next if (! @v); +sub _set_lookup { + $lookup = shift; +} - if ($tag->{'sort'}) { - @v = $self->sort_arr(@v); - } +=head2 _get_marc21_fields - # use format? - if ($tag->{'format_name'}) { - @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v; - } +Get all fields defined by calls to C - # delimiter will join repeatable fields - if ($tag->{'delimiter'}) { - @v = ( join($tag->{'delimiter'}, @v) ); - } + $marc->add_fields( WebPAC::Normalize:_get_marc21_fields() ); - # default types - my @types = qw(display search); - # override by type attribute - @types = ( $tag->{'type'} ) if ($tag->{'type'}); - - foreach my $type (@types) { - # append to previous line? - $log->debug("type: $type ",sub { join(" ",@v) }, $row->{'append'} || 'no append'); - if ($tag->{'append'}) { - - # I will delimit appended part with - # delimiter (or ,) - my $d = $tag->{'delimiter'}; - # default delimiter - $d ||= " "; - - my $last = pop @{$row->{$type}}; - $d = "" if (! $last); - $last .= $d . join($d, @v); - push @{$row->{$type}}, $last; - - } else { - push @{$row->{$type}}, @v; - } - } - } +We are using I which detect repeatable fields only from +sequence of field/subfield data generated by normalization. - if ($row) { - $row->{'tag'} = $field; +Repeatable field is created if there is second occurence of same subfield or +if any of indicators are different. This is sane for most cases except for +non-repeatable fields with repeatable subfields. - # TODO: name_sigular, name_plural - my $name = $self->{'import_xml'}->{'indexer'}->{$field}->{'name'}; - my $row_name = $name ? $self->_x($name) : $field; - - # post-sort all values in field - if ($self->{'import_xml'}->{'indexer'}->{$field}->{'sort'}) { - $log->warn("sort at field tag not implemented"); - } +B: implement exceptions to magic - $ds->{$row_name} = $row; +=cut - $log->debug("row $field: ",sub { Dumper($row) }); +sub _get_marc21_fields { + my @m; + my $last; + foreach my $row (@{ $marc21 }) { + if ($last && + $last->[0] eq $row->[0] && # check if field is same + $last->[1] eq $row->[1] && # check for i1 + $last->[2] eq $row->[2] && # and for i2 + $last->[3] ne $row->[3] # and subfield is different + ) { + push @$last, ( $row->[3] , $row->[4] ); + warn "## ++ added $row->[0] ^$row->[3] to $last->[0]\n"; + next; + } elsif ($last) { + push @m, $last; } + $last = $row; } - $self->{'db'}->save_ds( - id => $id, - ds => $ds, - prefix => $self->{prefix}, - ) if ($self->{'db'}); - - $log->debug("ds: ", sub { Dumper($ds) }); - - $log->logconfess("data structure returned is not array any more!") if wantarray; - - return $ds; + push @m, $last if ($last); + return @m; } -=head2 parse - -Perform smart parsing of string, skipping delimiters for fields which aren't -defined. It can also eval code in format starting with C and -return output or nothing depending on eval code. +=head1 Functions to create C - my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i); - -=cut +Those functions generally have to first in your normalization file. -sub parse { - my $self = shift; +=head2 tag - my ($rec, $format_utf8, $i) = @_; +Define new tag for I and I. - return if (! $format_utf8); + tag('Title', rec('200','a') ); - my $log = $self->_get_logger(); - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - - $i = 0 if (! $i); - - my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'}); - - my @out; - - $log->debug("format: $format"); - - my $eval_code; - # remove eval{...} from beginning - $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s); - - my $filter_name; - # remove filter{...} from beginning - $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s); - - my $prefix; - my $all_found=0; - - while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) { +=cut - my $del = $1 || ''; - $prefix ||= $del if ($all_found == 0); +sub tag { + my $name = shift or die "tag needs name as first argument"; + my @o = grep { defined($_) && $_ ne '' } @_; + return unless (@o); + $out->{$name}->{tag} = $name; + $out->{$name}->{search} = \@o; + $out->{$name}->{display} = \@o; +} - # repeatable index - my $r = $i; - $r = 0 if (lc("$2") eq 's'); +=head2 display - my $found = 0; - my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found); +Define tag just for I - if ($found) { - push @out, $del; - push @out, $tmp; - $all_found += $found; - } - } + @v = display('Title', rec('200','a') ); - return if (! $all_found); +=cut - my $out = join('',@out); +sub display { + my $name = shift or die "display needs name as first argument"; + my @o = grep { defined($_) && $_ ne '' } @_; + return unless (@o); + $out->{$name}->{tag} = $name; + $out->{$name}->{display} = \@o; +} - if ($out) { - # add rest of format (suffix) - $out .= $format; +=head2 search - # add prefix if not there - $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/); +Prepare values just for I - $log->debug("result: $out"); - } + @v = search('Title', rec('200','a') ); - if ($eval_code) { - my $eval = $self->fill_in($rec,$eval_code,$i) || return; - $log->debug("about to eval{$eval} format: $out"); - return if (! $self->_eval($eval)); - } - - if ($filter_name && $self->{'filter'}->{$filter_name}) { - $log->debug("about to filter{$filter_name} format: $out"); - $out = $self->{'filter'}->{$filter_name}->($out); - return unless(defined($out)); - $log->debug("filter result: $out"); - } +=cut - return $out; +sub search { + my $name = shift or die "search needs name as first argument"; + my @o = grep { defined($_) && $_ ne '' } @_; + return unless (@o); + $out->{$name}->{tag} = $name; + $out->{$name}->{search} = \@o; } -=head2 parse_to_arr +=head2 marc21 -Similar to C, but returns array of all repeatable fields +Save value for MARC field - my @arr = $webpac->parse_to_arr($rec,'v250^a'); + marc21('900','a', rec('200','a') ); =cut -sub parse_to_arr { - my $self = shift; - - my ($rec, $format_utf8) = @_; +sub marc21 { + my $f = shift or die "marc21 needs field"; + die "marc21 field must be numer" unless ($f =~ /^\d+$/); - my $log = $self->_get_logger(); + my $sf = shift or die "marc21 needs subfield"; - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - return if (! $format_utf8); - - my $i = 0; - my @arr; - - while (my $v = $self->parse($rec,$format_utf8,$i++)) { - push @arr, $v; + foreach (@_) { + my $v = $_; # make var read-write for Encode + next unless (defined($v) && $v !~ /^\s*$/); + from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding); + push @{ $marc21 }, [ $f, ' ', ' ', $sf => $v ]; } - - $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr); - - return @arr; } +=head1 Functions to extract data from input -=head2 fill_in - -Workhourse of all: takes record from in-memory structure of database and -strings with placeholders and returns string or array of with substituted -values from record. +This function should be used inside functions to create C described +above. - my $text = $webpac->fill_in($rec,'v250^a'); +=head2 rec1 -Optional argument is ordinal number for repeatable fields. By default, -it's assume to be first repeatable field (fields are perl array, so first -element is 0). -Following example will read second value from repeatable field. +Return all values in some field - my $text = $webpac->fill_in($rec,'Title: v250^a',1); + @v = rec1('200') -This function B perform parsing of format to inteligenty skip -delimiters before fields which aren't used. - -This method will automatically decode UTF-8 string to local code page -if needed. +TODO: order of values is probably same as in source data, need to investigate that =cut -sub fill_in { - my $self = shift; - - my $log = $self->_get_logger(); - - my $rec = shift || $log->logconfess("need data record"); - my $format = shift || $log->logconfess("need format to parse"); - # iteration (for repeatable fields) - my $i = shift || 0; - - $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999)); - - # FIXME remove for speedup? - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - - if (utf8::is_utf8($format)) { - $format = $self->_x($format); - } - - my $found = 0; - - my $eval_code; - # remove eval{...} from beginning - $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s); - - my $filter_name; - # remove filter{...} from beginning - $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s); - - # do actual replacement of placeholders - # repeatable fields - $format =~ s/v(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,$i,\$found)/ges; - # non-repeatable fields - $format =~ s/s(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,0,\$found)/ges; - - if ($found) { - $log->debug("format: $format"); - if ($eval_code) { - my $eval = $self->fill_in($rec,$eval_code,$i); - return if (! $self->_eval($eval)); - } - if ($filter_name && $self->{'filter'}->{$filter_name}) { - $log->debug("filter '$filter_name' for $format"); - $format = $self->{'filter'}->{$filter_name}->($format); - return unless(defined($format)); - $log->debug("filter result: $format"); - } - # do we have lookups? - if ($self->{'lookup'}) { - if ($self->{'lookup'}->can('lookup')) { - return $self->{'lookup'}->lookup($format); +sub rec1 { + my $f = shift; + return unless (defined($rec) && defined($rec->{$f})); + if (ref($rec->{$f}) eq 'ARRAY') { + return map { + if (ref($_) eq 'HASH') { + values %{$_}; } else { - $log->warn("Have lookup object but can't invoke lookup method"); + $_; } - } else { - return $format; - } - } else { - return; + } @{ $rec->{$f} }; + } elsif( defined($rec->{$f}) ) { + return $rec->{$f}; } } +=head2 rec2 -=head2 fill_in_to_arr +Return all values in specific field and subfield -Similar to C, but returns array of all repeatable fields. Usable -for fields which have lookups, so they shouldn't be parsed but rather -Ced. - - my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]'); + @v = rec2('200','a') =cut -sub fill_in_to_arr { - my $self = shift; +sub rec2 { + my $f = shift; + return unless (defined($rec && $rec->{$f})); + my $sf = shift; + return map { $_->{$sf} } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} }; +} - my ($rec, $format_utf8) = @_; +=head2 rec - my $log = $self->_get_logger(); +syntaxtic sugar for - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - return if (! $format_utf8); + @v = rec('200') + @v = rec('200','a') - my $i = 0; - my @arr; +=cut - while (my @v = $self->fill_in($rec,$format_utf8,$i++)) { - push @arr, @v; +sub rec { + if ($#_ == 0) { + return rec1(@_); + } elsif ($#_ == 1) { + return rec2(@_); } - - $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr); - - return @arr; } +=head2 regex -=head2 get_data - -Returns value from record. - - my $text = $self->get_data(\$rec,$f,$sf,$i,\$found); - -Arguments are: -record reference C<$rec>, -field C<$f>, -optional subfiled C<$sf>, -index for repeatable values C<$i>. +Apply regex to some or all values -Optinal variable C<$found> will be incremeted if there -is field. - -Returns value or empty string. + @v = regex( 's/foo/bar/g', @v ); =cut -sub get_data { - my $self = shift; - - my ($rec,$f,$sf,$i,$found) = @_; - - if ($$rec->{$f}) { - return '' if (! $$rec->{$f}->[$i]); - no strict 'refs'; - if ($sf && $$rec->{$f}->[$i]->{$sf}) { - $$found++ if (defined($$found)); - return $$rec->{$f}->[$i]->{$sf}; - } elsif (! $sf && $$rec->{$f}->[$i]) { - $$found++ if (defined($$found)); - # it still might have subfield, just - # not specified, so we'll dump all - if ($$rec->{$f}->[$i] =~ /HASH/o) { - my $out; - foreach my $k (keys %{$$rec->{$f}->[$i]}) { - $out .= $$rec->{$f}->[$i]->{$k}." "; - } - return $out; - } else { - return $$rec->{$f}->[$i]; - } - } else { - return ''; - } - } else { - return ''; +sub regex { + my $r = shift; + my @out; + #warn "r: $r\n",Dumper(\@_); + foreach my $t (@_) { + next unless ($t); + eval "\$t =~ $r"; + push @out, $t if ($t && $t ne ''); } + return @out; } +=head2 prefix -=head2 apply_format - -Apply format specified in tag with C and -C. +Prefix all values with a string - my $text = $webpac->apply_format($format_name,$format_delimiter,$data); - -Formats can contain C if you need them. + @v = prefix( 'my_', @v ); =cut -sub apply_format { - my $self = shift; - - my ($name,$delimiter,$data) = @_; - - my $log = $self->_get_logger(); - - if (! $self->{'import_xml'}->{'format'}->{$name}) { - $log->warn(" is not defined in ",$self->{'import_xml_file'}); - return $data; - } - - $log->warn("no delimiter for format $name") if (! $delimiter); +sub prefix { + my $p = shift or die "prefix needs string as first argument"; + return map { $p . $_ } grep { defined($_) } @_; +} - my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'"); +=head2 suffix - my @data = split(/\Q$delimiter\E/, $data); +suffix all values with a string - my $out = sprintf($format, @data); - $log->debug("using format $name [$format] on $data to produce: $out"); + @v = suffix( '_my', @v ); - if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) { - return $self->{'lookup'}->lookup($out); - } else { - return $out; - } +=cut +sub suffix { + my $s = shift or die "suffix needs string as first argument"; + return map { $_ . $s } grep { defined($_) } @_; } -=head2 sort_arr +=head2 surround -Sort array ignoring case and html in data +surround all values with a two strings - my @sorted = $webpac->sort_arr(@unsorted); + @v = surround( 'prefix_', '_suffix', @v ); =cut -sub sort_arr { - my $self = shift; - - my $log = $self->_get_logger(); - - # FIXME add Schwartzian Transformation? - - my @sorted = sort { - $a =~ s#<[^>]+/*>##; - $b =~ s#<[^>]+/*>##; - lc($b) cmp lc($a) - } @_; - $log->debug("sorted values: ",sub { join(", ",@sorted) }); - - return @sorted; +sub surround { + my $p = shift or die "surround need prefix as first argument"; + my $s = shift or die "surround needs suffix as second argument"; + return map { $p . $_ . $s } grep { defined($_) } @_; } +=head2 first -=head1 INTERNAL METHODS - -=head2 _sort_by_order +Return first element -Sort xml tags data structure accoding to C attribute. + $v = first( @v ); =cut -sub _sort_by_order { - my $self = shift; - - my $va = $self->{'import_xml'}->{'indexer'}->{$a}->{'order'} || - $self->{'import_xml'}->{'indexer'}->{$a}; - my $vb = $self->{'import_xml'}->{'indexer'}->{$b}->{'order'} || - $self->{'import_xml'}->{'indexer'}->{$b}; - - return $va <=> $vb; +sub first { + my $r = shift; + return $r; } -=head2 _x +=head2 lookup -Convert strings from C encoding into application -specific encoding (optinally specified using C to C -constructor). +Consult lookup hashes for some value - my $text = $n->_x('normalize text string'); - -This is a stub so that other modules doesn't have to implement it. + @v = lookup( $v ); + @v = lookup( @v ); =cut -sub _x { - my $self = shift; - return shift; +sub lookup { + my $k = shift or return; + return unless (defined($lookup->{$k})); + if (ref($lookup->{$k}) eq 'ARRAY') { + return @{ $lookup->{$k} }; + } else { + return $lookup->{$k}; + } } +=head2 join_with -=head1 AUTHOR - -Dobrica Pavlinusic, C<< >> +Joins walues with some delimiter -=head1 COPYRIGHT & LICENSE - -Copyright 2005 Dobrica Pavlinusic, All Rights Reserved. - -This program is free software; you can redistribute it and/or modify it -under the same terms as Perl itself. + $v = join_with(", ", @v); =cut -1; # End of WebPAC::Normalize +sub join_with { + my $d = shift; + return join($d, grep { defined($_) && $_ ne '' } @_); +} + +# END +1;