/[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 14 by dpavlin, Sun Jul 17 00:04:25 2005 UTC revision 540 by dpavlin, Thu Jun 29 15:29:41 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    
7            tag search display
8            marc21
9    
10            rec1 rec2 rec
11            regex prefix suffix surround
12            first lookup join_with
13    /;
14    
15  use warnings;  use warnings;
16  use strict;  use strict;
17    
18    #use base qw/WebPAC::Common/;
19  use Data::Dumper;  use Data::Dumper;
 use Storable;  
20    
21  =head1 NAME  =head1 NAME
22    
23  WebPAC::Normalize - normalisation of source file  WebPAC::Normalize - describe normalisaton rules using sets
24    
25  =head1 VERSION  =head1 VERSION
26    
27  Version 0.01  Version 0.05
28    
29  =cut  =cut
30    
31  our $VERSION = '0.01';  our $VERSION = '0.05';
32    
33  =head1 SYNOPSIS  =head1 SYNOPSIS
34    
35  This package contains code that could be helpful in implementing different  This module uses C<conf/normalize/*.pl> files to perform normalisation
36  normalisation front-ends.  from input records using perl functions which are specialized for set
37    processing.
38    
39    Sets are implemented as arrays, and normalisation file is valid perl, which
40    means that you check it's validity before running WebPAC using
41    C<perl -c normalize.pl>.
42    
43    Normalisation can generate multiple output normalized data. For now, supported output
44    types (on the left side of definition) are: C<tag>, C<display>, C<search> and
45    C<marc21>.
46    
47  =head1 FUNCTIONS  =head1 FUNCTIONS
48    
49  =head2 new  Functions which start with C<_> are private and used by WebPAC internally.
50    All other functions are available for use within normalisation rules.
 Create new normalisation object  
   
   my $n = new WebPAC::Normalize::Something(  
         cache_data_structure => './cache/ds/',  
         lookup_regex => $lookup->regex,  
   );  
   
 Optional parameter C<cache_data_structure> defines path to directory  
 in which cache file for C<data_structure> call will be created.  
   
 Recommended parametar C<lookup_regex> is used to enable parsing of lookups  
 in structures.  
   
 =cut  
   
 sub new {  
         my $class = shift;  
         my $self = {@_};  
         bless($self, $class);  
   
         $self->setup_cache_dir( $self->{'cache_data_structure'} );  
   
         $self ? return $self : return undef;  
 }  
   
 =head2 setup_cache_dir  
   
 Check if specified cache directory exist, and if not, disable caching.  
   
  $setup_cache_dir('./cache/ds/');  
   
 If you pass false or zero value to this function, it will disable  
 cacheing.  
   
 =cut  
   
 sub setup_cache_dir {  
         my $self = shift;  
   
         my $dir = shift;  
   
         my $log = $self->_get_logger();  
   
         if ($dir) {  
                 my $msg;  
                 if (! -e $dir) {  
                         $msg = "doesn't exist";  
                 } elsif (! -d $dir) {  
                         $msg = "is not directory";  
                 } elsif (! -w $dir) {  
                         $msg = "not writable";  
                 }  
   
                 if ($msg) {  
                         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'};  
         }  
 }  
   
51    
52  =head2 data_structure  =head2 data_structure
53    
54  Create in-memory data structure which represents normalized layout from  Return data structure
 C<conf/normalize/*.xml>.  
55    
56  This structures are used to produce output.    my $ds = WebPAC::Normalize::data_structure(
57            lookup => $lookup->lookup_hash,
58            row => $row,
59            rules => $normalize_pl_config,
60      );
61    
62   my @ds = $webpac->data_structure($rec);  Options C<lookup>, C<row>, C<rules> and C<log> are mandatory while all
63    other are optional.
64    
65  B<Note: historical oddity follows>  This function will B<die> if normalizastion can't be evaled.
66    
67  This method will also set C<< $webpac->{'currnet_filename'} >> if there is  Since this function isn't exported you have to call it with
68  C<< <filename> >> tag and C<< $webpac->{'headline'} >> if there is  C<WebPAC::Normalize::data_structure>.
 C<< <headline> >> tag.  
69    
70  =cut  =cut
71    
72  sub data_structure {  sub data_structure {
73          my $self = shift;          my $arg = {@_};
74    
75          my $log = $self->_get_logger();          die "need row argument" unless ($arg->{row});
76            die "need normalisation argument" unless ($arg->{rules});
77    
78          my $rec = shift;          no strict 'subs';
79          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);          _set_lookup( $arg->{lookup} );
80            _set_rec( $arg->{row} );
81            _clean_ds();
82    
83          my $cache_file;          eval "$arg->{rules}";
84            die "error evaling $arg->{rules}: $@\n" if ($@);
85    
86          if (my $cache_path = $self->{'cache_data_structure'}) {          return _get_ds();
87                  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'};  
                                         }  
                                 }  
                         }  
                 }  
         }  
88    
89          undef $self->{'currnet_filename'};  =head2 _set_rec
         undef $self->{'headline'};  
90    
91          my @sorted_tags;  Set current record hash
         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;  
         }  
92    
93          my @ds;    _set_rec( $rec );
94    
95          $log->debug("tags: ",sub { join(", ",@sorted_tags) });  =cut
   
         foreach my $field (@sorted_tags) {  
96    
97                  my $row;  my $rec;
98    
99  #print "field $field [",$self->{'tag'},"] = ",Dumper($self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}});  sub _set_rec {
100            $rec = shift or die "no record hash";
101    }
102    
103                  foreach my $tag (@{$self->{'import_xml'}->{'indexer'}->{$field}->{$self->{'tag'}}}) {  =head2 _get_ds
                         my $format = $tag->{'value'} || $tag->{'content'};  
104    
105                          $log->debug("format: $format");  Return hash formatted as data structure
106    
107                          my @v;    my $ds = _get_ds();
                         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);  
108    
109                          if ($tag->{'sort'}) {  =cut
                                 @v = $self->sort_arr(@v);  
                         }  
   
                         # use format?  
                         if ($tag->{'format_name'}) {  
                                 @v = map { $self->apply_format($tag->{'format_name'},$tag->{'format_delimiter'},$_) } @v;  
                         }  
110    
111                          if ($field eq 'filename') {  my $out;
112                                  $self->{'current_filename'} = join('',@v);  my $marc21;
                                 $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!  
                         }  
113    
114                          # delimiter will join repeatable fields  sub _get_ds {
115                          if ($tag->{'delimiter'}) {          return $out;
116                                  @v = ( join($tag->{'delimiter'}, @v) );  }
                         }  
117    
118                          # default types  =head2 _clean_ds
                         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;  
   
                                 } else {  
                                         push @{$row->{$type}}, @v;  
                                 }  
                         }  
119    
120    Clean data structure hash for next record
121    
122                  }    _clean_ds();
123    
124                  if ($row) {  =cut
                         $row->{'tag'} = $field;  
125    
126                          # TODO: name_sigular, name_plural  sub _clean_ds {
127                          my $name = $self->{'import_xml'}->{'indexer'}->{$field}->{'name'};          $out = undef;
128                          $row->{'name'} = $name ? $self->_x($name) : $field;          $marc21 = undef;
129    }
                         # post-sort all values in field  
                         if ($self->{'import_xml'}->{'indexer'}->{$field}->{'sort'}) {  
                                 $log->warn("sort at field tag not implemented");  
                         }  
130    
131                          push @ds, $row;  =head2 _set_lookup
132    
133                          $log->debug("row $field: ",sub { Dumper($row) });  Set current lookup hash
                 }  
134    
135          }    _set_lookup( $lookup );
136    
137          if ($cache_file) {  =cut
                 store {  
                         ds => \@ds,  
                         current_filename => $self->{'current_filename'},  
                         headline => $self->{'headline'},  
                 }, $cache_file;  
                 $log->debug("created storable cache file $cache_file");  
         }  
138    
139          return @ds;  my $lookup;
140    
141    sub _set_lookup {
142            $lookup = shift;
143  }  }
144    
145  =head2 apply_format  =head2 _get_marc21_fields
146    
147  Apply format specified in tag with C<format_name="name"> and  Get all fields defined by calls to C<marc21>
 C<format_delimiter=";;">.  
148    
149   my $text = $webpac->apply_format($format_name,$format_delimiter,$data);          $marc->add_fields( WebPAC::Normalize:_get_marc21_fields() );
   
 Formats can contain C<lookup{...}> if you need them.  
150    
151  =cut  =cut
152    
153  sub apply_format {  sub _get_marc21_fields {
154          my $self = shift;          return @{$marc21};
155    }
         my ($name,$delimiter,$data) = @_;  
156    
157          my $log = $self->_get_logger();  =head1 Functions to create C<data_structure>
158    
159          if (! $self->{'import_xml'}->{'format'}->{$name}) {  Those functions generally have to first in your normalization file.
                 $log->warn("<format name=\"$name\"> is not defined in ",$self->{'import_xml_file'});  
                 return $data;  
         }  
160    
161          $log->warn("no delimiter for format $name") if (! $delimiter);  =head2 tag
162    
163          my $format = $self->_x($self->{'import_xml'}->{'format'}->{$name}->{'content'}) || $log->logdie("can't find format '$name'");  Define new tag for I<search> and I<display>.
164    
165          my @data = split(/\Q$delimiter\E/, $data);    tag('Title', rec('200','a') );
166    
         my $out = sprintf($format, @data);  
         $log->debug("using format $name [$format] on $data to produce: $out");  
167    
168          if ($self->{'lookup_regex'} && $out =~ $self->{'lookup_regex'}) {  =cut
                 return $self->lookup($out);  
         } else {  
                 return $out;  
         }  
169    
170    sub tag {
171            my $name = shift or die "tag needs name as first argument";
172            my @o = grep { defined($_) && $_ ne '' } @_;
173            return unless (@o);
174            $out->{$name}->{tag} = $name;
175            $out->{$name}->{search} = \@o;
176            $out->{$name}->{display} = \@o;
177  }  }
178    
179  =head2 parse  =head2 display
180    
181  Perform smart parsing of string, skipping delimiters for fields which aren't  Define tag just for I<display>
 defined. It can also eval code in format starting with C<eval{...}> and  
 return output or nothing depending on eval code.  
182    
183   my $text = $webpac->parse($rec,'eval{"v901^a" eq "Deskriptor"}descriptor: v250^a', $i);    @v = display('Title', rec('200','a') );
184    
185  =cut  =cut
186    
187  sub parse {  sub display {
188          my $self = shift;          my $name = shift or die "display needs name as first argument";
189            my @o = grep { defined($_) && $_ ne '' } @_;
190          my ($rec, $format_utf8, $i) = @_;          return unless (@o);
191            $out->{$name}->{tag} = $name;
192          return if (! $format_utf8);          $out->{$name}->{display} = \@o;
193    }
194    
195          my $log = $self->_get_logger();  =head2 search
196    
197          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  Prepare values just for I<search>
198    
199          $i = 0 if (! $i);    @v = search('Title', rec('200','a') );
200    
201          my $format = $self->_x($format_utf8) || $log->logconfess("can't convert '$format_utf8' from UTF-8 to ",$self->{'code_page'});  =cut
202    
203          my @out;  sub search {
204            my $name = shift or die "search needs name as first argument";
205            my @o = grep { defined($_) && $_ ne '' } @_;
206            return unless (@o);
207            $out->{$name}->{tag} = $name;
208            $out->{$name}->{search} = \@o;
209    }
210    
211          $log->debug("format: $format");  =head2 marc21
212    
213          my $eval_code;  Save value for MARC field
         # remove eval{...} from beginning  
         $eval_code = $1 if ($format =~ s/^eval{([^}]+)}//s);  
214    
215          my $filter_name;    marc21('900','a', rec('200','a') );
         # remove filter{...} from beginning  
         $filter_name = $1 if ($format =~ s/^filter{([^}]+)}//s);  
216    
217          my $prefix;  =cut
         my $all_found=0;  
218    
219          while ($format =~ s/^(.*?)(v|s)(\d+)(?:\^(\w))?//s) {  sub marc21 {
220            my $f = shift or die "marc21 needs field";
221            die "marc21 field must be numer" unless ($f =~ /^\d+$/);
222    
223                  my $del = $1 || '';          my $sf = shift or die "marc21 needs subfield";
                 $prefix ||= $del if ($all_found == 0);  
224    
225                  # repeatable index          foreach my $v (@_) {
226                  my $r = $i;                  push @{ $marc21 }, [ $f, ' ', ' ', $sf => $v ];
227                  $r = 0 if (lc("$2") eq 's');          }
228    }
229    
230                  my $found = 0;  =head1 Functions to extract data from input
                 my $tmp = $self->get_data(\$rec,$3,$4,$r,\$found);  
231    
232                  if ($found) {  This function should be used inside functions to create C<data_structure> described
233                          push @out, $del;  above.
                         push @out, $tmp;  
                         $all_found += $found;  
                 }  
         }  
234    
235          return if (! $all_found);  =head2 rec1
236    
237          my $out = join('',@out);  Return all values in some field
238    
239          if ($out) {    @v = rec1('200')
                 # add rest of format (suffix)  
                 $out .= $format;  
240    
241                  # add prefix if not there  TODO: order of values is probably same as in source data, need to investigate that
                 $out = $prefix . $out if ($out !~ m/^\Q$prefix\E/);  
242    
243                  $log->debug("result: $out");  =cut
         }  
244    
245          if ($eval_code) {  sub rec1 {
246                  my $eval = $self->fill_in($rec,$eval_code,$i) || return;          my $f = shift;
247                  $log->debug("about to eval{$eval} format: $out");          return unless (defined($rec) && defined($rec->{$f}));
248                  return if (! $self->_eval($eval));          if (ref($rec->{$f}) eq 'ARRAY') {
249          }                  return map {
250                                    if (ref($_) eq 'HASH') {
251          if ($filter_name && $self->{'filter'}->{$filter_name}) {                                  values %{$_};
252                  $log->debug("about to filter{$filter_name} format: $out");                          } else {
253                  $out = $self->{'filter'}->{$filter_name}->($out);                                  $_;
254                  return unless(defined($out));                          }
255                  $log->debug("filter result: $out");                  } @{ $rec->{$f} };
256            } elsif( defined($rec->{$f}) ) {
257                    return $rec->{$f};
258          }          }
   
         return $out;  
259  }  }
260    
261  =head2 parse_to_arr  =head2 rec2
262    
263  Similar to C<parse>, but returns array of all repeatable fields  Return all values in specific field and subfield
264    
265   my @arr = $webpac->parse_to_arr($rec,'v250^a');    @v = rec2('200','a')
266    
267  =cut  =cut
268    
269  sub parse_to_arr {  sub rec2 {
270          my $self = shift;          my $f = shift;
271            return unless (defined($rec && $rec->{$f}));
272            my $sf = shift;
273            return map { $_->{$sf} } grep { ref($_) eq 'HASH' && $_->{$sf} } @{ $rec->{$f} };
274    }
275    
276          my ($rec, $format_utf8) = @_;  =head2 rec
277    
278          my $log = $self->_get_logger();  syntaxtic sugar for
279    
280          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);    @v = rec('200')
281          return if (! $format_utf8);    @v = rec('200','a')
282    
283          my $i = 0;  =cut
         my @arr;  
284    
285          while (my $v = $self->parse($rec,$format_utf8,$i++)) {  sub rec {
286                  push @arr, $v;          if ($#_ == 0) {
287                    return rec1(@_);
288            } elsif ($#_ == 1) {
289                    return rec2(@_);
290          }          }
   
         $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  
   
         return @arr;  
291  }  }
292    
293  =head2 fill_in_to_arr  =head2 regex
294    
295  Similar to C<fill_in>, but returns array of all repeatable fields. Usable  Apply regex to some or all values
 for fields which have lookups, so they shouldn't be parsed but rather  
 C<fill_id>ed.  
296    
297   my @arr = $webpac->fill_in_to_arr($rec,'[v900];;[v250^a]');    @v = regex( 's/foo/bar/g', @v );
298    
299  =cut  =cut
300    
301  sub fill_in_to_arr {  sub regex {
302          my $self = shift;          my $r = shift;
303            my @out;
304          my ($rec, $format_utf8) = @_;          #warn "r: $r\n",Dumper(\@_);
305            foreach my $t (@_) {
306          my $log = $self->_get_logger();                  next unless ($t);
307                    eval "\$t =~ $r";
308                    push @out, $t if ($t && $t ne '');
309            }
310            return @out;
311    }
312    
313          $log->logconfess("need HASH as first argument!") if ($rec !~ /HASH/o);  =head2 prefix
         return if (! $format_utf8);  
314    
315          my $i = 0;  Prefix all values with a string
         my @arr;  
316    
317          while (my @v = $self->fill_in($rec,$format_utf8,$i++)) {    @v = prefix( 'my_', @v );
                 push @arr, @v;  
         }  
318    
319          $log->debug("format '$format_utf8' returned ",--$i," elements: ", sub { join(" | ",@arr) }) if (@arr);  =cut
320    
321          return @arr;  sub prefix {
322            my $p = shift or die "prefix needs string as first argument";
323            return map { $p . $_ } grep { defined($_) } @_;
324  }  }
325    
326  =head2 sort_arr  =head2 suffix
327    
328  Sort array ignoring case and html in data  suffix all values with a string
329    
330   my @sorted = $webpac->sort_arr(@unsorted);    @v = suffix( '_my', @v );
331    
332  =cut  =cut
333    
334  sub sort_arr {  sub suffix {
335          my $self = shift;          my $s = shift or die "suffix needs string as first argument";
336            return map { $_ . $s } grep { defined($_) } @_;
337    }
338    
339          my $log = $self->_get_logger();  =head2 surround
340    
341          # FIXME add Schwartzian Transformation?  surround all values with a two strings
342    
343          my @sorted = sort {    @v = surround( 'prefix_', '_suffix', @v );
                 $a =~ s#<[^>]+/*>##;  
                 $b =~ s#<[^>]+/*>##;  
                 lc($b) cmp lc($a)  
         } @_;  
         $log->debug("sorted values: ",sub { join(", ",@sorted) });  
344    
345          return @sorted;  =cut
346    
347    sub surround {
348            my $p = shift or die "surround need prefix as first argument";
349            my $s = shift or die "surround needs suffix as second argument";
350            return map { $p . $_ . $s } grep { defined($_) } @_;
351  }  }
352    
353    =head2 first
354    
355  =head2 _sort_by_order  Return first element
356    
357  Sort xml tags data structure accoding to C<order=""> attribute.    $v = first( @v );
358    
359  =cut  =cut
360    
361  sub _sort_by_order {  sub first {
362          my $self = shift;          my $r = shift;
363            return $r;
         my $va = $self->{'import_xml'}->{'indexer'}->{$a}->{'order'} ||  
                 $self->{'import_xml'}->{'indexer'}->{$a};  
         my $vb = $self->{'import_xml'}->{'indexer'}->{$b}->{'order'} ||  
                 $self->{'import_xml'}->{'indexer'}->{$b};  
   
         return $va <=> $vb;  
364  }  }
365    
366  =head2 _x  =head2 lookup
   
 Convert strings from C<conf/normalize> encoding into application specific  
 (optinally specified using C<code_page> to C<new> constructor.  
367    
368   my $text = $n->_x('normalize text string');  Consult lookup hashes for some value
369    
370  This is a stub so that other modules doesn't have to implement it.    @v = lookup( $v );
371      @v = lookup( @v );
372    
373  =cut  =cut
374    
375  sub _x {  sub lookup {
376          my $self = shift;          my $k = shift or return;
377          return shift;          return unless (defined($lookup->{$k}));
378            if (ref($lookup->{$k}) eq 'ARRAY') {
379                    return @{ $lookup->{$k} };
380            } else {
381                    return $lookup->{$k};
382            }
383  }  }
384    
385    =head2 join_with
386    
387  =head1 AUTHOR  Joins walues with some delimiter
   
 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>  
   
 =head1 COPYRIGHT & LICENSE  
388    
389  Copyright 2005 Dobrica Pavlinusic, All Rights Reserved.    $v = join_with(", ", @v);
   
 This program is free software; you can redistribute it and/or modify it  
 under the same terms as Perl itself.  
390    
391  =cut  =cut
392    
393  1; # End of WebPAC::DB  sub join_with {
394            my $d = shift;
395            return join($d, grep { defined($_) && $_ ne '' } @_);
396    }
397    
398    # END
399    1;

Legend:
Removed from v.14  
changed lines
  Added in v.540

  ViewVC Help
Powered by ViewVC 1.1.26