/[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 22 by dpavlin, Sun Jul 17 22:48:25 2005 UTC revision 603 by dpavlin, Sun Jul 23 20:19:56 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 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.15
39    
40  =cut  =cut
41    
42  our $VERSION = '0.01';  our $VERSION = '0.15';
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  =item *          die "need row argument" unless ($arg->{row});
89            die "need normalisation argument" unless ($arg->{rules});
90    
91  optional C<lookup{...}> will be then performed. See C<WebPAC::Lookups>.          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  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.  
103    
104  =back  Set current record hash
105    
106  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.  
107    
108    =cut
109    
110    my $rec;
111    
112    sub _set_rec {
113            $rec = shift or die "no record hash";
114    }
115    
116  =head1 FUNCTIONS  =head2 _set_config
117    
118  =head2 new  Set current config hash
119    
120  Create new normalisation object    _set_config( $config );
121    
122    my $n = new WebPAC::Normalize::Something(  Magic keys are:
         filter => {  
                 'filter_name_1' => sub {  
                         # filter code  
                         return length($_);  
                 }, ...  
         },  
         db => $webpac_db_obj,  
         lookup_regex => $lookup->regex,  
   );  
123    
124  Parametar C<filter> defines user supplied snippets of perl code which can  =over 4
 be use with C<filter{...}> notation.  
125    
126  Recommended parametar C<lookup_regex> is used to enable parsing of lookups  =item _
 in structures.  
127    
128  =cut  Code of current database
129    
130  sub new {  =item _mfn
         my $class = shift;  
         my $self = {@_};  
         bless($self, $class);  
131    
132          $self ? return $self : return undef;  Current MFN
 }  
133    
134    =back
135    
136  =head2 data_structure  =cut
137    
138  Create in-memory data structure which represents normalized layout from  my $config;
 C<conf/normalize/*.xml>.  
139    
140  This structures are used to produce output.  sub _set_config {
141            $config = shift;
142    }
143    
144   my @ds = $webpac->data_structure($rec);  =head2 _get_ds
145    
146  B<Note: historical oddity follows>  Return hash formatted as data structure
147    
148  This method will also set C<< $webpac->{'currnet_filename'} >> if there is    my $ds = _get_ds();
 C<< <filename> >> tag and C<< $webpac->{'headline'} >> if there is  
 C<< <headline> >> tag.  
149    
150  =cut  =cut
151    
152  sub data_structure {  my ($out, $marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators);
153          my $self = shift;  my ($marc_record_offset, $marc_fetch_offset) = (0, 0);
154    
155          my $log = $self->_get_logger();  sub _get_ds {
156            return $out;
157    }
158    
159          my $rec = shift;  =head2 _clean_ds
         $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  
160    
161          my $cache_file;  Clean data structure hash for next record
162    
163          if ($self->{'db'}) {    _clean_ds();
                 my @ds = $self->{'db'}->load_ds($rec);  
                 return @ds if (@ds);  
         }  
164    
165          undef $self->{'currnet_filename'};  =cut
         undef $self->{'headline'};  
   
         my @sorted_tags;  
         if ($self->{tags_by_order}) {  
                 @sorted_tags = @{$self->{tags_by_order}};  
         } else {  
                 @sorted_tags = sort { $self->_sort_by_order } keys %{$self->{'import_xml'}->{'indexer'}};  
                 $self->{tags_by_order} = \@sorted_tags;  
         }  
166    
167          my @ds;  sub _clean_ds {
168            my $a = {@_};
169            ($out,$marc_record, $marc_encoding, $marc_repeatable_subfield, $marc_indicators) = ();
170            ($marc_record_offset, $marc_fetch_offset) = (0,0);
171            $marc_encoding = $a->{marc_encoding};
172    }
173    
174          $log->debug("tags: ",sub { join(", ",@sorted_tags) });  =head2 _set_lookup
175    
176          foreach my $field (@sorted_tags) {  Set current lookup hash
177    
178                  my $row;    _set_lookup( $lookup );
179    
180  #print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});  =cut
181    
182                  foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {  my $lookup;
                         my $format = $tag->{'value'} || $tag->{'content'};  
183    
184                          $log->debug("format: $format");  sub _set_lookup {
185            $lookup = shift;
186    }
187    
188                          my @v;  =head2 _get_marc_fields
                         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);  
189    
190                          if ($tag->{'sort'}) {  Get all fields defined by calls to C<marc>
                                 @v = $self->sort_arr(@v);  
                         }  
191    
192                          # use format?          $marc->add_fields( WebPAC::Normalize:_get_marc_fields() );
                         if ($tag->{'format_name'}) {  
                                 @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  
                         }  
193    
194                          if ($field eq 'filename') {  We are using I<magic> which detect repeatable fields only from
195                                  $self->{'current_filename'} = join('',@v);  sequence of field/subfield data generated by normalization.
                                 $log->debug("filename: ",$self->{'current_filename'});  
                         } elsif ($field eq 'headline') {  
                                 $self->{'headline'} .= join('',@v);  
                                 $log->debug("headline: ",$self->{'headline'});  
                                 next; # don't return headline in data_structure!  
                         }  
196    
197                          # delimiter will join repeatable fields  Repeatable field is created when there is second occurence of same subfield or
198                          if ($tag->{'delimiter'}) {  if any of indicators are different.
                                 @v = ( join($tag->{'delimiter'}, @v) );  
                         }  
199    
200                          # default types  This is sane for most cases. Something like:
                         my @types = qw(display swish);  
                         # override by type attribute  
                         @types = ( $tag->{'type'} ) if ($tag->{'type'});  
   
                         foreach my $type (@types) {  
                                 # append to previous line?  
                                 $log->debug("type: $type ",sub { join(" ",@v) }, $row->{'append'} || 'no append');  
                                 if ($tag->{'append'}) {  
   
                                         # I will delimit appended part with  
                                         # delimiter (or ,)  
                                         my $d = $tag->{'delimiter'};  
                                         # default delimiter  
                                         $d ||= " ";  
   
                                         my $last = pop @{$row->{$type}};  
                                         $d = "" if (! $last);  
                                         $last .= $d . join($d, @v);  
                                         push @{$row->{$type}}, $last;  
201    
202                                  } else {    900a-1 900b-1 900c-1
203                                          push @{$row->{$type}}, @v;    900a-2 900b-2
204                                  }    900a-3
                         }  
205    
206    will be created from any combination of:
207    
208                  }    900a-1 900a-2 900a-3 900b-1 900b-2 900c-1
209    
210                  if ($row) {  and following rules:
                         $row->{'tag'} = $field;  
211    
212                          # TODO: name_sigular, name_plural    marc('900','a', rec('200','a') );
213                          my $name = $self->{'import_xml'}->{'indexer'}->{$field}->{'name'};    marc('900','b', rec('200','b') );
214                          $row->{'name'} = $name ? $self->_x($name) : $field;    marc('900','c', rec('200','c') );
   
                         # post-sort all values in field  
                         if ($self->{'import_xml'}->{'indexer'}->{$field}->{'sort'}) {  
                                 $log->warn("sort at field tag not implemented");  
                         }  
215    
216                          push @ds, $row;  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                          $log->debug("row $field: ",sub { Dumper($row) });    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          }  will create:
225    
226          $self->{'db'}->save_ds(    900a-1 900a-2 900a-3 900b-1 900c-1
227                  ds => \@ds,    900b-2
                 current_filename => $self->{'current_filename'},  
                 headline => $self->{'headline'},  
         ) if ($self->{'db'});  
228    
229          return @ds;  There is also support for returning next or specific using:
230    
231  }    while (my $mf = WebPAC::Normalize:_get_marc_fields( fetch_next => 1 ) ) {
232            # do something with $mf
233      }
234    
235  =head2 parse  will always return fields from next MARC record or
236    
237  Perform smart parsing of string, skipping delimiters for fields which aren't    my $mf = WebPAC::Normalize::_get_marc_fields( offset => 42 );
 defined. It can also eval code in format starting with C<eval{...}> and  
 return output or nothing depending on eval code.  
238    
239   my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);  will return 42th copy record (if it exists).
240    
241  =cut  =cut
242    
243  sub parse {  sub _get_marc_fields {
         my $self = shift;  
244    
245          my ($rec, $format_utf8, $i) = @_;          my $arg = {@_};
246            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          return if (! $format_utf8);          return if (! $marc_record || ref($marc_record) ne 'ARRAY');
255    
256          my $log = $self->_get_logger();          warn "### full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 2);
257    
258          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);          my $marc_rec = $marc_record->[ $offset ];
259    
260          $i = 0 if (! $i);          warn "## _get_marc_fields (at offset: $offset) -- marc_record = ", dump( @$marc_rec ), $/ if ($debug > 1);
261    
262          my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});          return if (! $marc_rec || ref($marc_rec) ne 'ARRAY' || $#{ $marc_rec } < 0);
263    
264          my @out;          # first, sort all existing fields
265            # 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          $log->debug("format: $format");          @sorted_marc_record = @{ $marc_rec };   ### FIXME disable sorting
271            
272            # output marc fields
273            my @m;
274    
275          my $eval_code;          # count unique field-subfields (used for offset when walking to next subfield)
276          # remove eval{...} from beginning          my $u;
277          $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);          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          my $filter_name;          my $len = $#sorted_marc_record;
287          # remove filter{...} from beginning          my $visited;
288          $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);          my $i = 0;
289            my $field;
290    
291          my $prefix;          foreach ( 0 .. $len ) {
         my $all_found=0;  
292    
293          while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {                  # find next element which isn't visited
294                    while ($visited->{$i}) {
295                            $i = ($i + 1) % ($len + 1);
296                    }
297    
298                  my $del = $1 || '';                  # mark it visited
299                  $prefix ||= $del if ($all_found == 0);                  $visited->{$i}++;
300    
301                  # repeatable index                  my $row = dclone( $sorted_marc_record[$i] );
                 my $r = $i;  
                 $r = 0 if (lc("$2") eq 's');  
302    
303                  my $found = 0;                  # field and subfield which is key for
304                  my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found);                  # 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    
                 if ($found) {  
                         push @out, $del;  
                         push @out, $tmp;  
                         $all_found += $found;  
315                  }                  }
         }  
316    
317          return if (! $all_found);                  # if field exists
318                    if ( $#$field >= 0 ) {
319                            if (
320                                    $row->[0] ne $field->[0] ||             # field
321                                    $row->[1] ne $field->[1] ||             # i1
322                                    $row->[2] ne $field->[2]                # i2
323                            ) {
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          my $out = join('',@out);                          } else {
340                                    # append new subfields to existing field
341          if ($out) {                                  push @$field, ( $row->[3], $row->[4] );
342                  # add rest of format (suffix)                          }
343                  $out .= $format;                  } else {
344                            # insert first field
345                  # add prefix if not there                          $field = $row;
346                  $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);                  }
347    
348                  $log->debug("result: $out");                  if (! $marc_repeatable_subfield->{ $fsf }) {
349                            # make step to next subfield
350                            $i = ($i + $u->{ $fsf } ) % ($len + 1);
351                    }
352          }          }
353    
354          if ($eval_code) {          if ($#$field >= 0) {
355                  my $eval = $self->fill_in($rec,$eval_code,$i) || return;                  push @m, $field;
356                  $log->debug("about to eval{$eval} format: $out");                  warn "## saved/3 ", dump( $field ),$/ if ($debug);
                 return if (! $self->_eval($eval));  
         }  
           
         if ($filter_name && $self->{'filter'}->{$filter_name}) {  
                 $log->debug("about to filter{$filter_name} format: $out");  
                 $out = $self->{'filter'}->{$filter_name}->($out);  
                 return unless(defined($out));  
                 $log->debug("filter result: $out");  
357          }          }
358    
359          return $out;          return \@m;
360  }  }
361    
362  =head2 parse_to_arr  =head2 _debug
363    
364  Similar to C<parse>, but returns array of all repeatable fields  Change level of debug warnings
365    
366   my @arr = $webpac->parse_to_arr($rec,'v250^a');    _debug( 2 );
367    
368  =cut  =cut
369    
370  sub parse_to_arr {  sub _debug {
371          my $self = shift;          my $l = shift;
372            return $debug unless defined($l);
373            warn "debug level $l",$/ if ($l > 0);
374            $debug = $l;
375    }
376    
377          my ($rec, $format_utf8) = @_;  =head1 Functions to create C<data_structure>
378    
379          my $log = $self->_get_logger();  Those functions generally have to first in your normalization file.
380    
381          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  =head2 tag
         return if (! $format_utf8);  
382    
383          my $i = 0;  Define new tag for I<search> and I<display>.
384          my @arr;  
385      tag('Title', rec('200','a') );
386    
         while (my $v = $self->parse($rec,$format_utf8,$i++)) {  
                 push @arr, $v;  
         }  
387    
388          $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  =cut
389    
390          return @arr;  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    =head2 display
400    
401  =head2 fill_in  Define tag just for I<display>
402    
403  Workhourse of all: takes record from in-memory structure of database and    @v = display('Title', rec('200','a') );
 strings with placeholders and returns string or array of with substituted  
 values from record.  
404    
405   my $text = $webpac->fill_in($rec,'v250^a');  =cut
406    
407  Optional argument is ordinal number for repeatable fields. By default,  sub display {
408  it's assume to be first repeatable field (fields are perl array, so first          my $name = shift or die "display needs name as first argument";
409  element is 0).          my @o = grep { defined($_) && $_ ne '' } @_;
410  Following example will read second value from repeatable field.          return unless (@o);
411            $out->{$name}->{tag} = $name;
412            $out->{$name}->{display} = \@o;
413    }
414    
415   my $text = $webpac->fill_in($rec,'Title: v250^a',1);  =head2 search
416    
417  This function B<does not> perform parsing of format to inteligenty skip  Prepare values just for I<search>
 delimiters before fields which aren't used.  
418    
419  This method will automatically decode UTF-8 string to local code page    @v = search('Title', rec('200','a') );
 if needed.  
420    
421  =cut  =cut
422    
423  sub fill_in {  sub search {
424          my $self = shift;          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    =head2 marc_leader
432    
433          my $log = $self->_get_logger();  Setup fields within MARC leader or get leader
434    
435          my $rec = shift || $log->logconfess("need data record");    marc_leader('05','c');
436          my $format = shift || $log->logconfess("need format to parse");    my $leader = marc_leader();
         # iteration (for repeatable fields)  
         my $i = shift || 0;  
437    
438          $log->logdie("infitite loop in format $format") if ($i > ($self->{'max_mfn'} || 9999));  =cut
439    
440          # FIXME remove for speedup?  sub marc_leader {
441          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);          my ($offset,$value) = @_;
442    
443          if (utf8::is_utf8($format)) {          if ($offset) {
444                  $format = $self->_x($format);                  $out->{' leader'}->{ $offset } = $value;
445            } else {
446                    return $out->{' leader'};
447          }          }
448    }
449    
450          my $found = 0;  =head2 marc
451    
452          my $eval_code;  Save value for MARC field
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
453    
454          my $filter_name;    marc('900','a', rec('200','a') );
455          # remove filter{...} from beginning    marc('001', rec('000') );
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
456    
457          # do actual replacement of placeholders  =cut
         # 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;  
458    
459          if ($found) {  sub marc {
460                  $log->debug("format: $format");          my $f = shift or die "marc needs field";
461                  if ($eval_code) {          die "marc field must be numer" unless ($f =~ /^\d+$/);
462                          my $eval = $self->fill_in($rec,$eval_code,$i);  
463                          return if (! $self->_eval($eval));          my $sf;
464                  }          if ($f >= 10) {
465                  if ($filter_name && $self->{'filter'}->{$filter_name}) {                  $sf = shift or die "marc needs subfield";
466                          $log->debug("filter '$filter_name' for $format");          }
467                          $format = $self->{'filter'}->{$filter_name}->($format);  
468                          return unless(defined($format));          foreach (@_) {
469                          $log->debug("filter result: $format");                  my $v = $_;             # make var read-write for Encode
470                  }                  next unless (defined($v) && $v !~ /^\s*$/);
471                  # do we have lookups?                  from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
472                  if ($self->{'lookup'}) {                  my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' ');
473                          return $self->lookup($format);                  if (defined $sf) {
474                            push @{ $marc_record->[ $marc_record_offset ] }, [ $f, $i1, $i2, $sf => $v ];
475                  } else {                  } else {
476                          return $format;                          push @{ $marc_record->[ $marc_record_offset ] }, [ $f, $v ];
477                  }                  }
         } else {  
                 return;  
478          }          }
479  }  }
480    
481    =head2 marc_repeatable_subfield
482    
483    Save values for MARC repetable subfield
484    
485      marc_repeatable_subfield('910', 'z', rec('909') );
486    
487    =cut
488    
489    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    =head2 marc_indicators
497    
498  =head2 fill_in_to_arr  Set both indicators for MARC field
499    
500  Similar to C<fill_in>, but returns array of all repeatable fields. Usable    marc_indicators('900', ' ', 1);
 for fields which have lookups, so they shouldn't be parsed but rather  
 C<fill_id>ed.  
501    
502   my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]');  Any indicator value other than C<0-9> will be treated as undefined.
503    
504  =cut  =cut
505    
506  sub fill_in_to_arr {  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 ($rec, $format_utf8) = @_;          $i1 = ' ' if ($i1 !~ /^\d$/);
513            $i2 = ' ' if ($i2 !~ /^\d$/);
514            @{ $marc_indicators->{$f} } = ($i1,$i2);
515    }
516    
517          my $log = $self->_get_logger();  =head2 marc_compose
518    
519          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  Save values for each MARC subfield explicitly
         return if (! $format_utf8);  
520    
521          my $i = 0;    marc_compose('900',
522          my @arr;          'a', rec('200','a')
523            'b', rec('201','a')
524            'a', rec('200','b')
525            'c', rec('200','c')
526      );
527    
528    If you specify C<+> for subfield, value will be appended
529    to previous defined subfield.
530    
531    =cut
532    
533    sub marc_compose {
534            my $f = shift or die "marc_compose needs field";
535            die "marc_compose field must be numer" unless ($f =~ /^\d+$/);
536    
537            my ($i1,$i2) = defined($marc_indicators->{$f}) ? @{ $marc_indicators->{$f} } : (' ',' ');
538            my $m = [ $f, $i1, $i2 ];
539    
540            warn "### marc_compose input subfields = ", dump(@_),$/ if ($debug > 2);
541    
542          while (my @v = $self->fill_in($rec,$format_utf8,$i++)) {          while (@_) {
543                  push @arr, @v;                  my $sf = shift or die "marc_compose $f needs subfield";
544                    my $v = shift;
545    
546                    next unless (defined($v) && $v !~ /^\s*$/);
547                    from_to($v, 'iso-8859-2', $marc_encoding) if ($marc_encoding);
548                    warn "## ++ marc_compose($f,$sf,$v) ", dump( $m ),$/ if ($debug > 1);
549                    if ($sf ne '+') {
550                            push @$m, ( $sf, $v );
551                    } else {
552                            $m->[ $#$m ] .= $v;
553                    }
554          }          }
555    
556          $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);          warn "## marc_compose current marc = ", dump( $m ),$/ if ($debug > 1);
557    
558          return @arr;          push @{ $marc_record->[ $marc_record_offset ] }, $m if ($#{$m} > 2);
559  }  }
560    
561    =head2 marc_duplicate
562    
563    Generate copy of current MARC record and continue working on copy
564    
565  =head2 get_data    marc_duplicate();
566    
567  Returns value from record.  Copies can be accessed using C<< _get_marc_fields( fetch_next => 1 ) >> or
568    C<< _get_marc_fields( offset => 42 ) >>.
569    
570   my $text = $self->get_data(\$rec,$f,$sf,$i,\$found);  =cut
571    
572    sub marc_duplicate {
573             my $m = $marc_record->[ -1 ];
574             die "can't duplicate record which isn't defined" unless ($m);
575             push @{ $marc_record }, dclone( $m );
576             warn "## marc_duplicate = ", dump(@$marc_record), $/ if ($debug > 1);
577             $marc_record_offset = $#{ $marc_record };
578             warn "## marc_record_offset = $marc_record_offset", $/ if ($debug > 1);
579    }
580    
581  Arguments are:  =head2 marc_remove
 record reference C<$rec>,  
 field C<$f>,  
 optional subfiled C<$sf>,  
 index for repeatable values C<$i>.  
582    
583  Optinal variable C<$found> will be incremeted if there  Remove some field or subfield from MARC record.
 is field.  
584    
585  Returns value or empty string.    marc_remove('200');
586      marc_remove('200','a');
587    
588    This will erase field C<200> or C<200^a> from current MARC record.
589    
590    This is useful after calling C<marc_duplicate> or on it's own (but, you
591    should probably just remove that subfield definition if you are not
592    using C<marc_duplicate>).
593    
594    FIXME: support fields < 10.
595    
596  =cut  =cut
597    
598  sub get_data {  sub marc_remove {
599          my $self = shift;          my ($f, $sf) = @_;
600    
601          my ($rec,$f,$sf,$i,$found) = @_;          die "marc_remove needs record number" unless defined($f);
602    
603          if ($$rec->{$f}) {          my $marc = $marc_record->[ $marc_record_offset ];
604                  return '' if (! $$rec->{$f}->[$i]);  
605                  no strict 'refs';          warn "### marc_remove before = ", dump( $marc ), $/ if ($debug > 2);
606                  if ($sf && $$rec->{$f}->[$i]->{$sf}) {  
607                          $$found++ if (defined($$found));          my $i = 0;
608                          return $$rec->{$f}->[$i]->{$sf};          foreach ( 0 .. $#{ $marc } ) {
609                  } elsif ($$rec->{$f}->[$i]) {                  last unless (defined $marc->[$i]);
610                          $$found++ if (defined($$found));                  warn "#### working on ",dump( @{ $marc->[$i] }), $/ if ($debug > 3);
611                          # it still might have subfield, just                  if ($marc->[$i]->[0] eq $f) {
612                          # not specified, so we'll dump all                          if (! defined $sf) {
613                          if ($$rec->{$f}->[$i] =~ /HASH/o) {                                  # remove whole field
614                                  my $out;                                  splice @$marc, $i, 1;
615                                  foreach my $k (keys %{$$rec->{$f}->[$i]}) {                                  warn "#### slice \@\$marc, $i, 1 = ",dump( @{ $marc }), $/ if ($debug > 3);
616                                          $out .= $$rec->{$f}->[$i]->{$k}." ";                                  $i--;
617                            } else {
618                                    foreach my $j ( 0 .. (( $#{ $marc->[$i] } - 3 ) / 2) ) {
619                                            my $o = ($j * 2) + 3;
620                                            if ($marc->[$i]->[$o] eq $sf) {
621                                                    # remove subfield
622                                                    splice @{$marc->[$i]}, $o, 2;
623                                                    warn "#### slice \@{\$marc->[$i]}, $o, 2 = ", dump( @{ $marc }), $/ if ($debug > 3);
624                                                    # is record now empty?
625                                                    if ($#{ $marc->[$i] } == 2) {
626                                                            splice @$marc, $i, 1;
627                                                            warn "#### slice \@\$marc, $i, 1 = ", dump( @{ $marc }), $/ if ($debug > 3);
628                                                            $i--;
629                                                    };
630                                            }
631                                  }                                  }
632                                  return $out;                          }
633                    }
634                    $i++;
635            }
636    
637            warn "### marc_remove($f", $sf ? ",$sf" : "", ") after = ", dump( $marc ), $/ if ($debug > 2);
638    
639            $marc_record->[ $marc_record_offset ] = $marc;
640    
641            warn "## full marc_record = ", dump( @{ $marc_record }), $/ if ($debug > 1);
642    }
643    
644    =head1 Functions to extract data from input
645    
646    This function should be used inside functions to create C<data_structure> described
647    above.
648    
649    =head2 rec1
650    
651    Return all values in some field
652    
653      @v = rec1('200')
654    
655    TODO: order of values is probably same as in source data, need to investigate that
656    
657    =cut
658    
659    sub rec1 {
660            my $f = shift;
661            warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
662            return unless (defined($rec) && defined($rec->{$f}));
663            warn "rec1($f) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
664            if (ref($rec->{$f}) eq 'ARRAY') {
665                    return map {
666                            if (ref($_) eq 'HASH') {
667                                    values %{$_};
668                          } else {                          } else {
669                                  return $$rec->{$f}->[$i];                                  $_;
670                          }                          }
671                    } @{ $rec->{$f} };
672            } elsif( defined($rec->{$f}) ) {
673                    return $rec->{$f};
674            }
675    }
676    
677    =head2 rec2
678    
679    Return all values in specific field and subfield
680    
681      @v = rec2('200','a')
682    
683    =cut
684    
685    sub rec2 {
686            my $f = shift;
687            return unless (defined($rec && $rec->{$f}));
688            my $sf = shift;
689            warn "rec2($f,$sf) = ", dump( $rec->{$f} ), $/ if ($debug > 1);
690            return map {
691                    if (ref($_->{$sf}) eq 'ARRAY') {
692                            @{ $_->{$sf} };
693                    } else {
694                            $_->{$sf};
695                  }                  }
696            } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
697    }
698    
699    =head2 rec
700    
701    syntaxtic sugar for
702    
703      @v = rec('200')
704      @v = rec('200','a')
705    
706    =cut
707    
708    sub rec {
709            my @out;
710            if ($#_ == 0) {
711                    @out = rec1(@_);
712            } elsif ($#_ == 1) {
713                    @out = rec2(@_);
714            }
715            if (@out) {
716                    return @out;
717          } else {          } else {
718                  return '';                  return '';
719          }          }
720  }  }
721    
722    =head2 regex
723    
724  =head2 apply_format  Apply regex to some or all values
725    
726  Apply format specified in tag with C<format_name="name"> and    @v = regex( 's/foo/bar/g', @v );
 C<format_delimiter=";;">.  
727    
728   my $text = $webpac->apply_format($format_name,$format_delimiter,$data);  =cut
729    
730  Formats can contain C<lookup{...}> if you need them.  sub regex {
731            my $r = shift;
732            my @out;
733            #warn "r: $r\n", dump(\@_);
734            foreach my $t (@_) {
735                    next unless ($t);
736                    eval "\$t =~ $r";
737                    push @out, $t if ($t && $t ne '');
738            }
739            return @out;
740    }
741    
742    =head2 prefix
743    
744    Prefix all values with a string
745    
746      @v = prefix( 'my_', @v );
747    
748  =cut  =cut
749    
750  sub apply_format {  sub prefix {
751          my $self = shift;          my $p = shift or return;
752            return map { $p . $_ } grep { defined($_) } @_;
753    }
754    
755          my ($name,$delimiter,$data) = @_;  =head2 suffix
756    
757          my $log = $self->_get_logger();  suffix all values with a string
758    
759          if (! $self->{'import_xml'}->{'format'}->{$name}) {    @v = suffix( '_my', @v );
                 $log->warn("<format name=\"$name\"> is not defined in ",$self->{'import_xml_file'});  
                 return $data;  
         }  
760    
761          $log->warn("no delimiter for format $name") if (! $delimiter);  =cut
762    
763          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  sub suffix {
764            my $s = shift or die "suffix needs string as first argument";
765            return map { $_ . $s } grep { defined($_) } @_;
766    }
767    
768          my @data = split(/\Q$delimiter\E/, $data);  =head2 surround
769    
770          my $out = sprintf($format, @data);  surround all values with a two strings
         $log->debug("using format $name [$format] on $data to produce: $out");  
771    
772          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {    @v = surround( 'prefix_', '_suffix', @v );
                 return $self->lookup($out);  
         } else {  
                 return $out;  
         }  
773    
774    =cut
775    
776    sub surround {
777            my $p = shift or die "surround need prefix as first argument";
778            my $s = shift or die "surround needs suffix as second argument";
779            return map { $p . $_ . $s } grep { defined($_) } @_;
780  }  }
781    
782  =head2 sort_arr  =head2 first
783    
784  Sort array ignoring case and html in data  Return first element
785    
786   my @sorted = $webpac->sort_arr(@unsorted);    $v = first( @v );
787    
788  =cut  =cut
789    
790  sub sort_arr {  sub first {
791          my $self = shift;          my $r = shift;
792            return $r;
793    }
794    
795    =head2 lookup
796    
797          my $log = $self->_get_logger();  Consult lookup hashes for some value
798    
799          # FIXME add Schwartzian Transformation?    @v = lookup( $v );
800      @v = lookup( @v );
801    
802          my @sorted = sort {  =cut
                 $a =~ s#<[^>]+/*>##;  
                 $b =~ s#<[^>]+/*>##;  
                 lc($b) cmp lc($a)  
         } @_;  
         $log->debug("sorted values: ",sub { join(", ",@sorted) });  
803    
804          return @sorted;  sub lookup {
805            my $k = shift or return;
806            return unless (defined($lookup->{$k}));
807            if (ref($lookup->{$k}) eq 'ARRAY') {
808                    return @{ $lookup->{$k} };
809            } else {
810                    return $lookup->{$k};
811            }
812  }  }
813    
814    =head2 config
815    
816  =head1 INTERNAL METHODS  Consult config values stored in C<config.yml>
817    
818  =head2 _sort_by_order    # return database code (key under databases in yaml)
819      $database_code = config();    # use _ from hash
820      $database_name = config('name');
821      $database_input_name = config('input name');
822      $tag = config('input normalize tag');
823    
824  Sort xml tags data structure accoding to C<order=""> attribute.  Up to three levels are supported.
825    
826  =cut  =cut
827    
828  sub _sort_by_order {  sub config {
829          my $self = shift;          return unless ($config);
830    
831            my $p = shift;
832    
833            $p ||= '';
834    
835            my $v;
836    
837            warn "### getting config($p)\n" if ($debug > 1);
838    
839            my @p = split(/\s+/,$p);
840            if ($#p < 0) {
841                    $v = $config->{ '_' };  # special, database code
842            } else {
843    
844                    my $c = dclone( $config );
845    
846                    foreach my $k (@p) {
847                            warn "### k: $k c = ",dump($c),$/ if ($debug > 1);
848                            if (ref($c) eq 'ARRAY') {
849                                    $c = shift @$c;
850                                    warn "config($p) taking first occurence of '$k', probably not what you wanted!\n";
851                                    last;
852                            }
853    
854                            if (! defined($c->{$k}) ) {
855                                    $c = undef;
856                                    last;
857                            } else {
858                                    $c = $c->{$k};
859                            }
860                    }
861                    $v = $c if ($c);
862    
863            }
864    
865          my $va = $self->{'import_xml'}->{'indexer'}->{$a}->{'order'} ||          warn "## config( '$p' ) = ",dump( $v ),$/ if ($v && $debug);
866                  $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};  
867    
868          return $va <=> $vb;          return $v;
869  }  }
870    
871  =head2 _x  =head2 id
872    
873  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).  
874    
875   my $text = $n->_x('normalize text string');    $id = id();
876    
877  This is a stub so that other modules doesn't have to implement it.  Returns C<42/2> for 2nd occurence of MFN 42.
878    
879  =cut  =cut
880    
881  sub _x {  sub id {
882          my $self = shift;          my $mfn = $config->{_mfn} || die "no _mfn in config data";
883          return shift;          return $mfn . $#{$marc_record} ? $#{$marc_record} + 1 : '';
884  }  }
885    
886    =head2 join_with
887    
888    Joins walues with some delimiter
889    
890      $v = join_with(", ", @v);
891    
892  =head1 AUTHOR  =cut
893    
894    sub join_with {
895            my $d = shift;
896            warn "### join_with('$d',",dump(@_),")\n" if ($debug > 2);
897            my $v = join($d, grep { defined($_) && $_ ne '' } @_);
898            return '' unless defined($v);
899            return $v;
900    }
901    
902  Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>  =head2 split_rec_on
903    
904  =head1 COPYRIGHT & LICENSE  Split record subfield on some regex and take one of parts out
905    
906  Copyright 2005 Dobrica Pavlinusic, All Rights Reserved.    $a_before_semi_column =
907            split_rec_on('200','a', /\s*;\s*/, $part);
908    
909  This program is free software; you can redistribute it and/or modify it  C<$part> is optional number of element. First element is
910  under the same terms as Perl itself.  B<1>, not 0!
911    
912    If there is no C<$part> parameter or C<$part> is 0, this function will
913    return all values produced by splitting.
914    
915  =cut  =cut
916    
917  1; # End of WebPAC::DB  sub split_rec_on {
918            die "split_rec_on need (fld,sf,regex[,part]" if ($#_ < 2);
919    
920            my ($fld, $sf, $regex, $part) = @_;
921            warn "### regex ", ref($regex), $regex, $/ if ($debug > 2);
922    
923            my @r = rec( $fld, $sf );
924            my $v = shift @r;
925            warn "### first rec($fld,$sf) = ",dump($v),$/ if ($debug > 2);
926    
927            return '' if( ! defined($v) || $v =~ /^\s*$/);
928    
929            my @s = split( $regex, $v );
930            warn "## split_rec_on($fld,$sf,$regex,$part) = ",dump(@s),$/ if ($debug > 1);
931            if ($part && $part > 0) {
932                    return $s[ $part - 1 ];
933            } else {
934                    return @s;
935            }
936    }
937    
938    # END
939    1;

Legend:
Removed from v.22  
changed lines
  Added in v.603

  ViewVC Help
Powered by ViewVC 1.1.26