/[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 15 by dpavlin, Sun Jul 17 10:42:23 2005 UTC revision 589 by dpavlin, Fri Jul 7 21:48:09 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 Data::Dumper;  
23  use Storable;  #use base qw/WebPAC::Common/;
24    use Data::Dump qw/dump/;
25    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.01  Version 0.12
39    
40  =cut  =cut
41    
42  our $VERSION = '0.01';  our $VERSION = '0.12';
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      );
73    
74  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
75    other are optional.
76    
77  =item *  This function will B<die> if normalizastion can't be evaled.
78    
79  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
80  perl code that is evaluated before producing output (value of field will be  C<WebPAC::Normalize::data_structure>.
 interpolated before that)  
81    
82  =item *  =cut
83    
84  optional C<filter{filter_name}> at B<begining of format> will apply perl  sub data_structure {
85  code defined as code ref on format after field substitution to producing          my $arg = {@_};
 output  
86    
87  =item *          die "need row argument" unless ($arg->{row});
88            die "need normalisation argument" unless ($arg->{rules});
89    
90  optional C<lookup{...}> will be then performed. See C<WebPAC::Lookups>.          no strict 'subs';
91            _set_lookup( $arg->{lookup} );
92            _set_rec( $arg->{row} );
93            _clean_ds( %{ $arg } );
94            eval "$arg->{rules}";
95            die "error evaling $arg->{rules}: $@\n" if ($@);
96    
97  =item *          return _get_ds();
98    }
99    
100  at end, optional C<format>s rules are resolved. Format rules are similar to  =head2 _set_rec
 C<sprintf> and can also contain C<lookup{...}> which is performed after  
 values are inserted in format.  
101    
102  =back  Set current record hash
103    
104  This also describes order in which transformations are applied (eval,    _set_rec( $rec );
 filter, lookup, format) which is important to undestand when deciding how to  
 solve your data mungling and normalisation process.  
105    
106    =cut
107    
108    my $rec;
109    
110    sub _set_rec {
111            $rec = shift or die "no record hash";
112    }
113    
114  =head1 FUNCTIONS  =head2 _get_ds
115    
116  =head2 new  Return hash formatted as data structure
117    
118  Create new normalisation object    my $ds = _get_ds();
119    
120    my $n = new WebPAC::Normalize::Something(  =cut
         filter => {  
                 'filter_name_1' => sub {  
                         # filter code  
                         return length($_);  
                 }, ...  
         },  
         cache_data_structure => './cache/ds/',  
         lookup_regex => $lookup->regex,  
   );  
121    
122  Parametar C<filter> defines user supplied snippets of perl code which can  my ($out, $marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators);
123  be use with C<filter{...}> notation.  my ($marc_record_offset, $marc_fetch_offset) = (0, 0);
124    
125  Optional parameter C<cache_data_structure> defines path to directory  sub _get_ds {
126  in which cache file for C<data_structure> call will be created.          return $out;
127    }
128    
129  Recommended parametar C<lookup_regex> is used to enable parsing of lookups  =head2 _clean_ds
 in structures.  
130    
131  =cut  Clean data structure hash for next record
132    
133  sub new {    _clean_ds();
         my $class = shift;  
         my $self = {@_};  
         bless($self, $class);  
134    
135          $self->setup_cache_dir( $self->{'cache_data_structure'} );  =cut
136    
137          $self ? return $self : return undef;  sub _clean_ds {
138            my $a = {@_};
139            ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators) = ();
140            ($marc_record_offset, $marc_fetch_offset) = (0,0);
141            $marc_encoding = $a->{marc_encoding};
142  }  }
143    
144  =head2 setup_cache_dir  =head2 _set_lookup
145    
146  Check if specified cache directory exist, and if not, disable caching.  Set current lookup hash
147    
148   $setup_cache_dir('./cache/ds/');    _set_lookup( $lookup );
   
 If you pass false or zero value to this function, it will disable  
 cacheing.  
149    
150  =cut  =cut
151    
152  sub setup_cache_dir {  my $lookup;
         my $self = shift;  
153    
154          my $dir = shift;  sub _set_lookup {
155            $lookup = shift;
156    }
157    
158          my $log = $self->_get_logger();  =head2 _get_marc_fields
159    
160          if ($dir) {  Get all fields defined by calls to C<marc>
                 my $msg;  
                 if (! -e $dir) {  
                         $msg = "doesn't exist";  
                 } elsif (! -d $dir) {  
                         $msg = "is not directory";  
                 } elsif (! -w $dir) {  
                         $msg = "not writable";  
                 }  
161    
162                  if ($msg) {          $marc->add_fields( WebPAC::Normalize:_get_marc_fields() );
                         undef $self->{'cache_data_structure'};  
                         $log->warn("cache_data_structure $dir $msg, disabling...");  
                 } else {  
                         $log->debug("using cache dir $dir");  
                 }  
         } else {  
                 $log->debug("disabling cache");  
                 undef $self->{'cache_data_structure'};  
         }  
 }  
