/[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 436 by dpavlin, Sun Apr 30 12:17:19 2006 UTC revision 595 by dpavlin, Mon Jul 10 10:16:11 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            marc_compose marc_leader
11            marc_duplicate marc_remove
12    
13            rec1 rec2 rec
14            regex prefix suffix surround
15            first lookup join_with
16    
17            split_rec_on
18    /;
19    
20  use warnings;  use warnings;
21  use strict;  use strict;
22  use blib;  
23  use WebPAC::Common;  #use base qw/WebPAC::Common/;
24  use base 'WebPAC::Common';  use Data::Dump qw/dump/;
25  use Data::Dumper;  use Encode qw/from_to/;
26    use Storable qw/dclone/;
27    
28    # debugging warn(s)
29    my $debug = 0;
30    
31    
32  =head1 NAME  =head1 NAME
33    
34  WebPAC::Normalize - data mungling for normalisation  WebPAC::Normalize - describe normalisaton rules using sets
35    
36  =head1 VERSION  =head1 VERSION
37    
38  Version 0.09  Version 0.14
39    
40  =cut  =cut
41    
42  our $VERSION = '0.09';  our $VERSION = '0.14';
43    
44  =head1 SYNOPSIS  =head1 SYNOPSIS
45    
46  This package contains code that mungle data to produce normalized format.  This module uses C<conf/normalize/*.pl> files to perform normalisation
47    from input records using perl functions which are specialized for set
48    processing.
49    
50    Sets are implemented as arrays, and normalisation file is valid perl, which
51    means that you check it's validity before running WebPAC using
52    C<perl -c normalize.pl>.
53    
54    Normalisation can generate multiple output normalized data. For now, supported output
55    types (on the left side of definition) are: C<tag>, C<display>, C<search> and
56    C<marc>.
57    
58  It contains several assumptions:  =head1 FUNCTIONS
59    
60  =over  Functions which start with C<_> are private and used by WebPAC internally.
61    All other functions are available for use within normalisation rules.
62    
63  =item *  =head2 data_structure
64    
65  format of fields is defined using C<v123^a> notation for repeatable fields  Return data structure
 or C<s123^a> for single (or first) value, where C<123> is field number and  
 C<a> is subfield.  
66    
67  =item *    my $ds = WebPAC::Normalize::data_structure(
68            lookup => $lookup->lookup_hash,
69            row => $row,
70            rules => $normalize_pl_config,
71            marc_encoding => 'utf-8',
72            config => $config,
73      );
74    
75  source data records (C<$rec>) have unique identifiers in field C<000>  Options C<lookup>, C<row>, C<rules> and C<log> are mandatory while all
76    other are optional.
77    
78  =item *  This function will B<die> if normalizastion can't be evaled.
79    
80  optional C<eval{length('v123^a') == 3}> tag at B<beginning of format> will be  Since this function isn't exported you have to call it with
81  perl code that is evaluated before producing output (value of field will be  C<WebPAC::Normalize::data_structure>.
 interpolated before that)  
82    
83  =item *  =cut
84    
85  optional C<filter{filter_name}> at B<begining of format> will apply perl  sub data_structure {
86  code defined as code ref on format after field substitution to producing          my $arg = {@_};
 output  
87    
88  There is one built-in filter called C<regex> which can be use like this:          die "need row argument" unless ($arg->{row});
89            die "need normalisation argument" unless ($arg->{rules});
90    
91    filter{regex(s/foo/bar/)}          no strict 'subs';
92            _set_lookup( $arg->{lookup} );
93            _set_rec( $arg->{row} );
94            _set_config( $arg->{config} );
95            _clean_ds( %{ $arg } );
96            eval "$arg->{rules}";
97            die "error evaling $arg->{rules}: $@\n" if ($@);
98    
99  =item *          return _get_ds();
100    }
101    
102  optional C<lookup{...}> will be then performed. See C<WebPAC::Lookups>.  =head2 _set_rec
103    
104  =item *  Set current record hash
105    
106  at end, optional C<format>s rules are resolved. Format rules are similar to    _set_rec( $rec );
 C<sprintf> and can also contain C<lookup{...}> which is performed after  
 values are inserted in format.  
107    
108  =back  =cut
109    
110  This also describes order in which transformations are applied (eval,  my $rec;
 filter, lookup, format) which is important to undestand when deciding how to  
 solve your data mungling and normalisation process.  
111    
112    sub _set_rec {
113            $rec = shift or die "no record hash";
114    }
115    
116    =head2 _set_config
117    
118    Set current config hash
119    
120  =head1 FUNCTIONS    _set_config( $config );
121    
122  =head2 new  Magic keys are:
123    
124  Create new normalisation object  =over 4
125    
126    my $n = new WebPAC::Normalize::Something(  =item _
         filter => {  
                 'filter_name_1' => sub {  
                         # filter code  
                         return length($_);  
                 }, ...  
         },  
         db => $db_obj,  
         lookup_regex => $lookup->regex,  
         lookup => $lookup_obj,  
         prefix => 'foobar',  
   );  
127    
128  Parametar C<filter> defines user supplied snippets of perl code which can  Code of current database
 be use with C<filter{...}> notation.  
129    
130  C<prefix> is used to form filename for database record (to support multiple  =item _mfn
 source files which are joined in one database).  
131    
132  Recommended parametar C<lookup_regex> is used to enable parsing of lookups  Current MFN
 in structures. If you pass this parametar, you must also pass C<lookup>  
 which is C<WebPAC::Lookup> object.  
133    
134  =cut  =back
135    
136  sub new {  =cut
         my $class = shift;  
         my $self = {@_};  
         bless($self, $class);  
137    
138          my $r = $self->{'lookup_regex'} ? 1 : 0;  my $config;
         my $l = $self->{'lookup'} ? 1 : 0;  
139    
140          my $log = $self->_get_logger();  sub _set_config {
141            $config = shift;
142    }
143    
144          # those two must be in pair  =head2 _get_ds
         if ( ($r & $l) != ($r || $l) ) {  
                 my $log = $self->_get_logger();  
                 $log->logdie("lookup_regex and lookup must be in pair");  
         }  
145    
146          $log->logdie("lookup must be WebPAC::Lookup object") if ($self->{'lookup'} && ! $self->{'lookup'}->isa('WebPAC::Lookup'));  Return hash formatted as data structure
147    
148          $log->warn("no prefix defined. please check that!") unless ($self->{'prefix'});    my $ds = _get_ds();
149    
150          $log->debug("using lookup regex: ", $self->{lookup_regex}) if ($r && $l);  =cut
151    
152          if (! $self->{filter} || ! $self->{filter}->{regex}) {  my ($out, $marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators);
153                  $log->debug("adding built-in filter regex");  my ($marc_record_offset, $marc_fetch_offset) = (0, 0);
                 $self->{filter}->{regex} = sub {  
                         my ($val, $regex) = @_;  
                         eval "\$val =~ $regex";  
                         return $val;  
                 };  
         }  
154    
155          $self ? return $self : return undef;  sub _get_ds {
156            return $out;
157  }  }
158    
159  =head2 all_tags  =head2 _clean_ds
160    
161  Returns all tags in document in specified order  Clean data structure hash for next record
162    
163    my $sorted_tags = $self->all_tags();    _clean_ds();
164    
165  =cut  =cut
166    
167  sub all_tags {  sub _clean_ds {
168          my $self = shift;          my $a = {@_};
169            ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators) = ();
170          if (! $self->{_tags_by_order}) {          ($marc_record_offset, $marc_fetch_offset) = (0,0);
171            $marc_encoding = $a->{marc_encoding};
172    }
173    
174                  my $log = $self->_get_logger;  =head2 _set_lookup
                 # sanity check  
                 $log->logdie("can't find self->{inport_xml}->{indexer}") unless ($self->{import_xml}->{indexer});  
175    
176                  my @tags = keys %{ $self->{'import_xml'}->{'indexer'}};  Set current lookup hash
                 $log->debug("unsorted tags: " . join(", ", @tags));  
177    
178                  @tags = sort { $self->_sort_by_order } @tags;    _set_lookup( $lookup );
179    
180                  $log->debug("sorted tags: " . join(",", @tags) );  =cut
181    
182                  $self->{_tags_by_order} = \@tags;  my $lookup;
         }  
183    
184          return $self->{_tags_by_order};  sub _set_lookup {
185            $lookup = shift;
186  }  }
187    
188    =head2 _get_marc_fields
189    
190    Get all fields defined by calls to C<marc>
191    
192  =head2 data_structure          $marc->add_fields( WebPAC::Normalize:_get_marc_fields() );
193    
194  Create in-memory data structure which represents normalized layout from  We are using I<magic> which detect repeatable fields only from
195  C<conf/normalize/*.xml>.  sequence of field/subfield data generated by normalization.
196    
197  This structures are used to produce output.  Repeatable field is created when there is second occurence of same subfield or
198    if any of indicators are different.
199    
200   my $ds = $webpac->data_structure($rec);  This is sane for most cases. Something like:
201    
202  =cut    900a-1 900b-1 900c-1
203      900a-2 900b-2
204      900a-3
205    
206  sub data_structure {  will be created from any combination of:
         my $self = shift;  
207    
208          my $log = $self->_get_logger();    900a-1 900a-2 900a-3 900b-1 900b-2 900c-1
209    
210          my $rec = shift;  and following rules:
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
211    
212          $log->debug("data_structure rec = ", sub { Dumper($rec) });    marc('900','a', rec('200','a') );
213      marc('900','b', rec('200','b') );
214      marc('900','c', rec('200','c') );
215    
216          $log->logdie("need unique ID (mfn) in field 000 of record " . Dumper($rec) ) unless (defined($rec->{'000'}));  which might not be what you have in mind. If you need repeatable subfield,
217    define it using C<marc_repeatable_subfield> like this:
218    
219          my $id = $rec->{'000'}->[0] || $log->logdie("field 000 isn't array!");    marc_repeatable_subfield('900','a');
220      marc('900','a', rec('200','a') );
221      marc('900','b', rec('200','b') );
222      marc('900','c', rec('200','c') );
223    
224          my $cache_file;  will create:
225    
226          if ($self->{'db'}) {    900a-1 900a-2 900a-3 900b-1 900c-1
227                  my $ds = $self->{'db'}->load_ds( id => $id, prefix => $self->{prefix} );    900b-2
                 $log->debug("load_ds( rec = ", sub { Dumper($rec) }, ") = ", sub { Dumper($ds) });  
                 return $ds if ($ds);  
                 $log->debug("cache miss, creating");  
         }  
228    
229          my $tags = $self->all_tags();  There is also support for returning next or specific using:
230    
231          $log->debug("tags: ",sub { join(", ",@{ $tags }) });    while (my $mf = WebPAC::Normalize:_get_marc_fields( fetch_next => 1 ) ) {
232            # do something with $mf
233      }
234    
235          my $ds;  will always return fields from next MARC record or
236    
237          foreach my $field (@{ $tags }) {    my $mf = WebPAC::Normalize::_get_marc_fields( offset => 42 );
238    
239                  my $row;  will return 42th copy record (if it exists).
240    
241  #print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});  =cut
242    
243                  foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {  sub _get_marc_fields {
                         my $format;  
244    
245                          $log->logdie("expected tag HASH and got $tag") unless (ref($tag) eq 'HASH');          my $arg = {@_};
246                          $format = $tag->{'value'} || $tag->{'content'};          warn "### _get_marc_fields arg: ", dump($arg), $/ if ($debug > 2);
247            my $offset = $marc_fetch_offset;
248            if ($arg->{offset}) {
249                    $offset = $arg->{offset};
250            } elsif($arg->{fetch_next}) {
251                    $marc_fetch_offset++;
252            }
253    
254                          my @v;          return if (! $marc_record || ref($marc_record) ne 'ARRAY');
                         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;  
                         } else {  
                                 $log->debug("$field <",$self->{tag},"> format: $format values: ", join(",", @v));  
                         }  
255    
256                          if ($tag->{'sort'}) {          warn "### full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 2);
                                 @v = $self->sort_arr(@v);  
                         }  
257    
258                          # use format?          my $marc_rec = $marc_record->[ $offset ];
                         if ($tag->{'format_name'}) {  
                                 @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  
                         }  
259    
260                          # delimiter will join repeatable fields          warn "## _get_marc_fields (at offset: $offset) -- marc_record = ", dump( @$marc_rec ), $/ if ($debug > 1);
                         if ($tag->{'delimiter'}) {  
                                 @v = ( join($tag->{'delimiter'}, @v) );  
                         }  
261    
262                          # default types          return if (! $marc_rec || ref($marc_rec) ne 'ARRAY' || $#{ $marc_rec } < 0);
                         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;  
263    
264                                  } else {          # first, sort all existing fields
265                                          push @{$row->{$type}}, @v;          # XXX might not be needed, but modern perl might randomize elements in hash
266                                  }          my @sorted_marc_record = sort {
267                          }                  $a->[0] . ( $a->[3] || '' ) cmp $b->[0] . ( $b->[3] || '')
268            } @{ $marc_rec };
269    
270            @sorted_marc_record = @{ $marc_rec };   ### FIXME disable sorting
271            
272            # output marc fields
273            my @m;
274    
275                  }          # count unique field-subfields (used for offset when walking to next subfield)
276            my $u;
277            map { $u->{ $_->[0] . ( $_->[3] || '')  }++ } @sorted_marc_record;
278    
279            if ($debug) {
280                    warn "## marc_repeatable_subfield = ", dump( $marc_repeatable_subfield ), $/ if ( $marc_repeatable_subfield );
281                    warn "## marc_record[$offset] = ", dump( $marc_rec ), $/;
282                    warn "## sorted_marc_record = ", dump( \@sorted_marc_record ), $/;
283                    warn "## subfield count = ", dump( $u ), $/;
284            }
285    
286                  if ($row) {          my $len = $#sorted_marc_record;
287                          $row->{'tag'} = $field;          my $visited;
288            my $i = 0;
289            my $field;
290    
291                          # TODO: name_sigular, name_plural          foreach ( 0 .. $len ) {
                         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");  
                         }  
292    
293                          $ds->{$row_name} = $row;                  # find next element which isn't visited
294                    while ($visited->{$i}) {
295                            $i = ($i + 1) % ($len + 1);
296                    }
297    
298                    # mark it visited
299                    $visited->{$i}++;
300    
301                    my $row = dclone( $sorted_marc_record[$i] );
302    
303                    # field and subfield which is key for
304                    # marc_repeatable_subfield and u
305                    my $fsf = $row->[0] . ( $row->[3] || '' );
306    
307                    if ($debug > 1) {
308    
309                            print "### field so far [", $#$field, "] : ", dump( $field ), " ", $field ? 'T' : 'F', $/;
310                            print "### this [$i]: ", dump( $row ),$/;
311                            print "### sf: ", $row->[3], " vs ", $field->[3],
312                                    $marc_repeatable_subfield->{ $row->[0] . $row->[3] } ? ' (repeatable)' : '', $/,
313                                    if ($#$field >= 0);
314    
                         $log->debug("row $field: ",sub { Dumper($row) });  
315                  }                  }
316    
317          }                  # if field exists
318                    if ( $#$field >= 0 ) {
319          $self->{'db'}->save_ds(                          if (
320                  id => $id,                                  $row->[0] ne $field->[0] ||             # field
321                  ds => $ds,                                  $row->[1] ne $field->[1] ||             # i1
322                  prefix => $self->{prefix},                                  $row->[2] ne $field->[2]                # i2
323          ) if ($self->{'db'});                          ) {
324                                    push @m, $field;
325                                    warn "## saved/1 ", dump( $field ),$/ if ($debug);
326                                    $field = $row;
327    
328                            } elsif (
329                                    ( $row->[3] lt $field->[-2] )           # subfield which is not next (e.g. a after c)
330                                    ||
331                                    ( $row->[3] eq $field->[-2] &&          # same subfield, but not repeatable
332                                            ! $marc_repeatable_subfield->{ $fsf }
333                                    )
334                            ) {
335                                    push @m, $field;
336                                    warn "## saved/2 ", dump( $field ),$/ if ($debug);
337                                    $field = $row;
338    
339          $log->debug("ds: ", sub { Dumper($ds) });                          } else {
340                                    # append new subfields to existing field
341                                    push @$field, ( $row->[3], $row->[4] );
342                            }
343                    } else {
344                            # insert first field
345                            $field = $row;
346                    }
347    
348          $log->logconfess("data structure returned is not array any more!") if wantarray;                  if (! $marc_repeatable_subfield->{ $fsf }) {
349                            # make step to next subfield
350                            $i = ($i + $u->{ $fsf } ) % ($len + 1);
351                    }
352            }
353    
354          return $ds;          if ($#$field >= 0) {
355                    push @m, $field;
356                    warn "## saved/3 ", dump( $field ),$/ if ($debug);
357            }
358    
359            return \@m;
360  }  }
361    
362  =head2 parse  =head2 _debug
363    
364  Perform smart parsing of string, skipping delimiters for fields which aren't  Change level of debug warnings
 defined. It can also eval code in format starting with C<eval{...}> and  
 return output or nothing depending on eval code.  
365    
366   my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);    _debug( 2 );
367    
368  Filters are implemented here. While simple form of filters looks like this:  =cut
369    
370    filter{name_of_filter}  sub _debug {
371            my $l = shift;
372            return $debug unless defined($l);
373            warn "debug level $l",$/ if ($l > 0);
374            $debug = $l;
375    }
376    
377  but, filters can also have variable number of parametars like this:  =head1 Functions to create C<data_structure>
378    
379    filter{name_of_filter(param,param,param)}  Those functions generally have to first in your normalization file.
380    
381  =cut  =head2 tag
382    
383  my $warn_once;  Define new tag for I<search> and I<display>.
384    
385  sub parse {    tag('Title', rec('200','a') );
         my $self = shift;  
386    
         my ($rec, $format_utf8, $i, $rec_size) = @_;  
387    
388          return if (! $format_utf8);  =cut
389    
390          my $log = $self->_get_logger();  sub tag {
391            my $name = shift or die "tag needs name as first argument";
392            my @o = grep { defined($_) && $_ ne '' } @_;
393            return unless (@o);
394            $out->{$name}->{tag} = $name;
395            $out->{$name}->{search} = \@o;
396            $out->{$name}->{display} = \@o;
397    }
398    
399          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  =head2 display
400    
401          $i = 0 if (! $i);  Define tag just for I<display>
402    
403          my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});    @v = display('Title', rec('200','a') );
404    
405          my @out;  =cut
406    
407          $log->debug("format: $format [$i]");  sub display {
408            my $name = shift or die "display needs name as first argument";
409            my @o = grep { defined($_) && $_ ne '' } @_;
410            return unless (@o);
411            $out->{$name}->{tag} = $name;
412            $out->{$name}->{display} = \@o;
413    }
414    
415          my $eval_code;  =head2 search
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
416    
417          my $filter_name;  Prepare values just for I<search>
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
418    
419          # did we found any (att all) field from format in row?    @v = search('Title', rec('200','a') );
         my $found_any;  
         # prefix before first field which we preserve it $found_any  
         my $prefix;  
420    
421          my $f_step = 1;  =cut
422    
423          while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  sub search {
424            my $name = shift or die "search needs name as first argument";
425            my @o = grep { defined($_) && $_ ne '' } @_;
426            return unless (@o);
427            $out->{$name}->{tag} = $name;
428            $out->{$name}->{search} = \@o;
429    }
430    
431                  my $del = $1 || '';  =head2 marc_leader
                 $prefix = $del if ($f_step == 1);  
432    
433                  my $fld_type = lc($2);  Setup fields within MARC leader or get leader
434    
435                  # repeatable index    marc_leader('05','c');
436                  my $r = $i;    my $leader = marc_leader();
                 if ($fld_type eq 's') {  
                         if ($found_any->{'v'}) {  
                                 $r = 0;  
                         } else {  
                                 return;  
                         }  
                 }  
437    
438                  my $found = 0;  =cut
                 my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found,$rec_size);  
439    
440                  if ($found) {  sub marc_leader {
441                          $found_any->{$fld_type} += $found;          my ($offset,$value) = @_;
442    
443                          # we will skip delimiter before first occurence of field!          if ($offset) {
444                          push @out, $del unless($found_any->{$fld_type} == 1);                  $out->{' leader'}->{ $offset } = $value;
445                          push @out, $tmp if ($tmp);          } else {
446                  }                  return $out->{' leader'};
                 $f_step++;  
447          }          }
448    }
449    
450          # test if any fields found?  =head2 marc
         return if (! $found_any->{'v'} && ! $found_any->{'s'});  
451    
452          my $out = join('',@out);  Save value for MARC field
453    
454          if ($out) {    marc('900','a', rec('200','a') );
455                  # add rest of format (suffix)    marc('001', rec('000') );
                 $out .= $format;  
456    
457                  # add prefix if not there  =cut
                 $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);  
458    
459                  $log->debug("result: $out");  sub marc {
460          }          my $f = shift or die "marc needs field";
461            die "marc field must be numer" unless ($f =~ /^\d+$/);
462    
463          if ($eval_code) {          my $sf;
464                  my $eval = $self->fill_in($rec,$eval_code,$i) || return;          if ($f >= 10) {
465                  $log->debug("about to eval{$eval} format: $out");                  $sf = shift or die "marc needs subfield";
                 return if (! $self->_eval($eval));  
466          }          }
467            
468          if ($filter_name) {          foreach (@_) {
469                  my @filter_args;                  my $v = $_;             # make var read-write for Encode
470                  if ($filter_name =~ s/(\w+)\((.*)\)/$1/) {                  next unless (defined($v) && $v !~ /^\s*$/);
471                          @filter_args = split(/,/, $2);                  from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
472                  }                  my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' ');
473                  if ($self->{'filter'}->{$filter_name}) {                  if (defined $sf) {
474                          $log->debug("about to filter{$filter_name} format: $out with arguments: ", join(",", @filter_args));                          push @{ $marc_record->[ $marc_record_offset ] }, [ $f, $i1, $i2, $sf => $v ];
475                          unshift @filter_args, $out;                  } else {
476                          $out = $self->{'filter'}->{$filter_name}->(@filter_args);                          push @{ $marc_record->[ $marc_record_offset ] }, [ $f, $v ];
                         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}++;  
477                  }                  }
478          }          }
   
         return $out;  
479  }  }
480    
481  =head2 fill_in  =head2 marc_repeatable_subfield
482    
483  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.  
484    
485   my $text = $webpac->fill_in($rec,'v250^a');    marc_repeatable_subfield('910', 'z', rec('909') );
486    
487  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.  
488    
489   my $text = $webpac->fill_in($rec,'Title: v250^a',1);  sub marc_repeatable_subfield {
490            my ($f,$sf) = @_;
491            die "marc_repeatable_subfield need field and subfield!\n" unless ($f && $sf);
492            $marc_repeatable_subfield->{ $f . $sf }++;
493            marc(@_);
494    }
495    
496  This function B<does not> perform parsing of format to inteligenty skip  =head2 marc_indicators
 delimiters before fields which aren't used.  
497    
498  This method will automatically decode UTF-8 string to local code page  Set both indicators for MARC field
 if needed.  
499    
500  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.  
501    
502   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.
503    
504  =cut  =cut
505    
506  sub fill_in {  sub marc_indicators {
507          my $self = shift;          my $f = shift || die "marc_indicators need field!\n";
508            my ($i1,$i2) = @_;
509            die "marc_indicators($f, ...) need i1!\n" unless(defined($i1));
510            die "marc_indicators($f, $i1, ...) need i2!\n" unless(defined($i2));
511    
512          my $log = $self->_get_logger();          $i1 = ' ' if ($i1 !~ /^\d$/);
513            $i2 = ' ' if ($i2 !~ /^\d$/);
514            @{ $marc_indicators->{$f} } = ($i1,$i2);
515    }
516    
517    =head2 marc_compose
518    
519    Save values for each MARC subfield explicitly
520    
521      marc_compose('900',
522            'a', rec('200','a')
523            'b', rec('201','a')
524            'a', rec('200','b')
525            'c', rec('200','c')
526      );
527    
528          my ($rec,$format,$i,$rec_size) = @_;  =cut
529    
530          $log->logconfess("need data record") unless ($rec);  sub marc_compose {
531          $log->logconfess("need format to parse") unless($format);          my $f = shift or die "marc_compose needs field";
532            die "marc_compose field must be numer" unless ($f =~ /^\d+$/);
533    
534          # iteration (for repeatable fields)          my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' ');
535          $i ||= 0;          my $m = [ $f, $i1, $i2 ];
536    
537          $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999));          warn "### marc_compose input subfields = ", dump(@_),$/ if ($debug > 2);
538    
539          # FIXME remove for speedup?          while (@_) {
540          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);                  my $sf = shift or die "marc_compose $f needs subfield";
541                    my $v = shift;
542    
543          if (utf8::is_utf8($format)) {                  next unless (defined($v) && $v !~ /^\s*$/);
544                  $format = $self->_x($format);                  from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
545                    push @$m, ( $sf, $v );
546                    warn "## ++ marc_compose($f,$sf,$v) ", dump( $m ),$/ if ($debug > 1);
547          }          }
548    
549          my $found = 0;          warn "## marc_compose current marc = ", dump( $m ),$/ if ($debug > 1);
         my $just_single = 1;  
550    
551          my $eval_code;          push @{ $marc_record->[ $marc_record_offset ] }, $m if ($#{$m} > 2);
552          # remove eval{...} from beginning  }
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
553    
554          my $filter_name;  =head2 marc_duplicate
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
555    
556          {  Generate copy of current MARC record and continue working on copy
                 # fix warnings  
                 no warnings 'uninitialized';  
557    
558                  # do actual replacement of placeholders    marc_duplicate();
                 # repeatable fields  
                 if ($format =~ s/v(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,$i,\$found,$rec_size)/ges) {  
                         $just_single = 0;  
                 }  
559    
560                  # non-repeatable fields  Copies can be accessed using C<< _get_marc_fields( fetch_next => 1 ) >> or
561                  if ($format =~ s/s(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,0,\$found,$rec_size)/ges) {  C<< _get_marc_fields( offset => 42 ) >>.
                         return if ($i > 0 && $just_single);  
                 }  
         }  
562    
563          if ($found) {  =cut
564                  $log->debug("format: $format");  
565                  if ($eval_code) {  sub marc_duplicate {
566                          my $eval = $self->fill_in($rec,$eval_code,$i);           my $m = $marc_record->[ -1 ];
567                          return if (! $self->_eval($eval));           die "can't duplicate record which isn't defined" unless ($m);
568                  }           push @{ $marc_record }, dclone( $m );
569                  if ($filter_name && $self->{'filter'}->{$filter_name}) {           warn "## marc_duplicate = ", dump(@$marc_record), $/ if ($debug > 1);
570                          $log->debug("filter '$filter_name' for $format");           $marc_record_offset = $#{ $marc_record };
571                          $format = $self->{'filter'}->{$filter_name}->($format);           warn "## marc_record_offset = $marc_record_offset", $/ if ($debug > 1);
                         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;  
                         } else {  
                                 $log->warn("Have lookup object but can't invoke lookup method");  
                         }  
                 } else {  
                         return $format;  
                 }  
         } else {  
                 return;  
         }  
572  }  }
573    
574    =head2 marc_remove
575    
576  =head2 _rec_to_arr  Remove some field or subfield from MARC record.
577    
578  Similar to C<parse> and C<fill_in>, but returns array of all repeatable fields. Usable    marc_remove('200');
579  for fields which have lookups, so they shouldn't be parsed but rather    marc_remove('200','a');
 C<paste>d or C<fill_id>ed. Last argument is name of operation: C<paste> or C<fill_in>.  
580    
581   my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]','paste');  This will erase field C<200> or C<200^a> from current MARC record.
582    
583  =cut  This is useful after calling C<marc_duplicate> or on it's own (but, you
584    should probably just remove that subfield definition if you are not
585    using C<marc_duplicate>).
586    
587  sub _rec_to_arr {  FIXME: support fields < 10.
         my $self = shift;  
588    
589          my ($rec, $format_utf8, $code) = @_;  =cut
590    
591          my $log = $self->_get_logger();  sub marc_remove {
592            my ($f, $sf) = @_;
593    
594          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);          die "marc_remove needs record number" unless defined($f);
         return if (! $format_utf8);  
595    
596          $log->debug("using $code on $format_utf8");          my $marc = $marc_record->[ $marc_record_offset ];
597    
598            warn "### marc_remove before = ", dump( $marc ), $/ if ($debug > 2);
599    
600          my $i = 0;          my $i = 0;
601          my $max = 0;          foreach ( 0 .. $#{ $marc } ) {
602          my @arr;                  last unless (defined $marc->[$i]);
603          my $rec_size = {};                  warn "#### working on ",dump( @{ $marc->[$i] }), $/ if ($debug > 3);
604                    if ($marc->[$i]->[0] eq $f) {
605          while ($i <= $max) {                          if (! defined $sf) {
606                  my @v = $self->$code($rec,$format_utf8,$i++,\$rec_size);                                  # remove whole field
607                  if ($rec_size) {                                  splice @$marc, $i, 1;
608                          foreach my $f (keys %{ $rec_size }) {                                  warn "#### slice \@\$marc, $i, 1 = ",dump( @{ $marc }), $/ if ($debug > 3);
609                                  $max = $rec_size->{$f} if ($rec_size->{$f} > $max);                                  $i--;
610                            } else {
611                                    foreach my $j ( 0 .. (( $#{ $marc->[$i] } - 3 ) / 2) ) {
612                                            my $o = ($j * 2) + 3;
613                                            if ($marc->[$i]->[$o] eq $sf) {
614                                                    # remove subfield
615                                                    splice @{$marc->[$i]}, $o, 2;
616                                                    warn "#### slice \@{\$marc->[$i]}, $o, 2 = ", dump( @{ $marc }), $/ if ($debug > 3);
617                                                    # is record now empty?
618                                                    if ($#{ $marc->[$i] } == 2) {
619                                                            splice @$marc, $i, 1;
620                                                            warn "#### slice \@\$marc, $i, 1 = ", dump( @{ $marc }), $/ if ($debug > 3);
621                                                            $i--;
622                                                    };
623                                            }
624                                    }
625                          }                          }
                         $log->debug("max set to $max");  
                         undef $rec_size;  
                 }  
                 if (@v) {  
                         push @arr, @v;  
                 } else {  
                         push @arr, '' if ($max > $i);  
626                  }                  }
627                    $i++;
628          }          }
629    
630          $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);          warn "### marc_remove($f", $sf ? ",$sf" : "", ") after = ", dump( $marc ), $/ if ($debug > 2);
631    
632          return @arr;          $marc_record->[ $marc_record_offset ] = $marc;
633    
634            warn "## full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 1);
635  }  }
636    
637    =head1 Functions to extract data from input
638    
639  =head2 get_data  This function should be used inside functions to create C<data_structure> described
640    above.
641    
642  Returns value from record.  =head2 rec1
643    
644   my $text = $self->get_data(\$rec,$f,$sf,$i,\$found,\$rec_size);  Return all values in some field
645    
646  Required arguments are:    @v = rec1('200')
647    
648  =over 8  TODO: order of values is probably same as in source data, need to investigate that
649    
650  =item C<$rec>  =cut
651    
652  record reference  sub rec1 {
653            my $f = shift;
654            warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
655            return unless (defined($rec) && defined($rec->{$f}));
656            warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
657            if (ref($rec->{$f}) eq 'ARRAY') {
658                    return map {
659                            if (ref($_) eq 'HASH') {
660                                    values %{$_};
661                            } else {
662                                    $_;
663                            }
664                    } @{ $rec->{$f} };
665            } elsif( defined($rec->{$f}) ) {
666                    return $rec->{$f};
667            }
668    }
669    
670  =item C<$f>  =head2 rec2
671    
672  field  Return all values in specific field and subfield
673    
674  =item C<$sf>    @v = rec2('200','a')
675    
676  optional subfield  =cut
677    
678    sub rec2 {
679            my $f = shift;
680            return unless (defined($rec && $rec->{$f}));
681            my $sf = shift;
682            return map {
683                    if (ref($_->{$sf}) eq 'ARRAY') {
684                            @{ $_->{$sf} };
685                    } else {
686                            $_->{$sf};
687                    }
688            } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
689    }
690    
691  =item C<$i>  =head2 rec
692    
693  index offset for repeatable values ( 0 ... $rec_size->{'400^a'} )  syntaxtic sugar for
694    
695  =item C<$found>    @v = rec('200')
696      @v = rec('200','a')
697    
698  optional variable that will be incremeted if preset  =cut
699    
700  =item C<$rec_size>  sub rec {
701            my @out;
702            if ($#_ == 0) {
703                    @out = rec1(@_);
704            } elsif ($#_ == 1) {
705                    @out = rec2(@_);
706            }
707            if (@out) {
708                    return @out;
709            } else {
710                    return '';
711            }
712    }
713    
714  hash to hold maximum occurances of C<field^subfield> combinations  =head2 regex
 (which can be accessed using keys in same format)  
715    
716  =back  Apply regex to some or all values
717    
718  Returns value or empty string, updates C<$found> and C<rec_size>    @v = regex( 's/foo/bar/g', @v );
 if present.  
719    
720  =cut  =cut
721    
722  sub get_data {  sub regex {
723          my $self = shift;          my $r = shift;
724            my @out;
725            #warn "r: $r\n", dump(\@_);
726            foreach my $t (@_) {
727                    next unless ($t);
728                    eval "\$t =~ $r";
729                    push @out, $t if ($t && $t ne '');
730            }
731            return @out;
732    }
733    
734          my ($rec,$f,$sf,$i,$found,$cache) = @_;  =head2 prefix
735    
736          return '' unless ($$rec->{$f} && ref($$rec->{$f}) eq 'ARRAY');  Prefix all values with a string
737    
738          if (defined($$cache)) {    @v = prefix( 'my_', @v );
                 $$cache->{ $f . ( $sf ? '^' . $sf : '' ) } ||= scalar @{ $$rec->{$f} };  
         }  
739    
740          return '' unless ($$rec->{$f}->[$i]);  =cut
741    
742          {  sub prefix {
743                  no strict 'refs';          my $p = shift or return;
744                  if (defined($sf)) {          return map { $p . $_ } grep { defined($_) } @_;
                         $$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]}) {  
                                         my $v = $$rec->{$f}->[$i]->{$k};  
                                         $out .= '$' . $k .':' . $v if ($v);  
                                 }  
                                 return $out;  
                         } else {  
                                 return $$rec->{$f}->[$i];  
                         }  
                 }  
         }  
745  }  }
746    
747    =head2 suffix
748    
749    suffix all values with a string
750    
751      @v = suffix( '_my', @v );
752    
753    =cut
754    
755  =head2 apply_format  sub suffix {
756            my $s = shift or die "suffix needs string as first argument";
757            return map { $_ . $s } grep { defined($_) } @_;
758    }
759    
760  Apply format specified in tag with C<format_name="name"> and  =head2 surround
 C<format_delimiter=";;">.  
761    
762   my $text = $webpac->apply_format($format_name,$format_delimiter,$data);  surround all values with a two strings
763    
764  Formats can contain C<lookup{...}> if you need them.    @v = surround( 'prefix_', '_suffix', @v );
765    
766  =cut  =cut
767    
768  sub apply_format {  sub surround {
769          my $self = shift;          my $p = shift or die "surround need prefix as first argument";
770            my $s = shift or die "surround needs suffix as second argument";
771            return map { $p . $_ . $s } grep { defined($_) } @_;
772    }
773    
774          my ($name,$delimiter,$data) = @_;  =head2 first
775    
776          my $log = $self->_get_logger();  Return first element
777    
778          if (! $self->{'import_xml'}->{'format'}->{$name}) {    $v = first( @v );
                 $log->warn("<format name=\"$name\"> is not defined in ",$self->{'import_xml_file'});  
                 return $data;  
         }  
779    
780          $log->warn("no delimiter for format $name") if (! $delimiter);  =cut
781    
782    sub first {
783            my $r = shift;
784            return $r;
785    }
786    
787          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  =head2 lookup
788    
789          my @data = split(/\Q$delimiter\E/, $data);  Consult lookup hashes for some value
790    
791          my $out = sprintf($format, @data);    @v = lookup( $v );
792          $log->debug("using format $name [$format] on $data to produce: $out");    @v = lookup( @v );
793    
794          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {  =cut
795                  return $self->{'lookup'}->lookup($out);  
796    sub lookup {
797            my $k = shift or return;
798            return unless (defined($lookup->{$k}));
799            if (ref($lookup->{$k}) eq 'ARRAY') {
800                    return @{ $lookup->{$k} };
801          } else {          } else {
802                  return $out;                  return $lookup->{$k};
803          }          }
   
804  }  }
805    
806  =head2 sort_arr  =head2 config
807    
808  Sort array ignoring case and html in data  Consult config values stored in C<config.yml>
809    
810   my @sorted = $webpac->sort_arr(@unsorted);    # return database code (key under databases in yaml)
811      $database_code = config();    # use _ from hash
812      $database_name = config('name');
813      $database_input_name = config('input name');
814      $tag = config('input normalize tag');
815    
816  =cut  Up to three levels are supported.
817    
818  sub sort_arr {  =cut
         my $self = shift;  
819    
820          my $log = $self->_get_logger();  sub config {
821            return unless ($config);
822    
823          # FIXME add Schwartzian Transformation?          my $p = shift;
824    
825          my @sorted = sort {          $p ||= '';
                 $a =~ s#<[^>]+/*>##;  
                 $b =~ s#<[^>]+/*>##;  
                 lc($b) cmp lc($a)  
         } @_;  
         $log->debug("sorted values: ",sub { join(", ",@sorted) });  
826    
827          return @sorted;          my $v;
 }  
828    
829            warn "### getting config($p)\n" if ($debug > 1);
830    
831  =head1 INTERNAL METHODS          my @p = split(/\s+/,$p);
832            if ($#p < 0) {
833                    $v = $config->{ '_' };  # special, database code
834            } else {
835    
836  =head2 _sort_by_order                  my $c = dclone( $config );
837    
838  Sort xml tags data structure accoding to C<order=""> attribute.                  foreach my $k (@p) {
839                            warn "### k: $k c = ",dump($c),$/ if ($debug > 1);
840                            if (ref($c) eq 'ARRAY') {
841                                    $c = shift @$c;
842                                    warn "config($p) taking first occurence of '$k', probably not what you wanted!\n";
843                                    last;
844                            }
845    
846  =cut                          if (! defined($c->{$k}) ) {
847                                    $c = undef;
848                                    last;
849                            } else {
850                                    $c = $c->{$k};
851                            }
852                    }
853                    $v = $c if ($c);
854    
855  sub _sort_by_order {          }
         my $self = shift;  
856    
857          my $va = $self->{'import_xml'}->{'indexer'}->{$a}->{'order'} ||          warn "## config( '$p' ) = ",dump( $v ),$/ if ($v && $debug);
858                  $self->{'import_xml'}->{'indexer'}->{$a};          warn "config( '$p' ) is empty\n" if (! $v);
         my $vb = $self->{'import_xml'}->{'indexer'}->{$b}->{'order'} ||  
                 $self->{'import_xml'}->{'indexer'}->{$b};  
859    
860          return $va <=> $vb;          return $v;
861  }  }
862    
863  =head2 _x  =head2 id
864    
865  Convert strings from C<conf/normalize/*.xml> encoding into application  Returns unique id of this record
 specific encoding (optinally specified using C<code_page> to C<new>  
 constructor).  
866    
867   my $text = $n->_x('normalize text string');    $id = id();
868    
869  This is a stub so that other modules doesn't have to implement it.  Returns C<42/2> for 2nd occurence of MFN 42.
870    
871  =cut  =cut
872    
873  sub _x {  sub id {
874          my $self = shift;          my $mfn = $config->{_mfn} || die "no _mfn in config data";
875          return shift;          return $mfn . $#{$marc_record} ? $#{$marc_record} + 1 : '';
876  }  }
877    
878    =head2 join_with
879    
880    Joins walues with some delimiter
881    
882      $v = join_with(", ", @v);
883    
884    =cut
885    
886    sub join_with {
887            my $d = shift;
888            warn "### join_with('$d',",dump(@_),")\n" if ($debug > 2);
889            my $v = join($d, grep { defined($_) && $_ ne '' } @_);
890            return '' unless defined($v);
891            return $v;
892    }
893    
894  =head1 AUTHOR  =head2 split_rec_on
895    
896  Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>  Split record subfield on some regex and take one of parts out
897    
898  =head1 COPYRIGHT & LICENSE    $a_before_semi_column =
899            split_rec_on('200','a', /\s*;\s*/, $part);
900    
901  Copyright 2005 Dobrica Pavlinusic, All Rights Reserved.  C<$part> is optional number of element. First element is
902    B<1>, not 0!
903    
904  This program is free software; you can redistribute it and/or modify it  If there is no C<$part> parameter or C<$part> is 0, this function will
905  under the same terms as Perl itself.  return all values produced by splitting.
906    
907  =cut  =cut
908    
909  1; # End of WebPAC::Normalize  sub split_rec_on {
910            die "split_rec_on need (fld,sf,regex[,part]" if ($#_ < 2);
911    
912            my ($fld, $sf, $regex, $part) = @_;
913            warn "### regex ", ref($regex), $regex, $/ if ($debug > 2);
914    
915            my @r = rec( $fld, $sf );
916            my $v = shift @r;
917            warn "### first rec($fld,$sf) = ",dump($v),$/ if ($debug > 2);
918    
919            return '' if( ! defined($v) || $v =~ /^\s*$/);
920    
921            my @s = split( $regex, $v );
922            warn "## split_rec_on($fld,$sf,$regex,$part) = ",dump(@s),$/ if ($debug > 1);
923            if ($part && $part > 0) {
924                    return $s[ $part - 1 ];
925            } else {
926                    return @s;
927            }
928    }
929    
930    # END
931    1;

Legend:
Removed from v.436  
changed lines
  Added in v.595

  ViewVC Help
Powered by ViewVC 1.1.26