--- trunk/lib/WebPAC/Normalize.pm 2006/01/08 21:16:27 371 +++ trunk/lib/WebPAC/Normalize.pm 2006/07/30 14:19:54 604 @@ -1,779 +1,1001 @@ package WebPAC::Normalize; +use Exporter 'import'; +@EXPORT = qw/ + _set_rec _set_lookup + _get_ds _clean_ds + _debug + + tag search display + marc marc_indicators marc_repeatable_subfield + marc_compose marc_leader + marc_duplicate marc_remove + marc_original_order + + rec1 rec2 rec + regex prefix suffix surround + first lookup join_with + + split_rec_on +/; use warnings; use strict; -use blib; -use WebPAC::Common; -use base 'WebPAC::Common'; -use Data::Dumper; + +#use base qw/WebPAC::Common/; +use Data::Dump qw/dump/; +use Encode qw/from_to/; +use Storable qw/dclone/; + +# debugging warn(s) +my $debug = 0; + =head1 NAME -WebPAC::Normalize - data mungling for normalisation +WebPAC::Normalize - describe normalisaton rules using sets =head1 VERSION -Version 0.08 +Version 0.15 =cut -our $VERSION = '0.08'; +our $VERSION = '0.15'; =head1 SYNOPSIS -This package contains code that mungle data to produce normalized format. +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. -It contains several assumptions: +=head1 FUNCTIONS -=over +Functions which start with C<_> are private and used by WebPAC internally. +All other functions are available for use within normalisation rules. -=item * +=head2 data_structure -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. +Return data structure -=item * + my $ds = WebPAC::Normalize::data_structure( + lookup => $lookup->lookup_hash, + row => $row, + rules => $normalize_pl_config, + marc_encoding => 'utf-8', + config => $config, + ); -source data records (C<$rec>) have unique identifiers in field C<000> +Options C, C, C and C are mandatory while all +other are optional. -=item * +This function will B if normalizastion can't be evaled. -optional C tag at B will be -perl code that is evaluated before producing output (value of field will be -interpolated before that) +Since this function isn't exported you have to call it with +C. -=item * +=cut + +sub data_structure { + my $arg = {@_}; -optional C at B will apply perl -code defined as code ref on format after field substitution to producing -output + die "need row argument" unless ($arg->{row}); + die "need normalisation argument" unless ($arg->{rules}); -There is one built-in filter called C which can be use like this: + no strict 'subs'; + _set_lookup( $arg->{lookup} ); + _set_rec( $arg->{row} ); + _set_config( $arg->{config} ); + _clean_ds( %{ $arg } ); + eval "$arg->{rules}"; + die "error evaling $arg->{rules}: $@\n" if ($@); - filter{regex(s/foo/bar/)} + return _get_ds(); +} -=item * +=head2 _set_rec -optional C will be then performed. See C. +Set current record hash -=item * + _set_rec( $rec ); -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. +=cut -=back +my $rec; -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. +sub _set_rec { + $rec = shift or die "no record hash"; +} +=head2 _set_config +Set current config hash + _set_config( $config ); -=head1 FUNCTIONS +Magic keys are: -=head2 new +=over 4 -Create new normalisation object +=item _ - 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', - ); +Code of current database -Parametar C defines user supplied snippets of perl code which can -be use with C notation. +=item _mfn -C is used to form filename for database record (to support multiple -source files which are joined in one database). +Current MFN -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. +=back =cut -sub new { - my $class = shift; - my $self = {@_}; - bless($self, $class); +my $config; - my $r = $self->{'lookup_regex'} ? 1 : 0; - my $l = $self->{'lookup'} ? 1 : 0; - - my $log = $self->_get_logger(); +sub _set_config { + $config = shift; +} - # 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"); - } +=head2 _get_ds - $log->logdie("lookup must be WebPAC::Lookup object") if ($self->{'lookup'} && ! $self->{'lookup'}->isa('WebPAC::Lookup')); +Return hash formatted as data structure - $log->warn("no prefix defined. please check that!") unless ($self->{'prefix'}); + my $ds = _get_ds(); - $log->debug("using lookup regex: ", $self->{lookup_regex}) if ($r && $l); +=cut - if (! $self->{filter} || ! $self->{filter}->{regex}) { - $log->debug("adding built-in filter regex"); - $self->{filter}->{regex} = sub { - my ($val, $regex) = @_; - eval "\$val =~ $regex"; - return $val; - }; - } +my ($out, $marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators); +my ($marc_record_offset, $marc_fetch_offset) = (0, 0); - $self ? return $self : return undef; +sub _get_ds { + return $out; } +=head2 _clean_ds -=head2 data_structure +Clean data structure hash for next record -Create in-memory data structure which represents normalized layout from -C. + _clean_ds(); -This structures are used to produce output. +=cut - my $ds = $webpac->data_structure($rec); +sub _clean_ds { + my $a = {@_}; + ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators) = (); + ($marc_record_offset, $marc_fetch_offset) = (0,0); + $marc_encoding = $a->{marc_encoding}; +} + +=head2 _set_lookup + +Set current lookup hash + + _set_lookup( $lookup ); =cut -sub data_structure { - my $self = shift; +my $lookup; - my $log = $self->_get_logger(); +sub _set_lookup { + $lookup = shift; +} - my $rec = shift; - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); +=head2 _get_marc_fields - $log->debug("data_structure rec = ", sub { Dumper($rec) }); +Get all fields defined by calls to C - $log->logdie("need unique ID (mfn) in field 000 of record " . Dumper($rec) ) unless (defined($rec->{'000'})); + $marc->add_fields( WebPAC::Normalize:_get_marc_fields() ); - my $id = $rec->{'000'}->[0] || $log->logdie("field 000 isn't array!"); +We are using I which detect repeatable fields only from +sequence of field/subfield data generated by normalization. - my $cache_file; +Repeatable field is created when there is second occurence of same subfield or +if any of indicators are different. - 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"); - } +This is sane for most cases. Something like: - 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; - } + 900a-1 900b-1 900c-1 + 900a-2 900b-2 + 900a-3 - my $ds; +will be created from any combination of: - $log->debug("tags: ",sub { join(", ",@sorted_tags) }); + 900a-1 900a-2 900a-3 900b-1 900b-2 900c-1 - foreach my $field (@sorted_tags) { +and following rules: - my $row; + marc('900','a', rec('200','a') ); + marc('900','b', rec('200','b') ); + marc('900','c', rec('200','c') ); -#print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}); +which might not be what you have in mind. If you need repeatable subfield, +define it using C like this: - foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) { - my $format; + marc_repeatable_subfield('900','a'); + marc('900','a', rec('200','a') ); + marc('900','b', rec('200','b') ); + marc('900','c', rec('200','c') ); - $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH'); - $format = $tag->{'value'} || $tag->{'content'}; +will create: - 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); - } - if (! @v) { - $log->debug("$field <",$self->{tag},"> format: $format no values"); -# next; - } else { - $log->debug("$field <",$self->{tag},"> format: $format values: ", join(",", @v)); - } + 900a-1 900a-2 900a-3 900b-1 900c-1 + 900b-2 - if ($tag->{'sort'}) { - @v = $self->sort_arr(@v); - } +There is also support for returning next or specific using: - # use format? - if ($tag->{'format_name'}) { - @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v; - } + while (my $mf = WebPAC::Normalize:_get_marc_fields( fetch_next => 1 ) ) { + # do something with $mf + } - # delimiter will join repeatable fields - if ($tag->{'delimiter'}) { - @v = ( join($tag->{'delimiter'}, @v) ); - } +will always return fields from next MARC record or - # 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("tag $field / $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; + my $mf = WebPAC::Normalize::_get_marc_fields( offset => 42 ); - } else { - push @{$row->{$type}}, @v; - } - } +will return 42th copy record (if it exists). +=cut - } +sub _get_marc_fields { - if ($row) { - $row->{'tag'} = $field; + my $arg = {@_}; + warn "### _get_marc_fields arg: ", dump($arg), $/ if ($debug > 2); + my $offset = $marc_fetch_offset; + if ($arg->{offset}) { + $offset = $arg->{offset}; + } elsif($arg->{fetch_next}) { + $marc_fetch_offset++; + } - # 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"); - } + return if (! $marc_record || ref($marc_record) ne 'ARRAY'); - $ds->{$row_name} = $row; + warn "### full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 2); - $log->debug("row $field: ",sub { Dumper($row) }); - } + my $marc_rec = $marc_record->[ $offset ]; + + warn "## _get_marc_fields (at offset: $offset) -- marc_record = ", dump( @$marc_rec ), $/ if ($debug > 1); + + return if (! $marc_rec || ref($marc_rec) ne 'ARRAY' || $#{ $marc_rec } < 0); + + # first, sort all existing fields + # XXX might not be needed, but modern perl might randomize elements in hash + my @sorted_marc_record = sort { + $a->[0] . ( $a->[3] || '' ) cmp $b->[0] . ( $b->[3] || '') + } @{ $marc_rec }; + @sorted_marc_record = @{ $marc_rec }; ### FIXME disable sorting + + # output marc fields + my @m; + + # count unique field-subfields (used for offset when walking to next subfield) + my $u; + map { $u->{ $_->[0] . ( $_->[3] || '') }++ } @sorted_marc_record; + + if ($debug) { + warn "## marc_repeatable_subfield = ", dump( $marc_repeatable_subfield ), $/ if ( $marc_repeatable_subfield ); + warn "## marc_record[$offset] = ", dump( $marc_rec ), $/; + warn "## sorted_marc_record = ", dump( \@sorted_marc_record ), $/; + warn "## subfield count = ", dump( $u ), $/; } - $self->{'db'}->save_ds( - id => $id, - ds => $ds, - prefix => $self->{prefix}, - ) if ($self->{'db'}); + my $len = $#sorted_marc_record; + my $visited; + my $i = 0; + my $field; - $log->debug("ds: ", sub { Dumper($ds) }); + foreach ( 0 .. $len ) { - $log->logconfess("data structure returned is not array any more!") if wantarray; + # find next element which isn't visited + while ($visited->{$i}) { + $i = ($i + 1) % ($len + 1); + } - return $ds; + # mark it visited + $visited->{$i}++; -} + my $row = dclone( $sorted_marc_record[$i] ); -=head2 parse + # field and subfield which is key for + # marc_repeatable_subfield and u + my $fsf = $row->[0] . ( $row->[3] || '' ); + + if ($debug > 1) { + + print "### field so far [", $#$field, "] : ", dump( $field ), " ", $field ? 'T' : 'F', $/; + print "### this [$i]: ", dump( $row ),$/; + print "### sf: ", $row->[3], " vs ", $field->[3], + $marc_repeatable_subfield->{ $row->[0] . $row->[3] } ? ' (repeatable)' : '', $/, + if ($#$field >= 0); -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. + } - my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i); + # if field exists + if ( $#$field >= 0 ) { + if ( + $row->[0] ne $field->[0] || # field + $row->[1] ne $field->[1] || # i1 + $row->[2] ne $field->[2] # i2 + ) { + push @m, $field; + warn "## saved/1 ", dump( $field ),$/ if ($debug); + $field = $row; + + } elsif ( + ( $row->[3] lt $field->[-2] ) # subfield which is not next (e.g. a after c) + || + ( $row->[3] eq $field->[-2] && # same subfield, but not repeatable + ! $marc_repeatable_subfield->{ $fsf } + ) + ) { + push @m, $field; + warn "## saved/2 ", dump( $field ),$/ if ($debug); + $field = $row; -Filters are implemented here. While simple form of filters looks like this: + } else { + # append new subfields to existing field + push @$field, ( $row->[3], $row->[4] ); + } + } else { + # insert first field + $field = $row; + } - filter{name_of_filter} + if (! $marc_repeatable_subfield->{ $fsf }) { + # make step to next subfield + $i = ($i + $u->{ $fsf } ) % ($len + 1); + } + } -but, filters can also have variable number of parametars like this: + if ($#$field >= 0) { + push @m, $field; + warn "## saved/3 ", dump( $field ),$/ if ($debug); + } - filter{name_of_filter(param,param,param)} + return \@m; +} + +=head2 _debug + +Change level of debug warnings + + _debug( 2 ); =cut -my $warn_once; +sub _debug { + my $l = shift; + return $debug unless defined($l); + warn "debug level $l",$/ if ($l > 0); + $debug = $l; +} -sub parse { - my $self = shift; +=head1 Functions to create C - my ($rec, $format_utf8, $i, $rec_size) = @_; +Those functions generally have to first in your normalization file. - return if (! $format_utf8); +=head2 tag - my $log = $self->_get_logger(); +Define new tag for I and I. - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); + tag('Title', rec('200','a') ); - $i = 0 if (! $i); - my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'}); +=cut - my @out; +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; +} - $log->debug("format: $format [$i]"); +=head2 display - my $eval_code; - # remove eval{...} from beginning - $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s); +Define tag just for I - my $filter_name; - # remove filter{...} from beginning - $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s); + @v = display('Title', rec('200','a') ); - # did we found any (att all) field from format in row? - my $found_any; - # prefix before first field which we preserve it $found_any - my $prefix; +=cut - my $f_step = 1; +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; +} - while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) { +=head2 search - my $del = $1 || ''; - $prefix = $del if ($f_step == 1); +Prepare values just for I - my $fld_type = lc($2); + @v = search('Title', rec('200','a') ); - # repeatable index - my $r = $i; - if ($fld_type eq 's') { - if ($found_any->{'v'}) { - $r = 0; - } else { - return; - } - } +=cut - my $found = 0; - my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found,$rec_size); +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; +} - if ($found) { - $found_any->{$fld_type} += $found; +=head2 marc_leader - # we will skip delimiter before first occurence of field! - push @out, $del unless($found_any->{$fld_type} == 1); - push @out, $tmp; - } - $f_step++; +Setup fields within MARC leader or get leader + + marc_leader('05','c'); + my $leader = marc_leader(); + +=cut + +sub marc_leader { + my ($offset,$value) = @_; + + if ($offset) { + $out->{' leader'}->{ $offset } = $value; + } else { + return $out->{' leader'}; } +} - # test if any fields found? - return if (! $found_any->{'v'} && ! $found_any->{'s'}); +=head2 marc - my $out = join('',@out); +Save value for MARC field - if ($out) { - # add rest of format (suffix) - $out .= $format; + marc('900','a', rec('200','a') ); + marc('001', rec('000') ); - # add prefix if not there - $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/); +=cut - $log->debug("result: $out"); - } +sub marc { + my $f = shift or die "marc needs field"; + die "marc field must be numer" unless ($f =~ /^\d+$/); - 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)); + my $sf; + if ($f >= 10) { + $sf = shift or die "marc needs subfield"; } - - if ($filter_name) { - my @filter_args; - if ($filter_name =~ s/(\w+)\((.*)\)/$1/) { - @filter_args = split(/,/, $2); - } - if ($self->{'filter'}->{$filter_name}) { - $log->debug("about to filter{$filter_name} format: $out with arguments: ", join(",", @filter_args)); - unshift @filter_args, $out; - $out = $self->{'filter'}->{$filter_name}->(@filter_args); - return unless(defined($out)); - $log->debug("filter result: $out"); - } elsif (! $warn_once->{$filter_name}) { - $log->warn("trying to use undefined filter $filter_name"); - $warn_once->{$filter_name}++; + + 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); + my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' '); + if (defined $sf) { + push @{ $marc_record->[ $marc_record_offset ] }, [ $f, $i1, $i2, $sf => $v ]; + } else { + push @{ $marc_record->[ $marc_record_offset ] }, [ $f, $v ]; } } - - return $out; } -=head2 parse_to_arr +=head2 marc_repeatable_subfield -Similar to C, but returns array of all repeatable fields +Save values for MARC repetable subfield - my @arr = $webpac->parse_to_arr($rec,'v250^a'); + marc_repeatable_subfield('910', 'z', rec('909') ); =cut -sub parse_to_arr { - my $self = shift; - - my ($rec, $format_utf8) = @_; +sub marc_repeatable_subfield { + my ($f,$sf) = @_; + die "marc_repeatable_subfield need field and subfield!\n" unless ($f && $sf); + $marc_repeatable_subfield->{ $f . $sf }++; + marc(@_); +} - my $log = $self->_get_logger(); +=head2 marc_indicators - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - return if (! $format_utf8); +Set both indicators for MARC field - my $i = 0; - my @arr; + marc_indicators('900', ' ', 1); - my $rec_size = { '_' => '_' }; +Any indicator value other than C<0-9> will be treated as undefined. - while (my $v = $self->parse($rec,$format_utf8,$i++,\$rec_size)) { - push @arr, $v; - warn "parse rec_size = ", Dumper($rec_size); - } +=cut - $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr); +sub marc_indicators { + my $f = shift || die "marc_indicators need field!\n"; + my ($i1,$i2) = @_; + die "marc_indicators($f, ...) need i1!\n" unless(defined($i1)); + die "marc_indicators($f, $i1, ...) need i2!\n" unless(defined($i2)); - return @arr; + $i1 = ' ' if ($i1 !~ /^\d$/); + $i2 = ' ' if ($i2 !~ /^\d$/); + @{ $marc_indicators->{$f} } = ($i1,$i2); } +=head2 marc_compose + +Save values for each MARC subfield explicitly + + marc_compose('900', + 'a', rec('200','a') + 'b', rec('201','a') + 'a', rec('200','b') + 'c', rec('200','c') + ); -=head2 fill_in +If you specify C<+> for subfield, value will be appended +to previous defined subfield. -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. +=cut - my $text = $webpac->fill_in($rec,'v250^a'); +sub marc_compose { + my $f = shift or die "marc_compose needs field"; + die "marc_compose field must be numer" unless ($f =~ /^\d+$/); -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. + my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' '); + my $m = [ $f, $i1, $i2 ]; - my $text = $webpac->fill_in($rec,'Title: v250^a',1); + warn "### marc_compose input subfields = ", dump(@_),$/ if ($debug > 2); -This function B perform parsing of format to inteligenty skip -delimiters before fields which aren't used. + while (@_) { + my $sf = shift or die "marc_compose $f needs subfield"; + my $v = shift; -This method will automatically decode UTF-8 string to local code page -if needed. + next unless (defined($v) && $v !~ /^\s*$/); + from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding); + warn "## ++ marc_compose($f,$sf,$v) ", dump( $m ),$/ if ($debug > 1); + if ($sf ne '+') { + push @$m, ( $sf, $v ); + } else { + $m->[ $#$m ] .= $v; + } + } -There is optional parametar C<$record_size> which can be used to get sizes of -all C combinations in this format. + warn "## marc_compose current marc = ", dump( $m ),$/ if ($debug > 1); - my $text = $webpac->fill_in($rec,'got: v900^a v900^x',0,\$rec_size); + push @{ $marc_record->[ $marc_record_offset ] }, $m if ($#{$m} > 2); +} -=cut +=head2 marc_duplicate -sub fill_in { - my $self = shift; +Generate copy of current MARC record and continue working on copy - my $log = $self->_get_logger(); + marc_duplicate(); - my ($rec,$format,$i,$rec_size) = @_; +Copies can be accessed using C<< _get_marc_fields( fetch_next => 1 ) >> or +C<< _get_marc_fields( offset => 42 ) >>. - $log->logconfess("need data record") unless ($rec); - $log->logconfess("need format to parse") unless($format); +=cut - # iteration (for repeatable fields) - $i ||= 0; +sub marc_duplicate { + my $m = $marc_record->[ -1 ]; + die "can't duplicate record which isn't defined" unless ($m); + push @{ $marc_record }, dclone( $m ); + warn "## marc_duplicate = ", dump(@$marc_record), $/ if ($debug > 1); + $marc_record_offset = $#{ $marc_record }; + warn "## marc_record_offset = $marc_record_offset", $/ if ($debug > 1); +} - $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999)); +=head2 marc_remove - # FIXME remove for speedup? - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); +Remove some field or subfield from MARC record. - if (utf8::is_utf8($format)) { - $format = $self->_x($format); - } + marc_remove('200'); + marc_remove('200','a'); - my $found = 0; - my $just_single = 1; +This will erase field C<200> or C<200^a> from current MARC record. - my $eval_code; - # remove eval{...} from beginning - $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s); +This is useful after calling C or on it's own (but, you +should probably just remove that subfield definition if you are not +using C). - my $filter_name; - # remove filter{...} from beginning - $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s); +FIXME: support fields < 10. - # do actual replacement of placeholders - # repeatable fields - if ($format =~ s/v(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,$i,\$found,$rec_size)/ges) { - $just_single = 0; - } +=cut - # non-repeatable fields - if ($format =~ s/s(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,0,\$found,$rec_size)/ges) { - return if ($i > 0 && $just_single); - } +sub marc_remove { + my ($f, $sf) = @_; - 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')) { - my @lookup = $self->{lookup}->lookup($format); - $log->debug("lookup $format", join(", ", @lookup)); - return @lookup; + die "marc_remove needs record number" unless defined($f); + + my $marc = $marc_record->[ $marc_record_offset ]; + + warn "### marc_remove before = ", dump( $marc ), $/ if ($debug > 2); + + my $i = 0; + foreach ( 0 .. $#{ $marc } ) { + last unless (defined $marc->[$i]); + warn "#### working on ",dump( @{ $marc->[$i] }), $/ if ($debug > 3); + if ($marc->[$i]->[0] eq $f) { + if (! defined $sf) { + # remove whole field + splice @$marc, $i, 1; + warn "#### slice \@\$marc, $i, 1 = ",dump( @{ $marc }), $/ if ($debug > 3); + $i--; } else { - $log->warn("Have lookup object but can't invoke lookup method"); + foreach my $j ( 0 .. (( $#{ $marc->[$i] } - 3 ) / 2) ) { + my $o = ($j * 2) + 3; + if ($marc->[$i]->[$o] eq $sf) { + # remove subfield + splice @{$marc->[$i]}, $o, 2; + warn "#### slice \@{\$marc->[$i]}, $o, 2 = ", dump( @{ $marc }), $/ if ($debug > 3); + # is record now empty? + if ($#{ $marc->[$i] } == 2) { + splice @$marc, $i, 1; + warn "#### slice \@\$marc, $i, 1 = ", dump( @{ $marc }), $/ if ($debug > 3); + $i--; + }; + } + } } - } else { - return $format; } - } else { - return; + $i++; } + + warn "### marc_remove($f", $sf ? ",$sf" : "", ") after = ", dump( $marc ), $/ if ($debug > 2); + + $marc_record->[ $marc_record_offset ] = $marc; + + warn "## full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 1); } +=head2 marc_original_order -=head2 fill_in_to_arr +Copy all subfields preserving original order to marc field. -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. + marc_original_order(210, 260); - my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]'); +You might want to use this command if you are just renaming subfields or +using pre-processing modify_record in C and don't need any +post-processing or want to preserve order of original subfields. =cut -sub fill_in_to_arr { - my $self = shift; +sub marc_original_order { - my ($rec, $format_utf8) = @_; + my ($from, $to) = @_; + die "marc_original_order needs from and to fields\n" unless ($from && $to); - my $log = $self->_get_logger(); + my $r = $rec->{$from} || return; + die "record field $from isn't array\n" unless (ref($r) eq 'ARRAY'); - $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o); - return if (! $format_utf8); + my ($i1,$i2) = defined($marc_indicators->{$to}) ? @{ $marc_indicators->{$to} } : (' ',' '); + warn "## marc_original_order($from,$to) source = ", dump( $r ),$/ if ($debug > 1); - my $i = 0; - my @arr; + foreach my $d (@$r) { - my $rec_size; + my @sfs = @{ $d->{subfields} }; - while (my $v = $self->fill_in($rec,$format_utf8,$i,\$rec_size)) { - push @arr, $v; - warn "rec_size = ", Dumper($rec_size); + die "field $from doesn't have subfields specification\n" unless(@sfs); + die "field $from doesn't have even number of subfields specifications\n" unless($#sfs % 2 == 1); + +warn "#--> d: ",dump($d), "\n#--> sfs: ",dump(@sfs),$/; + + my $m = [ $to, $i1, $i2 ]; + + while (my $sf = shift @sfs) { +warn "#--> sf: ",dump($sf), $/; + my $offset = shift @sfs; + die "corrupted sufields specification for field $from\n" unless defined($offset); + + my $v; + if (ref($d->{$sf}) eq 'ARRAY') { + $v = $d->{$sf}->[$offset] if (defined($d->{$sf}->[$offset])); + } elsif ($offset == 0) { + $v = $d->{$sf}; + } else { + die "field $from subfield '$sf' need occurence $offset which doesn't exist", dump($d->{$sf}); + } + push @$m, ( $sf, $v ) if (defined($v)); + } + + if ($#{$m} > 2) { + push @{ $marc_record->[ $marc_record_offset ] }, $m; + } } - $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr); + warn "## marc_record = ", dump( $marc_record ),$/ if ($debug > 1); - return @arr; + warn "# marc_original_order is partly implemented"; } -=head2 get_data +=head1 Functions to extract data from input -Returns value from record. +This function should be used inside functions to create C described +above. - my $text = $self->get_data(\$rec,$f,$sf,$i,\$found,\$rec_size); +=head2 rec1 -Required arguments are: +Return all values in some field -=over 8 + @v = rec1('200') -=item C<$rec> +TODO: order of values is probably same as in source data, need to investigate that -record reference +=cut -=item C<$f> +sub rec1 { + my $f = shift; + warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1); + return unless (defined($rec) && defined($rec->{$f})); + warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1); + if (ref($rec->{$f}) eq 'ARRAY') { + return map { + if (ref($_) eq 'HASH') { + values %{$_}; + } else { + $_; + } + } @{ $rec->{$f} }; + } elsif( defined($rec->{$f}) ) { + return $rec->{$f}; + } +} -field +=head2 rec2 -=item C<$sf> +Return all values in specific field and subfield -optional subfield + @v = rec2('200','a') -=item C<$i> +=cut -index offset for repeatable values ( 0 ... $rec_size->{'400^a'} ) +sub rec2 { + my $f = shift; + return unless (defined($rec && $rec->{$f})); + my $sf = shift; + warn "rec2($f,$sf) = ", dump( $rec->{$f} ), $/ if ($debug > 1); + return map { + if (ref($_->{$sf}) eq 'ARRAY') { + @{ $_->{$sf} }; + } else { + $_->{$sf}; + } + } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} }; +} -=item C<$found> +=head2 rec -optional variable that will be incremeted if preset +syntaxtic sugar for -=item C<$rec_size> + @v = rec('200') + @v = rec('200','a') -hash to hold maximum occurances of C combinations -(which can be accessed using keys in same format) +=cut -=back +sub rec { + my @out; + if ($#_ == 0) { + @out = rec1(@_); + } elsif ($#_ == 1) { + @out = rec2(@_); + } + if (@out) { + return @out; + } else { + return ''; + } +} -Returns value or empty string, updates C<$found> and C -if present. +=head2 regex + +Apply regex to some or all values + + @v = regex( 's/foo/bar/g', @v ); =cut -sub get_data { - my $self = shift; +sub regex { + my $r = shift; + my @out; + #warn "r: $r\n", dump(\@_); + foreach my $t (@_) { + next unless ($t); + eval "\$t =~ $r"; + push @out, $t if ($t && $t ne ''); + } + return @out; +} - my ($rec,$f,$sf,$i,$found,$cache) = @_; +=head2 prefix - return '' unless ($$rec->{$f} && ref($$rec->{$f}) eq 'ARRAY'); +Prefix all values with a string - if (defined($$cache)) { - $$cache->{ $f . ( $sf ? '^' . $sf : '' ) } ||= scalar @{ $$rec->{$f} }; - } + @v = prefix( 'my_', @v ); - return '' unless ($$rec->{$f}->[$i]); +=cut - { - no strict 'refs'; - if (defined($sf)) { - $$found++ if (defined($$found) && $$rec->{$f}->[$i]->{$sf}); - return $$rec->{$f}->[$i]->{$sf}; - } else { - $$found++ if (defined($$found)); - # it still might have subfields, just - # not specified, so we'll dump some debug info - if ($$rec->{$f}->[$i] =~ /HASH/o) { - my $out; - foreach my $k (keys %{$$rec->{$f}->[$i]}) { - $out .= '$' . $k .':' . $$rec->{$f}->[$i]->{$k}." "; - } - return $out; - } else { - return $$rec->{$f}->[$i]; - } - } - } +sub prefix { + my $p = shift or return; + return map { $p . $_ } grep { defined($_) } @_; } +=head2 suffix -=head2 apply_format +suffix all values with a string -Apply format specified in tag with C and -C. + @v = suffix( '_my', @v ); - my $text = $webpac->apply_format($format_name,$format_delimiter,$data); +=cut + +sub suffix { + my $s = shift or die "suffix needs string as first argument"; + return map { $_ . $s } grep { defined($_) } @_; +} -Formats can contain C if you need them. +=head2 surround + +surround all values with a two strings + + @v = surround( 'prefix_', '_suffix', @v ); =cut -sub apply_format { - my $self = shift; +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 - my ($name,$delimiter,$data) = @_; +Return first element - my $log = $self->_get_logger(); + $v = first( @v ); - if (! $self->{'import_xml'}->{'format'}->{$name}) { - $log->warn(" is not defined in ",$self->{'import_xml_file'}); - return $data; - } +=cut - $log->warn("no delimiter for format $name") if (! $delimiter); +sub first { + my $r = shift; + return $r; +} + +=head2 lookup - my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'"); +Consult lookup hashes for some value - my @data = split(/\Q$delimiter\E/, $data); + @v = lookup( $v ); + @v = lookup( @v ); - my $out = sprintf($format, @data); - $log->debug("using format $name [$format] on $data to produce: $out"); +=cut - if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) { - return $self->{'lookup'}->lookup($out); +sub lookup { + my $k = shift or return; + return unless (defined($lookup->{$k})); + if (ref($lookup->{$k}) eq 'ARRAY') { + return @{ $lookup->{$k} }; } else { - return $out; + return $lookup->{$k}; } - } -=head2 sort_arr +=head2 config -Sort array ignoring case and html in data +Consult config values stored in C - my @sorted = $webpac->sort_arr(@unsorted); + # return database code (key under databases in yaml) + $database_code = config(); # use _ from hash + $database_name = config('name'); + $database_input_name = config('input name'); + $tag = config('input normalize tag'); -=cut +Up to three levels are supported. -sub sort_arr { - my $self = shift; +=cut - my $log = $self->_get_logger(); +sub config { + return unless ($config); - # FIXME add Schwartzian Transformation? + my $p = shift; - my @sorted = sort { - $a =~ s#<[^>]+/*>##; - $b =~ s#<[^>]+/*>##; - lc($b) cmp lc($a) - } @_; - $log->debug("sorted values: ",sub { join(", ",@sorted) }); + $p ||= ''; - return @sorted; -} + my $v; + warn "### getting config($p)\n" if ($debug > 1); -=head1 INTERNAL METHODS + my @p = split(/\s+/,$p); + if ($#p < 0) { + $v = $config->{ '_' }; # special, database code + } else { -=head2 _sort_by_order + my $c = dclone( $config ); -Sort xml tags data structure accoding to C attribute. + foreach my $k (@p) { + warn "### k: $k c = ",dump($c),$/ if ($debug > 1); + if (ref($c) eq 'ARRAY') { + $c = shift @$c; + warn "config($p) taking first occurence of '$k', probably not what you wanted!\n"; + last; + } -=cut + if (! defined($c->{$k}) ) { + $c = undef; + last; + } else { + $c = $c->{$k}; + } + } + $v = $c if ($c); -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}; + warn "## config( '$p' ) = ",dump( $v ),$/ if ($v && $debug); + warn "config( '$p' ) is empty\n" if (! $v); - return $va <=> $vb; + return $v; } -=head2 _x +=head2 id -Convert strings from C encoding into application -specific encoding (optinally specified using C to C -constructor). +Returns unique id of this record - my $text = $n->_x('normalize text string'); + $id = id(); -This is a stub so that other modules doesn't have to implement it. +Returns C<42/2> for 2nd occurence of MFN 42. =cut -sub _x { - my $self = shift; - return shift; +sub id { + my $mfn = $config->{_mfn} || die "no _mfn in config data"; + return $mfn . $#{$marc_record} ? $#{$marc_record} + 1 : ''; } +=head2 join_with -=head1 AUTHOR +Joins walues with some delimiter -Dobrica Pavlinusic, C<< >> + $v = join_with(", ", @v); -=head1 COPYRIGHT & LICENSE +=cut -Copyright 2005 Dobrica Pavlinusic, All Rights Reserved. +sub join_with { + my $d = shift; + warn "### join_with('$d',",dump(@_),")\n" if ($debug > 2); + my $v = join($d, grep { defined($_) && $_ ne '' } @_); + return '' unless defined($v); + return $v; +} -This program is free software; you can redistribute it and/or modify it -under the same terms as Perl itself. +=head2 split_rec_on + +Split record subfield on some regex and take one of parts out + + $a_before_semi_column = + split_rec_on('200','a', /\s*;\s*/, $part); + +C<$part> is optional number of element. First element is +B<1>, not 0! + +If there is no C<$part> parameter or C<$part> is 0, this function will +return all values produced by splitting. =cut -1; # End of WebPAC::Normalize +sub split_rec_on { + die "split_rec_on need (fld,sf,regex[,part]" if ($#_ < 2); + + my ($fld, $sf, $regex, $part) = @_; + warn "### regex ", ref($regex), $regex, $/ if ($debug > 2); + + my @r = rec( $fld, $sf ); + my $v = shift @r; + warn "### first rec($fld,$sf) = ",dump($v),$/ if ($debug > 2); + + return '' if ( ! defined($v) || $v =~ /^\s*$/); + + my @s = split( $regex, $v ); + warn "## split_rec_on($fld,$sf,$regex,$part) = ",dump(@s),$/ if ($debug > 1); + if ($part && $part > 0) { + return $s[ $part - 1 ]; + } else { + return @s; + } +} + +# END +1;