/[webpac2]/trunk/lib/WebPAC/Normalize.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /trunk/lib/WebPAC/Normalize.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 433 by dpavlin, Mon Apr 17 16:01:12 2006 UTC revision 554 by dpavlin, Sat Jul 1 10:19:29 2006 UTC
# Line 1  Line 1 
1  package WebPAC::Normalize;  package WebPAC::Normalize;
2    use Exporter 'import';
3    @EXPORT = qw/
4            _set_rec _set_lookup
5            _get_ds _clean_ds
6            _debug
7    
8            tag search display
9            marc marc_indicators marc_repeatable_subfield
10    
11            rec1 rec2 rec
12            regex prefix suffix surround
13            first lookup join_with
14    /;
15    
16  use warnings;  use warnings;
17  use strict;  use strict;
18  use blib;  
19  use WebPAC::Common;  #use base qw/WebPAC::Common/;
20  use base 'WebPAC::Common';  use Data::Dump qw/dump/;
21  use Data::Dumper;  use Encode qw/from_to/;
22    
23    # debugging warn(s)
24    my $debug = 0;
25    
26    
27  =head1 NAME  =head1 NAME
28    
29  WebPAC::Normalize - data mungling for normalisation  WebPAC::Normalize - describe normalisaton rules using sets
30    
31  =head1 VERSION  =head1 VERSION
32    
33  Version 0.09  Version 0.07
34    
35  =cut  =cut
36    
37  our $VERSION = '0.09';  our $VERSION = '0.07';
38    
39  =head1 SYNOPSIS  =head1 SYNOPSIS
40    
41  This package contains code that mungle data to produce normalized format.  This module uses C<conf/normalize/*.pl> files to perform normalisation
42    from input records using perl functions which are specialized for set
43  It contains several assumptions:  processing.
44    
45  =over  Sets are implemented as arrays, and normalisation file is valid perl, which
46    means that you check it's validity before running WebPAC using
47  =item *  C<perl -c normalize.pl>.
48    
49    Normalisation can generate multiple output normalized data. For now, supported output
50    types (on the left side of definition) are: C<tag>, C<display>, C<search> and
51    C<marc>.
52    
53  format of fields is defined using C<v123^a> notation for repeatable fields  =head1 FUNCTIONS
 or C<s123^a> for single (or first) value, where C<123> is field number and  
 C<a> is subfield.  
   
 =item *  
   
 source data records (C<$rec>) have unique identifiers in field C<000>  
   
 =item *  
54    
55  optional C<eval{length('v123^a') == 3}> tag at B<beginning of format> will be  Functions which start with C<_> are private and used by WebPAC internally.
56  perl code that is evaluated before producing output (value of field will be  All other functions are available for use within normalisation rules.
 interpolated before that)  
57    
58  =item *  =head2 data_structure
59    
60  optional C<filter{filter_name}> at B<begining of format> will apply perl  Return data structure
 code defined as code ref on format after field substitution to producing  
 output  
61    
62  There is one built-in filter called C<regex> which can be use like this:    my $ds = WebPAC::Normalize::data_structure(
63            lookup => $lookup->lookup_hash,
64            row => $row,
65            rules => $normalize_pl_config,
66            marc_encoding => 'utf-8',
67      );
68    
69    filter{regex(s/foo/bar/)}  Options C<lookup>, C<row>, C<rules> and C<log> are mandatory while all
70    other are optional.
71    
72  =item *  This function will B<die> if normalizastion can't be evaled.
73    
74  optional C<lookup{...}> will be then performed. See C<WebPAC::Lookups>.  Since this function isn't exported you have to call it with
75    C<WebPAC::Normalize::data_structure>.
76    
77  =item *  =cut
78    
79  at end, optional C<format>s rules are resolved. Format rules are similar to  sub data_structure {
80  C<sprintf> and can also contain C<lookup{...}> which is performed after          my $arg = {@_};
 values are inserted in format.  
81    
82  =back          die "need row argument" unless ($arg->{row});
83            die "need normalisation argument" unless ($arg->{rules});
84    
85  This also describes order in which transformations are applied (eval,          no strict 'subs';
86  filter, lookup, format) which is important to undestand when deciding how to          _set_lookup( $arg->{lookup} );
87  solve your data mungling and normalisation process.          _set_rec( $arg->{row} );
88            _clean_ds( %{ $arg } );
89            eval "$arg->{rules}";
90            die "error evaling $arg->{rules}: $@\n" if ($@);
91    
92            return _get_ds();
93    }
94    
95    =head2 _set_rec
96    
97    Set current record hash
98    
99  =head1 FUNCTIONS    _set_rec( $rec );
100    
101  =head2 new  =cut
102    
103  Create new normalisation object  my $rec;
104    
105    my $n = new WebPAC::Normalize::Something(  sub _set_rec {
106          filter => {          $rec = shift or die "no record hash";
107                  'filter_name_1' => sub {  }
                         # filter code  
                         return length($_);  
                 }, ...  
         },  
         db => $db_obj,  
         lookup_regex => $lookup->regex,  
         lookup => $lookup_obj,  
         prefix => 'foobar',  
   );  
108    
109  Parametar C<filter> defines user supplied snippets of perl code which can  =head2 _get_ds
 be use with C<filter{...}> notation.  
110    
111  C<prefix> is used to form filename for database record (to support multiple  Return hash formatted as data structure
 source files which are joined in one database).  
112    
113  Recommended parametar C<lookup_regex> is used to enable parsing of lookups    my $ds = _get_ds();
 in structures. If you pass this parametar, you must also pass C<lookup>  
 which is C<WebPAC::Lookup> object.  
114    
115  =cut  =cut
116    
117  sub new {  my ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators);
         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();  
118    
119          # those two must be in pair  sub _get_ds {
120          if ( ($r & $l) != ($r || $l) ) {          return $out;
121                  my $log = $self->_get_logger();  }
                 $log->logdie("lookup_regex and lookup must be in pair");  
         }  
122    
123          $log->logdie("lookup must be WebPAC::Lookup object") if ($self->{'lookup'} && ! $self->{'lookup'}->isa('WebPAC::Lookup'));  =head2 _clean_ds
124    
125          $log->warn("no prefix defined. please check that!") unless ($self->{'prefix'});  Clean data structure hash for next record
126    
127          $log->debug("using lookup regex: ", $self->{lookup_regex}) if ($r && $l);    _clean_ds();
128    
129          if (! $self->{filter} || ! $self->{filter}->{regex}) {  =cut
                 $log->debug("adding built-in filter regex");  
                 $self->{filter}->{regex} = sub {  
                         my ($val, $regex) = @_;  
                         eval "\$val =~ $regex";  
                         return $val;  
                 };  
         }  
130    
131          $self ? return $self : return undef;  sub _clean_ds {
132            my $a = {@_};
133            ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators) = ();
134            $marc_encoding = $a->{marc_encoding};
135  }  }
136    
137  =head2 all_tags  =head2 _set_lookup
138    
139  Returns all tags in document in specified order  Set current lookup hash
140    
141    my $sorted_tags = $self->all_tags();    _set_lookup( $lookup );
142    
143  =cut  =cut
144    
145  sub all_tags {  my $lookup;
         my $self = shift;  
146    
147          if (! $self->{_tags_by_order}) {  sub _set_lookup {
148            $lookup = shift;
149    }
150    
151                  my $log = $self->_get_logger;  =head2 _get_marc_fields
                 # sanity check  
                 $log->logdie("can't find self->{inport_xml}->{indexer}") unless ($self->{import_xml}->{indexer});  
152    
153                  my @tags = keys %{ $self->{'import_xml'}->{'indexer'}};  Get all fields defined by calls to C<marc>
                 $log->debug("unsorted tags: " . join(", ", @tags));  
154    
155                  @tags = sort { $self->_sort_by_order } @tags;          $marc->add_fields( WebPAC::Normalize:_get_marc_fields() );
156    
157                  $log->debug("sorted tags: " . join(",", @tags) );  We are using I<magic> which detect repeatable fields only from
158    sequence of field/subfield data generated by normalization.
159    
160                  $self->{_tags_by_order} = \@tags;  Repeatable field is created when there is second occurence of same subfield or
161          }  if any of indicators are different.
162    
163          return $self->{_tags_by_order};  This is sane for most cases. Something like:
 }  
164    
165      900a-1 900b-1 900c-1
166      900a-2 900b-2
167      900a-3
168    
169    will be created from any combination of:
170    
171  =head2 data_structure    900a-1 900a-2 900a-3 900b-1 900b-2 900c-1
   
 Create in-memory data structure which represents normalized layout from  
 C<conf/normalize/*.xml>.  
172    
173  This structures are used to produce output.  and following rules:
174    
175   my $ds = $webpac->data_structure($rec);    marc('900','a', rec('200','a') );
176      marc('900','b', rec('200','b') );
177      marc('900','c', rec('200','c') );
178    
179  =cut  which might not be what you have in mind. If you need repeatable subfield,
180    define it using C<marc_repeatable_subfield> like this:
181    
182  sub data_structure {  ....
         my $self = shift;  
183    
184          my $log = $self->_get_logger();  =cut
185    
186          my $rec = shift;  sub _get_marc_fields {
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
187    
188          $log->debug("data_structure rec = ", sub { Dumper($rec) });          return if (! $marc_record || ref($marc_record) ne 'ARRAY' || $#{ $marc_record } < 0);
189    
190          $log->logdie("need unique ID (mfn) in field 000 of record " . Dumper($rec) ) unless (defined($rec->{'000'}));          # first, sort all existing fields
191            # XXX might not be needed, but modern perl might randomize elements in hash
192            my @sorted_marc_record = sort {
193                    $a->[0] . $a->[3] cmp $b->[0] . $b->[3]
194            } @{ $marc_record };
195    
196          my $id = $rec->{'000'}->[0] || $log->logdie("field 000 isn't array!");          # output marc fields
197            my @m;
198    
199          my $cache_file;          # count unique field-subfields (used for offset when walking to next subfield)
200            my $u;
201            map { $u->{ $_->[0] . $_->[3]  }++ } @sorted_marc_record;
202    
203          if ($self->{'db'}) {          if ($debug) {
204                  my $ds = $self->{'db'}->load_ds( id => $id, prefix => $self->{prefix} );                  warn "## marc_repeatable_subfield ", dump( $marc_repeatable_subfield ), $/;
205                  $log->debug("load_ds( rec = ", sub { Dumper($rec) }, ") = ", sub { Dumper($ds) });                  warn "## marc_record ", dump( $marc_record ), $/;
206                  return $ds if ($ds);                  warn "## sorted_marc_record ", dump( \@sorted_marc_record ), $/;
207                  $log->debug("cache miss, creating");                  warn "## subfield count ", dump( $u ), $/;
208          }          }
209    
210          my $tags = $self->all_tags();          my $len = $#sorted_marc_record;
211            my $visited;
212          $log->debug("tags: ",sub { join(", ",@{ $tags }) });          my $i = 0;
213            my $field;
         my $ds;  
   
         foreach my $field (@{ $tags }) {  
214    
215                  my $row;          foreach ( 0 .. $len ) {
216    
217  #print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});                  # find next element which isn't visited
218                    while ($visited->{$i}) {
219                            $i = ($i + 1) % ($len + 1);
220                    }
221    
222                    # mark it visited
223                    $visited->{$i}++;
224    
225                    my $row = $sorted_marc_record[$i];
226    
227                    # field and subfield which is key for
228                    # marc_repeatable_subfield and u
229                    my $fsf = $row->[0] . $row->[3];
230    
231                    if ($debug > 1) {
232    
233                            print "### field so far [", $#$field, "] : ", dump( $field ), " ", $field ? 'T' : 'F', $/;
234                            print "### this [$i]: ", dump( $row ),$/;
235                            print "### sf: ", $row->[3], " vs ", $field->[3],
236                                    $marc_repeatable_subfield->{ $row->[0] . $row->[3] } ? ' (repeatable)' : '', $/,
237                                    if ($#$field >= 0);
238    
239                  foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {                  }
                         my $format;  
240    
241                          $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH');                  # if field exists
242                          $format = $tag->{'value'} || $tag->{'content'};                  if ( $#$field >= 0 ) {
243                            if (
244                                    $row->[0] ne $field->[0] ||             # field
245                                    $row->[1] ne $field->[1] ||             # i1
246                                    $row->[2] ne $field->[2]                # i2
247                            ) {
248                                    push @m, $field;
249                                    warn "## saved/1 ", dump( $field ),$/ if ($debug);
250                                    $field = $row;
251    
252                            } elsif (
253                                    ( $row->[3] lt $field->[-2] )           # subfield which is not next (e.g. a after c)
254                                    ||
255                                    ( $row->[3] eq $field->[-2] &&          # same subfield, but not repeatable
256                                            ! $marc_repeatable_subfield->{ $fsf }
257                                    )
258                            ) {
259                                    push @m, $field;
260                                    warn "## saved/2 ", dump( $field ),$/ if ($debug);
261                                    $field = $row;
262    
                         my @v;  
                         if ($self->{'lookup_regex'} && $format =~ $self->{'lookup_regex'}) {  
                                 @v = $self->_rec_to_arr($rec,$format,'fill_in');  
                         } else {  
                                 @v = $self->_rec_to_arr($rec,$format,'parse');  
                         }  
                         if (! @v) {  
                                 $log->debug("$field <",$self->{tag},"> format: $format no values");  
                                 next;  
263                          } else {                          } else {
264                                  $log->debug("$field <",$self->{tag},"> format: $format values: ", join(",", @v));                                  # append new subfields to existing field
265                                    push @$field, ( $row->[3], $row->[4] );
266                          }                          }
267                    } else {
268                          if ($tag->{'sort'}) {                          # insert first field
269                                  @v = $self->sort_arr(@v);                          $field = $row;
                         }  
   
                         # use format?  
                         if ($tag->{'format_name'}) {  
                                 @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  
                         }  
   
                         # delimiter will join repeatable fields  
                         if ($tag->{'delimiter'}) {  
                                 @v = ( join($tag->{'delimiter'}, @v) );  
                         }  
   
                         # 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;  
   
                                 } else {  
                                         push @{$row->{$type}}, @v;  
                                 }  
                         }  
   
   
270                  }                  }
271    
272                  if ($row) {                  if (! $marc_repeatable_subfield->{ $fsf }) {
273                          $row->{'tag'} = $field;                          # make step to next subfield
274                            $i = ($i + $u->{ $fsf } ) % ($len + 1);
                         # 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");  
                         }  
   
                         $ds->{$row_name} = $row;  
   
                         $log->debug("row $field: ",sub { Dumper($row) });  
275                  }                  }
   
276          }          }
277    
278          $self->{'db'}->save_ds(          if ($#$field >= 0) {
279                  id => $id,                  push @m, $field;
280                  ds => $ds,                  warn "## saved/3 ", dump( $field ),$/ if ($debug);
281                  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;  
282    
283            return @m;
284  }  }
285    
286  =head2 parse  =head2 _debug
   
 Perform smart parsing of string, skipping delimiters for fields which aren't  
 defined. It can also eval code in format starting with C<eval{...}> and  
 return output or nothing depending on eval code.  
287    
288   my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);  Change level of debug warnings
289    
290  Filters are implemented here. While simple form of filters looks like this:    _debug( 2 );
   
   filter{name_of_filter}  
   
 but, filters can also have variable number of parametars like this:  
   
   filter{name_of_filter(param,param,param)}  
291    
292  =cut  =cut
293    
294  my $warn_once;  sub _debug {
295            my $l = shift;
296  sub parse {          return $debug unless defined($l);
297          my $self = shift;          $debug = $l;
298    }
299    
300          my ($rec, $format_utf8, $i, $rec_size) = @_;  =head1 Functions to create C<data_structure>
301    
302          return if (! $format_utf8);  Those functions generally have to first in your normalization file.
303    
304          my $log = $self->_get_logger();  =head2 tag
305    
306          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  Define new tag for I<search> and I<display>.
307    
308          $i = 0 if (! $i);    tag('Title', rec('200','a') );
309    
         my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});  
310    
311          my @out;  =cut
312    
313          $log->debug("format: $format [$i]");  sub tag {
314            my $name = shift or die "tag needs name as first argument";
315            my @o = grep { defined($_) && $_ ne '' } @_;
316            return unless (@o);
317            $out->{$name}->{tag} = $name;
318            $out->{$name}->{search} = \@o;
319            $out->{$name}->{display} = \@o;
320    }
321    
322          my $eval_code;  =head2 display
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
323    
324          my $filter_name;  Define tag just for I<display>
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
325    
326          # did we found any (att all) field from format in row?    @v = display('Title', rec('200','a') );
         my $found_any;  
         # prefix before first field which we preserve it $found_any  
         my $prefix;  
327    
328          my $f_step = 1;  =cut
329    
330          while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  sub display {
331            my $name = shift or die "display needs name as first argument";
332            my @o = grep { defined($_) && $_ ne '' } @_;
333            return unless (@o);
334            $out->{$name}->{tag} = $name;
335            $out->{$name}->{display} = \@o;
336    }
337    
338                  my $del = $1 || '';  =head2 search
                 $prefix = $del if ($f_step == 1);  
339    
340                  my $fld_type = lc($2);  Prepare values just for I<search>
341    
342                  # repeatable index    @v = search('Title', rec('200','a') );
                 my $r = $i;  
                 if ($fld_type eq 's') {  
                         if ($found_any->{'v'}) {  
                                 $r = 0;  
                         } else {  
                                 return;  
                         }  
                 }  
343    
344                  my $found = 0;  =cut
                 my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found,$rec_size);  
345    
346                  if ($found) {  sub search {
347                          $found_any->{$fld_type} += $found;          my $name = shift or die "search needs name as first argument";
348            my @o = grep { defined($_) && $_ ne '' } @_;
349            return unless (@o);
350            $out->{$name}->{tag} = $name;
351            $out->{$name}->{search} = \@o;
352    }
353    
354                          # we will skip delimiter before first occurence of field!  =head2 marc
                         push @out, $del unless($found_any->{$fld_type} == 1);  
                         push @out, $tmp;  
                 }  
                 $f_step++;  
         }  
355    
356          # test if any fields found?  Save value for MARC field
         return if (! $found_any->{'v'} && ! $found_any->{'s'});  
357    
358          my $out = join('',@out);    marc('900','a', rec('200','a') );
359    
360          if ($out) {  =cut
                 # add rest of format (suffix)  
                 $out .= $format;  
361    
362                  # add prefix if not there  sub marc {
363                  $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);          my $f = shift or die "marc needs field";
364            die "marc field must be numer" unless ($f =~ /^\d+$/);
365    
366                  $log->debug("result: $out");          my $sf = shift or die "marc needs subfield";
         }  
367    
368          if ($eval_code) {          foreach (@_) {
369                  my $eval = $self->fill_in($rec,$eval_code,$i) || return;                  my $v = $_;             # make var read-write for Encode
370                  $log->debug("about to eval{$eval} format: $out");                  next unless (defined($v) && $v !~ /^\s*$/);
371                  return if (! $self->_eval($eval));                  from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
372          }                  my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' ');
373                            push @{ $marc_record }, [ $f, $i1, $i2, $sf => $v ];
         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}++;  
                 }  
374          }          }
   
         return $out;  
375  }  }
376    
377  =head2 fill_in  =head2 marc_repeatable_subfield
378    
379  Workhourse of all: takes record from in-memory structure of database and  Save values for MARC repetable subfield
 strings with placeholders and returns string or array of with substituted  
 values from record.  
380    
381   my $text = $webpac->fill_in($rec,'v250^a');    marc_repeatable_subfield('910', 'z', rec('909') );
382    
383  Optional argument is ordinal number for repeatable fields. By default,  =cut
 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.  
384    
385   my $text = $webpac->fill_in($rec,'Title: v250^a',1);  sub marc_repeatable_subfield {
386            my ($f,$sf) = @_;
387            die "marc_repeatable_subfield need field and subfield!\n" unless ($f && $sf);
388            $marc_repeatable_subfield->{ $f . $sf }++;
389            marc(@_);
390    }
391    
392  This function B<does not> perform parsing of format to inteligenty skip  =head2 marc_indicators
 delimiters before fields which aren't used.  
393    
394  This method will automatically decode UTF-8 string to local code page  Set both indicators for MARC field
 if needed.  
395    
396  There is optional parametar C<$record_size> which can be used to get sizes of    marc_indicators('900', ' ', 1);
 all C<field^subfield> combinations in this format.  
397    
398   my $text = $webpac->fill_in($rec,'got: v900^a v900^x',0,\$rec_size);  Any indicator value other than C<0-9> will be treated as undefined.
399    
400  =cut  =cut
401    
402  sub fill_in {  sub marc_indicators {
403          my $self = shift;          my $f = shift || die "marc_indicators need field!\n";
404            my ($i1,$i2) = @_;
405            die "marc_indicators($f, ...) need i1!\n" unless(defined($i1));
406            die "marc_indicators($f, $i1, ...) need i2!\n" unless(defined($i2));
407    
408          my $log = $self->_get_logger();          $i1 = ' ' if ($i1 !~ /^\d$/);
409            $i2 = ' ' if ($i2 !~ /^\d$/);
410            @{ $marc_indicators->{$f} } = ($i1,$i2);
411    }
412    
         my ($rec,$format,$i,$rec_size) = @_;  
413    
414          $log->logconfess("need data record") unless ($rec);  =head1 Functions to extract data from input
         $log->logconfess("need format to parse") unless($format);  
415    
416          # iteration (for repeatable fields)  This function should be used inside functions to create C<data_structure> described
417          $i ||= 0;  above.
418    
419          $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999));  =head2 rec1
420    
421          # FIXME remove for speedup?  Return all values in some field
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
422    
423          if (utf8::is_utf8($format)) {    @v = rec1('200')
                 $format = $self->_x($format);  
         }  
424    
425          my $found = 0;  TODO: order of values is probably same as in source data, need to investigate that
         my $just_single = 1;  
426    
427          my $eval_code;  =cut
         # 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);  
   
         {  
                 # fix warnings  
                 no warnings 'uninitialized';  
   
                 # 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;  
                 }  
   
                 # 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);  
                 }  
         }  
428    
429          if ($found) {  sub rec1 {
430                  $log->debug("format: $format");          my $f = shift;
431                  if ($eval_code) {          return unless (defined($rec) && defined($rec->{$f}));
432                          my $eval = $self->fill_in($rec,$eval_code,$i);          if (ref($rec->{$f}) eq 'ARRAY') {
433                          return if (! $self->_eval($eval));                  return map {
434                  }                          if (ref($_) eq 'HASH') {
435                  if ($filter_name && $self->{'filter'}->{$filter_name}) {                                  values %{$_};
                         $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;  
436                          } else {                          } else {
437                                  $log->warn("Have lookup object but can't invoke lookup method");                                  $_;
438                          }                          }
439                  } else {                  } @{ $rec->{$f} };
440                          return $format;          } elsif( defined($rec->{$f}) ) {
441                  }                  return $rec->{$f};
         } else {  
                 return;  
442          }          }
443  }  }
444    
445    =head2 rec2
446    
447  =head2 _rec_to_arr  Return all values in specific field and subfield
   
 Similar to C<parse> and C<fill_in>, but returns array of all repeatable fields. Usable  
 for fields which have lookups, so they shouldn't be parsed but rather  
 C<paste>d or C<fill_id>ed. Last argument is name of operation: C<paste> or C<fill_in>.  
448    
449   my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]','paste');    @v = rec2('200','a')
450    
451  =cut  =cut
452    
453  sub _rec_to_arr {  sub rec2 {
454          my $self = shift;          my $f = shift;
455            return unless (defined($rec && $rec->{$f}));
456            my $sf = shift;
457            return map { $_->{$sf} } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
458    }
459    
460          my ($rec, $format_utf8, $code) = @_;  =head2 rec
461    
462          my $log = $self->_get_logger();  syntaxtic sugar for
463    
464          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);    @v = rec('200')
465          return if (! $format_utf8);    @v = rec('200','a')
466    
467          $log->debug("using $code on $format_utf8");  =cut
468    
469          my $i = 0;  sub rec {
470          my $max = 0;          if ($#_ == 0) {
471          my @arr;                  return rec1(@_);
472          my $rec_size = {};          } elsif ($#_ == 1) {
473                    return rec2(@_);
         while ($i <= $max) {  
                 my @v = $self->$code($rec,$format_utf8,$i++,\$rec_size);  
                 if ($rec_size) {  
                         foreach my $f (keys %{ $rec_size }) {  
                                 $max = $rec_size->{$f} if ($rec_size->{$f} > $max);  
                         }  
                         $log->debug("max set to $max");  
                         undef $rec_size;  
                 }  
                 if (@v) {  
                         push @arr, @v;  
                 } else {  
                         push @arr, '' if ($max > $i);  
                 }  
474          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
475  }  }
476    
477    =head2 regex
478    
479  =head2 get_data  Apply regex to some or all values
   
 Returns value from record.  
   
  my $text = $self->get_data(\$rec,$f,$sf,$i,\$found,\$rec_size);  
   
 Required arguments are:  
   
 =over 8  
   
 =item C<$rec>  
   
 record reference  
   
 =item C<$f>  
   
 field  
   
 =item C<$sf>  
   
 optional subfield  
   
 =item C<$i>  
   
 index offset for repeatable values ( 0 ... $rec_size->{'400^a'} )  
   
 =item C<$found>  
480    
481  optional variable that will be incremeted if preset    @v = regex( 's/foo/bar/g', @v );
   
 =item C<$rec_size>  
   
 hash to hold maximum occurances of C<field^subfield> combinations  
 (which can be accessed using keys in same format)  
   
 =back  
   
 Returns value or empty string, updates C<$found> and C<rec_size>  
 if present.  
482    
483  =cut  =cut
484    
485  sub get_data {  sub regex {
486          my $self = shift;          my $r = shift;
487            my @out;
488          my ($rec,$f,$sf,$i,$found,$cache) = @_;          #warn "r: $r\n", dump(\@_);
489            foreach my $t (@_) {
490          return '' unless ($$rec->{$f} && ref($$rec->{$f}) eq 'ARRAY');                  next unless ($t);
491                    eval "\$t =~ $r";
492          if (defined($$cache)) {                  push @out, $t if ($t && $t ne '');
                 $$cache->{ $f . ( $sf ? '^' . $sf : '' ) } ||= scalar @{ $$rec->{$f} };  
         }  
   
         return '' unless ($$rec->{$f}->[$i]);  
   
         {  
                 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];  
                         }  
                 }  
493          }          }
494            return @out;
495  }  }
496    
497    =head2 prefix
498    
499  =head2 apply_format  Prefix all values with a string
   
 Apply format specified in tag with C<format_name="name"> and  
 C<format_delimiter=";;">.  
500    
501   my $text = $webpac->apply_format($format_name,$format_delimiter,$data);    @v = prefix( 'my_', @v );
   
 Formats can contain C<lookup{...}> if you need them.  
502    
503  =cut  =cut
504    
505  sub apply_format {  sub prefix {
506          my $self = shift;          my $p = shift or die "prefix needs string as first argument";
507            return map { $p . $_ } grep { defined($_) } @_;
508          my ($name,$delimiter,$data) = @_;  }
   
         my $log = $self->_get_logger();  
   
         if (! $self->{'import_xml'}->{'format'}->{$name}) {  
                 $log->warn("<format name=\"$name\"> is not defined in ",$self->{'import_xml_file'});  
                 return $data;  
         }  
   
         $log->warn("no delimiter for format $name") if (! $delimiter);  
509    
510          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  =head2 suffix
511    
512          my @data = split(/\Q$delimiter\E/, $data);  suffix all values with a string
513    
514          my $out = sprintf($format, @data);    @v = suffix( '_my', @v );
         $log->debug("using format $name [$format] on $data to produce: $out");  
515    
516          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {  =cut
                 return $self->{'lookup'}->lookup($out);  
         } else {  
                 return $out;  
         }  
517    
518    sub suffix {
519            my $s = shift or die "suffix needs string as first argument";
520            return map { $_ . $s } grep { defined($_) } @_;
521  }  }
522    
523  =head2 sort_arr  =head2 surround
524    
525  Sort array ignoring case and html in data  surround all values with a two strings
526    
527   my @sorted = $webpac->sort_arr(@unsorted);    @v = surround( 'prefix_', '_suffix', @v );
528    
529  =cut  =cut
530    
531  sub sort_arr {  sub surround {
532          my $self = shift;          my $p = shift or die "surround need prefix as first argument";
533            my $s = shift or die "surround needs suffix as second argument";
534          my $log = $self->_get_logger();          return map { $p . $_ . $s } grep { defined($_) } @_;
   
         # 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;  
535  }  }
536    
537    =head2 first
538    
539  =head1 INTERNAL METHODS  Return first element
   
 =head2 _sort_by_order  
540    
541  Sort xml tags data structure accoding to C<order=""> attribute.    $v = first( @v );
542    
543  =cut  =cut
544    
545  sub _sort_by_order {  sub first {
546          my $self = shift;          my $r = shift;
547            return $r;
         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;  
548  }  }
549    
550  =head2 _x  =head2 lookup
   
 Convert strings from C<conf/normalize/*.xml> encoding into application  
 specific encoding (optinally specified using C<code_page> to C<new>  
 constructor).  
551    
552   my $text = $n->_x('normalize text string');  Consult lookup hashes for some value
553    
554  This is a stub so that other modules doesn't have to implement it.    @v = lookup( $v );
555      @v = lookup( @v );
556    
557  =cut  =cut
558    
559  sub _x {  sub lookup {
560          my $self = shift;          my $k = shift or return;
561          return shift;          return unless (defined($lookup->{$k}));
562            if (ref($lookup->{$k}) eq 'ARRAY') {
563                    return @{ $lookup->{$k} };
564            } else {
565                    return $lookup->{$k};
566            }
567  }  }
568    
569    =head2 join_with
570    
571  =head1 AUTHOR  Joins walues with some delimiter
572    
573  Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>    $v = join_with(", ", @v);
   
 =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.  
574    
575  =cut  =cut
576    
577  1; # End of WebPAC::Normalize  sub join_with {
578            my $d = shift;
579            return join($d, grep { defined($_) && $_ ne '' } @_);
580    }
581    
582    # END
583    1;

Legend:
Removed from v.433  
changed lines
  Added in v.554

  ViewVC Help
Powered by ViewVC 1.1.26