163    
164    We are using I<magic> which detect repeatable fields only from
165    sequence of field/subfield data generated by normalization.
166    
167  =head2 data_structure  Repeatable field is created when there is second occurence of same subfield or
168    if any of indicators are different.
169    
170  Create in-memory data structure which represents normalized layout from  This is sane for most cases. Something like:
 C<conf/normalize/*.xml>.  
171    
172  This structures are used to produce output.    900a-1 900b-1 900c-1
173      900a-2 900b-2
174      900a-3
175    
176   my @ds = $webpac->data_structure($rec);  will be created from any combination of:
177    
178  B<Note: historical oddity follows>    900a-1 900a-2 900a-3 900b-1 900b-2 900c-1
179    
180  This method will also set C<< $webpac->{'currnet_filename'} >> if there is  and following rules:
 C<< <filename> >> tag and C<< $webpac->{'headline'} >> if there is  
 C<< <headline> >> tag.  
181    
182  =cut    marc('900','a', rec('200','a') );
183      marc('900','b', rec('200','b') );
184      marc('900','c', rec('200','c') );
185    
186  sub data_structure {  which might not be what you have in mind. If you need repeatable subfield,
187          my $self = shift;  define it using C<marc_repeatable_subfield> like this:
188    
189          my $log = $self->_get_logger();    marc_repeatable_subfield('900','a');
190      marc('900','a', rec('200','a') );
191      marc('900','b', rec('200','b') );
192      marc('900','c', rec('200','c') );
193    
194          my $rec = shift;  will create:
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
195    
196          my $cache_file;    900a-1 900a-2 900a-3 900b-1 900c-1
197      900b-2
198    
199          if (my $cache_path = $self->{'cache_data_structure'}) {  There is also support for returning next or specific using:
                 my $id = $rec->{'000'};  
                 $id = $rec->{'000'}->[0] if ($id =~ m/^ARRAY/o);  
                 unless (defined($id)) {  
                         $log->warn("Can't use cache_data_structure on records without unique identifier in field 000");  
                         undef $self->{'cache_data_structure'};  
                 } else {  
                         $cache_file = "$cache_path/$id";  
                         if (-r $cache_file) {  
                                 my $ds_ref = retrieve($cache_file);  
                                 if ($ds_ref) {  
                                         $log->debug("cache hit: $cache_file");  
                                         my $ok = 1;  
                                         foreach my $f (qw(current_filename headline)) {  
                                                 if ($ds_ref->{$f}) {  
                                                         $self->{$f} = $ds_ref->{$f};  
                                                 } else {  
                                                         $ok = 0;  
                                                 }  
                                         };  
                                         if ($ok && $ds_ref->{'ds'}) {  
                                                 return @{ $ds_ref->{'ds'} };  
                                         } else {  
                                                 $log->warn("cache_data_structure $cache_path corrupt. Use rm $cache_path/* to re-create it on next run!");  
                                                 undef $self->{'cache_data_structure'};  
                                         }  
                                 }  
                         }  
                 }  
         }  
200    
201          undef $self->{'currnet_filename'};    while (my $mf = WebPAC::Normalize:_get_marc_fields( fetch_next => 1 ) ) {
202          undef $self->{'headline'};          # do something with $mf
203      }
204    
205          my @sorted_tags;  will always return fields from next MARC record or
         if ($self->{tags_by_order}) {  
                 @sorted_tags = @{$self->{tags_by_order}};  
         } else {  
                 @sorted_tags = sort { $self->_sort_by_order } keys %{$self->{'import_xml'}->{'indexer'}};  
                 $self->{tags_by_order} = \@sorted_tags;  
         }  
206    
207          my @ds;    my $mf = WebPAC::Normalize::_get_marc_fields( offset => 42 );
208    
209          $log->debug("tags: ",sub { join(", ",@sorted_tags) });  will return 42th copy record (if it exists).
210    
211          foreach my $field (@sorted_tags) {  =cut
212    
213                  my $row;  sub _get_marc_fields {
214    
215  #print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});          my $arg = {@_};
216            warn "### _get_marc_fields arg: ", dump($arg), $/ if ($debug > 2);
217            my $offset = $marc_fetch_offset;
218            if ($arg->{offset}) {
219                    $offset = $arg->{offset};
220            } elsif($arg->{fetch_next}) {
221                    $marc_fetch_offset++;
222            }
223    
224                  foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {          return if (! $marc_record || ref($marc_record) ne 'ARRAY');
                         my $format = $tag->{'value'} || $tag->{'content'};  
225    
226                          $log->debug("format: $format");          warn "### full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 2);
227    
228                          my @v;          my $marc_rec = $marc_record->[ $offset ];
                         if ($self->{'lookup_regex'} && $format =~ $self->{'lookup_regex'}) {  
                                 @v = $self->fill_in_to_arr($rec,$format);  
                         } else {  
                                 @v = $self->parse_to_arr($rec,$format);  
                         }  
                         next if (! @v);  
229    
230                          if ($tag->{'sort'}) {          warn "## _get_marc_fields (at offset: $offset) -- marc_record = ", dump( @$marc_rec ), $/ if ($debug > 1);
                                 @v = $self->sort_arr(@v);  
                         }  
231    
232                          # use format?          return if (! $marc_rec || ref($marc_rec) ne 'ARRAY' || $#{ $marc_rec } < 0);
                         if ($tag->{'format_name'}) {  
                                 @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  
                         }  
233    
234                          if ($field eq 'filename') {          # first, sort all existing fields
235                                  $self->{'current_filename'} = join('',@v);          # XXX might not be needed, but modern perl might randomize elements in hash
236                                  $log->debug("filename: ",$self->{'current_filename'});          my @sorted_marc_record = sort {
237                          } elsif ($field eq 'headline') {                  $a->[0] . ( $a->[3] || '' ) cmp $b->[0] . ( $b->[3] || '')
238                                  $self->{'headline'} .= join('',@v);          } @{ $marc_rec };
                                 $log->debug("headline: ",$self->{'headline'});  
                                 next; # don't return headline in data_structure!  
                         }  
239    
240                          # delimiter will join repeatable fields          @sorted_marc_record = @{ $marc_rec };   ### FIXME disable sorting
241                          if ($tag->{'delimiter'}) {          
242                                  @v = ( join($tag->{'delimiter'}, @v) );          # output marc fields
243                          }          my @m;
244    
245                          # default types          # count unique field-subfields (used for offset when walking to next subfield)
246                          my @types = qw(display swish);          my $u;
247                          # override by type attribute          map { $u->{ $_->[0] . ( $_->[3] || '')  }++ } @sorted_marc_record;
248                          @types = ( $tag->{'type'} ) if ($tag->{'type'});  
249            if ($debug) {
250                          foreach my $type (@types) {                  warn "## marc_repeatable_subfield = ", dump( $marc_repeatable_subfield ), $/ if ( $marc_repeatable_subfield );
251                                  # append to previous line?                  warn "## marc_record[$offset] = ", dump( $marc_rec ), $/;
252                                  $log->debug("type: $type ",sub { join(" ",@v) }, $row->{'append'} || 'no append');                  warn "## sorted_marc_record = ", dump( \@sorted_marc_record ), $/;
253                                  if ($tag->{'append'}) {                  warn "## subfield count = ", dump( $u ), $/;
254            }
                                         # 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;  
255    
256                                  } else {          my $len = $#sorted_marc_record;
257                                          push @{$row->{$type}}, @v;          my $visited;
258                                  }          my $i = 0;
259                          }          my $field;
260    
261            foreach ( 0 .. $len ) {
262    
263                    # find next element which isn't visited
264                    while ($visited->{$i}) {
265                            $i = ($i + 1) % ($len + 1);
266                  }                  }
267    
268                  if ($row) {                  # mark it visited
269                          $row->{'tag'} = $field;                  $visited->{$i}++;
270    
271                          # TODO: name_sigular, name_plural                  my $row = dclone( $sorted_marc_record[$i] );
                         my $name = $self->{'import_xml'}->{'indexer'}->{$field}->{'name'};  
                         $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");  
                         }  
272    
273                          push @ds, $row;                  # field and subfield which is key for
274                    # marc_repeatable_subfield and u
275                    my $fsf = $row->[0] . ( $row->[3] || '' );
276    
277                    if ($debug > 1) {
278    
279                            print "### field so far [", $#$field, "] : ", dump( $field ), " ", $field ? 'T' : 'F', $/;
280                            print "### this [$i]: ", dump( $row ),$/;
281                            print "### sf: ", $row->[3], " vs ", $field->[3],
282                                    $marc_repeatable_subfield->{ $row->[0] . $row->[3] } ? ' (repeatable)' : '', $/,
283                                    if ($#$field >= 0);
284    
                         $log->debug("row $field: ",sub { Dumper($row) });  
285                  }                  }
286    
287          }                  # if field exists
288                    if ( $#$field >= 0 ) {
289                            if (
290                                    $row->[0] ne $field->[0] ||             # field
291                                    $row->[1] ne $field->[1] ||             # i1
292                                    $row->[2] ne $field->[2]                # i2
293                            ) {
294                                    push @m, $field;
295                                    warn "## saved/1 ", dump( $field ),$/ if ($debug);
296                                    $field = $row;
297    
298                            } elsif (
299                                    ( $row->[3] lt $field->[-2] )           # subfield which is not next (e.g. a after c)
300                                    ||
301                                    ( $row->[3] eq $field->[-2] &&          # same subfield, but not repeatable
302                                            ! $marc_repeatable_subfield->{ $fsf }
303                                    )
304                            ) {
305                                    push @m, $field;
306                                    warn "## saved/2 ", dump( $field ),$/ if ($debug);
307                                    $field = $row;
308    
309                            } else {
310                                    # append new subfields to existing field
311                                    push @$field, ( $row->[3], $row->[4] );
312                            }
313                    } else {
314                            # insert first field
315                            $field = $row;
316                    }
317    
318          if ($cache_file) {                  if (! $marc_repeatable_subfield->{ $fsf }) {
319                  store {                          # make step to next subfield
320                          ds => \@ds,                          $i = ($i + $u->{ $fsf } ) % ($len + 1);
321                          current_filename => $self->{'current_filename'},                  }
                         headline => $self->{'headline'},  
                 }, $cache_file;  
                 $log->debug("created storable cache file $cache_file");  
322          }          }
323    
324          return @ds;          if ($#$field >= 0) {
325                    push @m, $field;
326                    warn "## saved/3 ", dump( $field ),$/ if ($debug);
327            }
328    
329            return \@m;
330  }  }
331    
332  =head2 parse  =head2 _debug
333    
334  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.  
335    
336   my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);    _debug( 2 );
337    
338  =cut  =cut
339    
340  sub parse {  sub _debug {
341          my $self = shift;          my $l = shift;
342            return $debug unless defined($l);
343            warn "debug level $l",$/ if ($l > 0);
344            $debug = $l;
345    }
346    
347    =head1 Functions to create C<data_structure>
348    
349          my ($rec, $format_utf8, $i) = @_;  Those functions generally have to first in your normalization file.
350    
351          return if (! $format_utf8);  =head2 tag
352    
353          my $log = $self->_get_logger();  Define new tag for I<search> and I<display>.
354    
355          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);    tag('Title', rec('200','a') );
356    
         $i = 0 if (! $i);  
357    
358          my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});  =cut
359    
360          my @out;  sub tag {
361            my $name = shift or die "tag needs name as first argument";
362            my @o = grep { defined($_) && $_ ne '' } @_;
363            return unless (@o);
364            $out->{$name}->{tag} = $name;
365            $out->{$name}->{search} = \@o;
366            $out->{$name}->{display} = \@o;
367    }
368    
369    =head2 display
370    
371          $log->debug("format: $format");  Define tag just for I<display>
372    
373          my $eval_code;    @v = display('Title', rec('200','a') );
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
374    
375          my $filter_name;  =cut
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
376    
377          my $prefix;  sub display {
378          my $all_found=0;          my $name = shift or die "display needs name as first argument";
379            my @o = grep { defined($_) && $_ ne '' } @_;
380            return unless (@o);
381            $out->{$name}->{tag} = $name;
382            $out->{$name}->{display} = \@o;
383    }
384    
385          while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  =head2 search
386    
387                  my $del = $1 || '';  Prepare values just for I<search>
                 $prefix ||= $del if ($all_found == 0);  
388    
389                  # repeatable index    @v = search('Title', rec('200','a') );
                 my $r = $i;  
                 $r = 0 if (lc("$2") eq 's');  
390    
391                  my $found = 0;  =cut
                 my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found);  
392    
393                  if ($found) {  sub search {
394                          push @out, $del;          my $name = shift or die "search needs name as first argument";
395                          push @out, $tmp;          my @o = grep { defined($_) && $_ ne '' } @_;
396                          $all_found += $found;          return unless (@o);
397                  }          $out->{$name}->{tag} = $name;
398          }          $out->{$name}->{search} = \@o;
399    }
400    
401          return if (! $all_found);  =head2 marc_leader
402    
403          my $out = join('',@out);  Setup fields within MARC leader or get leader
404    
405          if ($out) {    marc_leader('05','c');
406                  # add rest of format (suffix)    my $leader = marc_leader();
                 $out .= $format;  
407    
408                  # add prefix if not there  =cut
                 $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);  
409    
410                  $log->debug("result: $out");  sub marc_leader {
411          }          my ($offset,$value) = @_;
412    
413          if ($eval_code) {          if ($offset) {
414                  my $eval = $self->fill_in($rec,$eval_code,$i) || return;                  $out->{' leader'}->{ $offset } = $value;
415                  $log->debug("about to eval{$eval} format: $out");          } else {
416                  return if (! $self->_eval($eval));                  return $out->{' leader'};
         }  
           
         if ($filter_name && $self->{'filter'}->{$filter_name}) {  
                 $log->debug("about to filter{$filter_name} format: $out");  
                 $out = $self->{'filter'}->{$filter_name}->($out);  
                 return unless(defined($out));  
                 $log->debug("filter result: $out");  
417          }          }
   
         return $out;  
418  }  }
419    
420  =head2 parse_to_arr  =head2 marc
421    
422  Similar to C<parse>, but returns array of all repeatable fields  Save value for MARC field
423    
424   my @arr = $webpac->parse_to_arr($rec,'v250^a');    marc('900','a', rec('200','a') );
425      marc('001', rec('000') );
426    
427  =cut  =cut
428    
429  sub parse_to_arr {  sub marc {
430          my $self = shift;          my $f = shift or die "marc needs field";
431            die "marc field must be numer" unless ($f =~ /^\d+$/);
432    
433          my ($rec, $format_utf8) = @_;          my $sf;
434            if ($f >= 10) {
435                    $sf = shift or die "marc needs subfield";
436            }
437    
438          my $log = $self->_get_logger();          foreach (@_) {
439                    my $v = $_;             # make var read-write for Encode
440                    next unless (defined($v) && $v !~ /^\s*$/);
441                    from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
442                    my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' ');
443                    if (defined $sf) {
444                            push @{ $marc_record->[ $marc_record_offset ] }, [ $f, $i1, $i2, $sf => $v ];
445                    } else {
446                            push @{ $marc_record->[ $marc_record_offset ] }, [ $f, $v ];
447                    }
448            }
449    }
450    
451          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  =head2 marc_repeatable_subfield
         return if (! $format_utf8);  
452    
453          my $i = 0;  Save values for MARC repetable subfield
         my @arr;  
454    
455          while (my $v = $self->parse($rec,$format_utf8,$i++)) {    marc_repeatable_subfield('910', 'z', rec('909') );
                 push @arr, $v;  
         }  
456    
457          $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  =cut
458    
459          return @arr;  sub marc_repeatable_subfield {
460            my ($f,$sf) = @_;
461            die "marc_repeatable_subfield need field and subfield!\n" unless ($f && $sf);
462            $marc_repeatable_subfield->{ $f . $sf }++;
463            marc(@_);
464  }  }
465    
466    =head2 marc_indicators
467    
468  =head2 fill_in  Set both indicators for MARC field
469    
470  Workhourse of all: takes record from in-memory structure of database and    marc_indicators('900', ' ', 1);
 strings with placeholders and returns string or array of with substituted  
 values from record.  
471    
472   my $text = $webpac->fill_in($rec,'v250^a');  Any indicator value other than C<0-9> will be treated as undefined.
473    
474  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.  
475    
476   my $text = $webpac->fill_in($rec,'Title: v250^a',1);  sub marc_indicators {
477            my $f = shift || die "marc_indicators need field!\n";
478            my ($i1,$i2) = @_;
479            die "marc_indicators($f, ...) need i1!\n" unless(defined($i1));
480            die "marc_indicators($f, $i1, ...) need i2!\n" unless(defined($i2));
481    
482  This function B<does not> perform parsing of format to inteligenty skip          $i1 = ' ' if ($i1 !~ /^\d$/);
483  delimiters before fields which aren't used.          $i2 = ' ' if ($i2 !~ /^\d$/);
484            @{ $marc_indicators->{$f} } = ($i1,$i2);
485    }
486    
487  This method will automatically decode UTF-8 string to local code page  =head2 marc_compose
 if needed.  
488    
489  =cut  Save values for each MARC subfield explicitly
490    
491      marc_compose('900',
492            'a', rec('200','a')
493            'b', rec('201','a')
494            'a', rec('200','b')
495            'c', rec('200','c')
496      );
497    
498  sub fill_in {  =cut
         my $self = shift;  
499    
500          my $log = $self->_get_logger();  sub marc_compose {
501            my $f = shift or die "marc_compose needs field";
502            die "marc_compose field must be numer" unless ($f =~ /^\d+$/);
503    
504          my $rec = shift || $log->logconfess("need data record");          my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' ');
505          my $format = shift || $log->logconfess("need format to parse");          my $m = [ $f, $i1, $i2 ];
         # iteration (for repeatable fields)  
         my $i = shift || 0;  
506    
507          $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999));          warn "### marc_compose input subfields = ", dump(@_),$/ if ($debug > 2);
508    
509          # FIXME remove for speedup?          while (@_) {
510          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);                  my $sf = shift or die "marc_compose $f needs subfield";
511                    my $v = shift;
512    
513          if (utf8::is_utf8($format)) {                  next unless (defined($v) && $v !~ /^\s*$/);
514                  $format = $self->_x($format);                  from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
515                    push @$m, ( $sf, $v );
516                    warn "## ++ marc_compose($f,$sf,$v) ", dump( $m ),$/ if ($debug > 1);
517          }          }
518    
519          my $found = 0;          warn "## marc_compose current marc = ", dump( $m ),$/ if ($debug > 1);
520    
521          my $eval_code;          push @{ $marc_record->[ $marc_record_offset ] }, $m if ($#{$m} > 2);
522          # remove eval{...} from beginning  }
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
523    
524          my $filter_name;  =head2 marc_duplicate
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
525    
526          # do actual replacement of placeholders  Generate copy of current MARC record and continue working on copy
         # repeatable fields  
         $format =~ s/v(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,$i,\$found)/ges;  
         # non-repeatable fields  
         $format =~ s/s(\d+)(?:\^(\w))?/$self->get_data(\$rec,$1,$2,0,\$found)/ges;  
527    
528          if ($found) {    marc_duplicate();
529                  $log->debug("format: $format");  
530                  if ($eval_code) {  Copies can be accessed using C<< _get_marc_fields( fetch_next => 1 ) >> or
531                          my $eval = $self->fill_in($rec,$eval_code,$i);  C<< _get_marc_fields( offset => 42 ) >>.
532                          return if (! $self->_eval($eval));  
533                  }  =cut
534                  if ($filter_name && $self->{'filter'}->{$filter_name}) {  
535                          $log->debug("filter '$filter_name' for $format");  sub marc_duplicate {
536                          $format = $self->{'filter'}->{$filter_name}->($format);           my $m = $marc_record->[ -1 ];
537                          return unless(defined($format));           die "can't duplicate record which isn't defined" unless ($m);
538                          $log->debug("filter result: $format");           push @{ $marc_record }, dclone( $m );
539                  }           warn "## marc_duplicate = ", dump(@$marc_record), $/ if ($debug > 1);
540                  # do we have lookups?           $marc_record_offset = $#{ $marc_record };
541                  if ($self->{'lookup'}) {           warn "## marc_record_offset = $marc_record_offset", $/ if ($debug > 1);
                         return $self->lookup($format);  
                 } else {  
                         return $format;  
                 }  
         } else {  
                 return;  
         }  
542  }  }
543    
544    =head2 marc_remove
545    
546    Remove some field or subfield from MARC record.
547    
548      marc_remove('200');
549      marc_remove('200','a');
550    
551  =head2 fill_in_to_arr  This will erase field C<200> or C<200^a> from current MARC record.
552    
553  Similar to C<fill_in>, but returns array of all repeatable fields. Usable  This is useful after calling C<marc_duplicate> or on it's own (but, you
554  for fields which have lookups, so they shouldn't be parsed but rather  should probably just remove that subfield definition if you are not
555  C<fill_id>ed.  using C<marc_duplicate>).
556    
557   my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]');  FIXME: support fields < 10.
558    
559  =cut  =cut
560    
561  sub fill_in_to_arr {  sub marc_remove {
562          my $self = shift;          my ($f, $sf) = @_;
563    
564          my ($rec, $format_utf8) = @_;          die "marc_remove needs record number" unless defined($f);
565    
566          my $log = $self->_get_logger();          my $marc = $marc_record->[ $marc_record_offset ];
567    
568          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);          warn "### marc_remove before = ", dump( $marc ), $/ if ($debug > 2);
         return if (! $format_utf8);  
569    
570          my $i = 0;          my $i = 0;
571          my @arr;          foreach ( 0 .. $#{ $marc } ) {
572                    last unless (defined $marc->[$i]);
573          while (my @v = $self->fill_in($rec,$format_utf8,$i++)) {                  warn "#### working on ",dump( @{ $marc->[$i] }), $/ if ($debug > 3);
574                  push @arr, @v;                  if ($marc->[$i]->[0] eq $f) {
575                            if (! defined $sf) {
576                                    # remove whole field
577                                    splice @$marc, $i, 1;
578                                    warn "#### slice \@\$marc, $i, 1 = ",dump( @{ $marc }), $/ if ($debug > 3);
579                                    $i--;
580                            } else {
581                                    foreach my $j ( 0 .. (( $#{ $marc->[$i] } - 3 ) / 2) ) {
582                                            my $o = ($j * 2) + 3;
583                                            if ($marc->[$i]->[$o] eq $sf) {
584                                                    # remove subfield
585                                                    splice @{$marc->[$i]}, $o, 2;
586                                                    warn "#### slice \@{\$marc->[$i]}, $o, 2 = ", dump( @{ $marc }), $/ if ($debug > 3);
587                                                    # is record now empty?
588                                                    if ($#{ $marc->[$i] } == 2) {
589                                                            splice @$marc, $i, 1;
590                                                            warn "#### slice \@\$marc, $i, 1 = ", dump( @{ $marc }), $/ if ($debug > 3);
591                                                            $i--;
592                                                    };
593                                            }
594                                    }
595                            }
596                    }
597                    $i++;
598          }          }
599    
600          $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);
601    
602          return @arr;          $marc_record->[ $marc_record_offset ] = $marc;
 }  
603    
604            warn "## full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 1);
605    }
606    
607  =head2 get_data  =head1 Functions to extract data from input
608    
609  Returns value from record.  This function should be used inside functions to create C<data_structure> described
610    above.
611    
612   my $text = $self->get_data(\$rec,$f,$sf,$i,\$found);  =head2 rec1
613    
614  Arguments are:  Return all values in some field
 record reference C<$rec>,  
 field C<$f>,  
 optional subfiled C<$sf>,  
 index for repeatable values C<$i>.  
615    
616  Optinal variable C<$found> will be incremeted if there    @v = rec1('200')
 is field.  
617    
618  Returns value or empty string.  TODO: order of values is probably same as in source data, need to investigate that
619    
620  =cut  =cut
621    
622  sub get_data {  sub rec1 {
623          my $self = shift;          my $f = shift;
624            warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
625          my ($rec,$f,$sf,$i,$found) = @_;          return unless (defined($rec) && defined($rec->{$f}));
626            warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
627          if ($$rec->{$f}) {          if (ref($rec->{$f}) eq 'ARRAY') {
628                  return '' if (! $$rec->{$f}->[$i]);                  return map {
629                  no strict 'refs';                          if (ref($_) eq 'HASH') {
630                  if ($sf && $$rec->{$f}->[$i]->{$sf}) {                                  values %{$_};
                         $$found++ if (defined($$found));  
                         return $$rec->{$f}->[$i]->{$sf};  
                 } elsif ($$rec->{$f}->[$i]) {  
                         $$found++ if (defined($$found));  
                         # it still might have subfield, just  
                         # not specified, so we'll dump all  
                         if ($$rec->{$f}->[$i] =~ /HASH/o) {  
                                 my $out;  
                                 foreach my $k (keys %{$$rec->{$f}->[$i]}) {  
                                         $out .= $$rec->{$f}->[$i]->{$k}." ";  
                                 }  
                                 return $out;  
631                          } else {                          } else {
632                                  return $$rec->{$f}->[$i];                                  $_;
633                          }                          }
634                  }                  } @{ $rec->{$f} };
635          } else {          } elsif( defined($rec->{$f}) ) {
636                  return '';                  return $rec->{$f};
637          }          }
638  }  }
639    
640    =head2 rec2
641    
642  =head2 apply_format  Return all values in specific field and subfield
643    
644  Apply format specified in tag with C<format_name="name"> and    @v = rec2('200','a')
 C<format_delimiter=";;">.  
645    
646   my $text = $webpac->apply_format($format_name,$format_delimiter,$data);  =cut
647    
648  Formats can contain C<lookup{...}> if you need them.  sub rec2 {
649            my $f = shift;
650            return unless (defined($rec && $rec->{$f}));
651            my $sf = shift;
652            return map {
653                    if (ref($_->{$sf}) eq 'ARRAY') {
654                            @{ $_->{$sf} };
655                    } else {
656                            $_->{$sf};
657                    }
658            } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
659    }
660    
661  =cut  =head2 rec
662    
663  sub apply_format {  syntaxtic sugar for
         my $self = shift;  
664    
665          my ($name,$delimiter,$data) = @_;    @v = rec('200')
666      @v = rec('200','a')
667    
668          my $log = $self->_get_logger();  =cut
669    
670          if (! $self->{'import_xml'}->{'format'}->{$name}) {  sub rec {
671                  $log->warn("<format name=\"$name\"> is not defined in ",$self->{'import_xml_file'});          my @out;
672                  return $data;          if ($#_ == 0) {
673                    @out = rec1(@_);
674            } elsif ($#_ == 1) {
675                    @out = rec2(@_);
676          }          }
677            if (@out) {
678                    return @out;
679            } else {
680                    return '';
681            }
682    }
683    
684          $log->warn("no delimiter for format $name") if (! $delimiter);  =head2 regex
685    
686          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  Apply regex to some or all values
687    
688          my @data = split(/\Q$delimiter\E/, $data);    @v = regex( 's/foo/bar/g', @v );
689    
690          my $out = sprintf($format, @data);  =cut
         $log->debug("using format $name [$format] on $data to produce: $out");  
691    
692          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {  sub regex {
693                  return $self->lookup($out);          my $r = shift;
694          } else {          my @out;
695                  return $out;          #warn "r: $r\n", dump(\@_);
696            foreach my $t (@_) {
697                    next unless ($t);
698                    eval "\$t =~ $r";
699                    push @out, $t if ($t && $t ne '');
700          }          }
701            return @out;
702  }  }
703    
704  =head2 sort_arr  =head2 prefix
705    
706  Sort array ignoring case and html in data  Prefix all values with a string
707    
708   my @sorted = $webpac->sort_arr(@unsorted);    @v = prefix( 'my_', @v );
709    
710  =cut  =cut
711    
712  sub sort_arr {  sub prefix {
713          my $self = shift;          my $p = shift or die "prefix needs string as first argument";
714            return map { $p . $_ } grep { defined($_) } @_;
715    }
716    
717    =head2 suffix
718    
719          my $log = $self->_get_logger();  suffix all values with a string
720    
721          # FIXME add Schwartzian Transformation?    @v = suffix( '_my', @v );
722    
723          my @sorted = sort {  =cut
                 $a =~ s#<[^>]+/*>##;  
                 $b =~ s#<[^>]+/*>##;  
                 lc($b) cmp lc($a)  
         } @_;  
         $log->debug("sorted values: ",sub { join(", ",@sorted) });  
724    
725          return @sorted;  sub suffix {
726            my $s = shift or die "suffix needs string as first argument";
727            return map { $_ . $s } grep { defined($_) } @_;
728  }  }
729    
730    =head2 surround
731    
732  =head1 INTERNAL METHODS  surround all values with a two strings
   
 =head2 _sort_by_order  
733    
734  Sort xml tags data structure accoding to C<order=""> attribute.    @v = surround( 'prefix_', '_suffix', @v );
735    
736  =cut  =cut
737    
738  sub _sort_by_order {  sub surround {
739          my $self = shift;          my $p = shift or die "surround need prefix as first argument";
740            my $s = shift or die "surround needs suffix as second argument";
741            return map { $p . $_ . $s } grep { defined($_) } @_;
742    }
743    
744          my $va = $self->{'import_xml'}->{'indexer'}->{$a}->{'order'} ||  =head2 first
                 $self->{'import_xml'}->{'indexer'}->{$a};  
         my $vb = $self->{'import_xml'}->{'indexer'}->{$b}->{'order'} ||  
                 $self->{'import_xml'}->{'indexer'}->{$b};  
745    
746          return $va <=> $vb;  Return first element
 }  
747    
748  =head2 _x    $v = first( @v );
749    
750  Convert strings from C<conf/normalize/*.xml> encoding into application  =cut
751  specific encoding (optinally specified using C<code_page> to C<new>  
752  constructor).  sub first {
753            my $r = shift;
754            return $r;
755    }
756    
757   my $text = $n->_x('normalize text string');  =head2 lookup
758    
759  This is a stub so that other modules doesn't have to implement it.  Consult lookup hashes for some value
760    
761      @v = lookup( $v );
762      @v = lookup( @v );
763    
764  =cut  =cut
765    
766  sub _x {  sub lookup {
767          my $self = shift;          my $k = shift or return;
768          return shift;          return unless (defined($lookup->{$k}));
769            if (ref($lookup->{$k}) eq 'ARRAY') {
770                    return @{ $lookup->{$k} };
771            } else {
772                    return $lookup->{$k};
773            }
774  }  }
775    
776    =head2 join_with
777    
778    Joins walues with some delimiter
779    
780      $v = join_with(", ", @v);
781    
782    =cut
783    
784    sub join_with {
785            my $d = shift;
786            warn "### join_with('$d',",dump(@_),")\n" if ($debug > 2);
787            my $v = join($d, grep { defined($_) && $_ ne '' } @_);
788            return '' unless defined($v);
789            return $v;
790    }
791    
792  =head1 AUTHOR  =head2 split_rec_on
793    
794  Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>  Split record subfield on some regex and take one of parts out
795    
796  =head1 COPYRIGHT & LICENSE    $a_before_semi_column =
797            split_rec_on('200','a', /\s*;\s*/, $part);
798    
799  Copyright 2005 Dobrica Pavlinusic, All Rights Reserved.  C<$part> is optional number of element. First element is
800    B<1>, not 0!
801    
802  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
803  under the same terms as Perl itself.  return all values produced by splitting.
804    
805  =cut  =cut
806    
807  1; # End of WebPAC::DB  sub split_rec_on {
808            die "split_rec_on need (fld,sf,regex[,part]" if ($#_ < 2);
809    
810            my ($fld, $sf, $regex, $part) = @_;
811            warn "### regex ", ref($regex), $regex, $/ if ($debug > 2);
812    
813            my @r = rec( $fld, $sf );
814            my $v = shift @r;
815            warn "### first rec($fld,$sf) = ",dump($v),$/ if ($debug > 2);
816    
817            return '' if( ! defined($v) || $v =~ /^\s*$/);
818    
819            my @s = split( $regex, $v );
820            warn "## split_rec_on($fld,$sf,$regex,$part) = ",dump(@s),$/ if ($debug > 1);
821            if ($part && $part > 0) {
822                    return $s[ $part - 1 ];
823            } else {
824                    return @s;
825            }
826    }
827    
828    # END
829    1;

Legend:
Removed from v.15  
changed lines
  Added in v.589

  ViewVC Help
Powered by ViewVC 1.1.26