Make cleanup of encodings, moving webpac closer to having
[webpac2] / lib / WebPAC / Input.pm
1 package WebPAC::Input;
2
3 use warnings;
4 use strict;
5
6 use blib;
7
8 use WebPAC::Common;
9 use base qw/WebPAC::Common/;
10 use Data::Dump qw/dump/;
11 use Encode qw/decode from_to/;
12
13 =head1 NAME
14
15 WebPAC::Input - read different file formats into WebPAC
16
17 =cut
18
19 our $VERSION = '0.19';
20
21 =head1 SYNOPSIS
22
23 This module implements input as database which have fixed and known
24 I<size> while indexing and single unique numeric identifier for database
25 position ranging from 1 to I<size>.
26
27 Simply, something that is indexed by unmber from 1 .. I<size>.
28
29 Examples of such databases are CDS/ISIS files, MARC files, lines in
30 text file, and so on.
31
32 Specific file formats are implemented using low-level interface modules,
33 located in C<WebPAC::Input::*> namespace which export C<open_db>,
34 C<fetch_rec> and optional C<init> functions.
35
36 Perhaps a little code snippet.
37
38         use WebPAC::Input;
39
40         my $db = WebPAC::Input->new(
41                 module => 'WebPAC::Input::ISIS',
42         );
43
44         $db->open( path => '/path/to/database' );
45         print "database size: ",$db->size,"\n";
46         while (my $rec = $db->fetch) {
47                 # do something with $rec
48         }
49
50
51
52 =head1 FUNCTIONS
53
54 =head2 new
55
56 Create new input database object.
57
58   my $db = new WebPAC::Input(
59         module => 'WebPAC::Input::MARC',
60         recode => 'char pairs',
61         no_progress_bar => 1,
62         input_config => {
63                 mapping => [ 'foo', 'bar', 'baz' ],
64         },
65   );
66
67 C<module> is low-level file format module. See L<WebPAC::Input::ISIS> and
68 L<WebPAC::Input::MARC>.
69
70 C<recode> is optional string constisting of character or words pairs that
71 should be replaced in input stream.
72
73 C<no_progress_bar> disables progress bar output on C<STDOUT>
74
75 This function will also call low-level C<init> if it exists with same
76 parametars.
77
78 =cut
79
80 sub new {
81         my $class = shift;
82         my $self = {@_};
83         bless($self, $class);
84
85         my $log = $self->_get_logger;
86
87         $log->logconfess("code_page argument is not suppored any more.") if $self->{code_page};
88         $log->logconfess("encoding argument is not suppored any more.") if $self->{encoding};
89         $log->logconfess("lookup argument is not suppored any more. rewrite call to lookup_ref") if $self->{lookup};
90         $log->logconfess("low_mem argument is not suppored any more. rewrite it to load_row and save_row") if $self->{low_mem};
91
92         $log->logconfess("specify low-level file format module") unless ($self->{module});
93         my $module_path = $self->{module};
94         $module_path =~ s#::#/#g;
95         $module_path .= '.pm';
96         $log->debug("require low-level module $self->{module} from $module_path");
97
98         require $module_path;
99
100         $self ? return $self : return undef;
101 }
102
103 =head2 open
104
105 This function will read whole database in memory and produce lookups.
106
107  my $store;     # simple in-memory hash
108
109  $input->open(
110         path => '/path/to/database/file',
111         input_encoding => 'cp852',
112         strict_encoding => 0,
113         limit => 500,
114         offset => 6000,
115         stats => 1,
116         lookup_coderef => sub {
117                 my $rec = shift;
118                 # store lookups
119         },
120         modify_records => {
121                 900 => { '^a' => { ' : ' => '^b' } },
122                 901 => { '*' => { '^b' => ' ; ' } },
123         },
124         modify_file => 'conf/modify/mapping.map',
125         save_row => sub {
126                 my $a = shift;
127                 $store->{ $a->{id} } = $a->{row};
128         },
129         load_row => sub {
130                 my $a = shift;
131                 return defined($store->{ $a->{id} }) &&
132                         $store->{ $a->{id} };
133         },
134
135  );
136
137 By default, C<input_encoding> is assumed to be C<cp852>.
138
139 C<offset> is optional parametar to position at some offset before reading from database.
140
141 C<limit> is optional parametar to read just C<limit> records from database
142
143 C<stats> create optional report about usage of fields and subfields
144
145 C<lookup_coderef> is closure to called to save data into lookups
146
147 C<modify_records> specify mapping from subfields to delimiters or from
148 delimiters to subfields, as well as oprations on fields (if subfield is
149 defined as C<*>.
150
151 C<modify_file> is alternative for C<modify_records> above which preserves order and offers
152 (hopefully) simplier sintax than YAML or perl (see L</modify_file_regex>). This option
153 overrides C<modify_records> if both exists for same input.
154
155 C<save_row> and C<load_row> are low-level implementation of store engine. Calling convention
156 is documented in example above.
157
158 C<strict_encoding> should really default to 1, but it doesn't for now.
159
160 Returns size of database, regardless of C<offset> and C<limit>
161 parametars, see also C<size>.
162
163 =cut
164
165 sub open {
166         my $self = shift;
167         my $arg = {@_};
168
169         my $log = $self->_get_logger();
170         $log->debug( "arguments: ",dump( $arg ));
171
172         $log->logconfess("encoding argument is not suppored any more.") if $self->{encoding};
173         $log->logconfess("code_page argument is not suppored any more.") if $self->{code_page};
174         $log->logconfess("lookup argument is not suppored any more. rewrite call to lookup_coderef") if ($arg->{lookup});
175         $log->logconfess("lookup_coderef must be CODE, not ",ref($arg->{lookup_coderef}))
176                 if ($arg->{lookup_coderef} && ref($arg->{lookup_coderef}) ne 'CODE');
177
178         $log->debug( $arg->{lookup_coderef} ? '' : 'not ', "using lookup_coderef");
179
180         $log->logcroak("need path") if (! $arg->{'path'});
181         my $input_encoding = $arg->{'input_encoding'} || $self->{'input_encoding'} || 'cp852';
182
183         # store data in object
184         foreach my $v (qw/path offset limit/) {
185                 $self->{$v} = $arg->{$v} if ($arg->{$v});
186         }
187
188         if ($arg->{load_row} || $arg->{save_row}) {
189                 $log->logconfess("save_row and load_row must be defined in pair and be CODE") unless (
190                         ref($arg->{load_row}) eq 'CODE' &&
191                         ref($arg->{save_row}) eq 'CODE'
192                 );
193                 $self->{load_row} = $arg->{load_row};
194                 $self->{save_row} = $arg->{save_row};
195                 $log->debug("using load_row and save_row instead of in-memory hash");
196         }
197
198         my $filter_ref;
199         my $recode_regex;
200         my $recode_map;
201
202         if ($self->{recode}) {
203                 my @r = split(/\s/, $self->{recode});
204                 if ($#r % 2 != 1) {
205                         $log->logwarn("recode needs even number of elements (some number of valid pairs)");
206                 } else {
207                         while (@r) {
208                                 my $from = shift @r;
209                                 my $to = shift @r;
210                                 $recode_map->{$from} = $to;
211                         }
212
213                         $recode_regex = join '|' => keys %{ $recode_map };
214
215                         $log->debug("using recode regex: $recode_regex");
216                 }
217
218         }
219
220         my $rec_regex;
221         if (my $p = $arg->{modify_file}) {
222                 $log->debug("using modify_file $p");
223                 $rec_regex = $self->modify_file_regexps( $p );
224         } elsif (my $h = $arg->{modify_records}) {
225                 $log->debug("using modify_records ", sub { dump( $h ) });
226                 $rec_regex = $self->modify_record_regexps(%{ $h });
227         }
228         $log->debug("rec_regex: ", sub { dump($rec_regex) }) if ($rec_regex);
229
230         my $class = $self->{module} || $log->logconfess("can't get low-level module name!");
231
232         my $ll_db = $class->new(
233                 path => $arg->{path},
234                 input_config => $arg->{input_config} || $self->{input_config},
235 #               filter => sub {
236 #                       my ($l,$f_nr) = @_;
237 #                       return unless defined($l);
238 #                       $l = decode($input_encoding, $l);
239 #                       $l =~ s/($recode_regex)/$recode_map->{$1}/g if ($recode_regex && $recode_map);
240 #                       return $l;
241 #               },
242                 %{ $arg },
243         );
244
245         unless (defined($ll_db)) {
246                 $log->logwarn("can't open database $arg->{path}, skipping...");
247                 return;
248         }
249
250         my $size = $ll_db->size;
251
252         unless ($size) {
253                 $log->logwarn("no records in database $arg->{path}, skipping...");
254                 return;
255         }
256
257         my $from_rec = 1;
258         my $to_rec = $size;
259
260         if (my $s = $self->{offset}) {
261                 $log->debug("skipping to MFN $s");
262                 $from_rec = $s;
263         } else {
264                 $self->{offset} = $from_rec;
265         }
266
267         if ($self->{limit}) {
268                 $log->debug("limiting to ",$self->{limit}," records");
269                 $to_rec = $from_rec + $self->{limit} - 1;
270                 $to_rec = $size if ($to_rec > $size);
271         }
272
273         # store size for later
274         $self->{size} = ($to_rec - $from_rec) ? ($to_rec - $from_rec + 1) : 0;
275
276         my $strict_encoding = $arg->{strict_encoding} || $self->{strict_encoding}; ## FIXME should be 1 really
277
278         $log->info("processing $self->{size}/$size records [$from_rec-$to_rec]",
279                 " encoding $input_encoding ", $strict_encoding ? ' [strict]' : '',
280                 $self->{stats} ? ' [stats]' : '',
281         );
282
283         # read database
284         for (my $pos = $from_rec; $pos <= $to_rec; $pos++) {
285
286                 $log->debug("position: $pos\n");
287
288                 my $rec = $ll_db->fetch_rec($pos, sub {
289                                 my ($l,$f_nr,$debug) = @_;
290 #                               return unless defined($l);
291 #                               return $l unless ($rec_regex && $f_nr);
292
293                                 return unless ( defined($l) && defined($f_nr) );
294
295                                 warn "-=> $f_nr ## |$l|\n" if ($debug);
296                                 $log->debug("-=> $f_nr ## $l");
297
298                                 # codepage conversion and recode_regex
299 #                               $l = decode($input_encoding, $l, 1);
300                                 from_to( $l, $input_encoding, 'utf-8', 1 );
301                                 $l =~ s/($recode_regex)/$recode_map->{$1}/g if ($recode_regex && $recode_map);
302
303                                 # apply regexps
304                                 if ($rec_regex && defined($rec_regex->{$f_nr})) {
305                                         $log->logconfess("regexps->{$f_nr} must be ARRAY") if (ref($rec_regex->{$f_nr}) ne 'ARRAY');
306                                         my $c = 0;
307                                         foreach my $r (@{ $rec_regex->{$f_nr} }) {
308                                                 my $old_l = $l;
309                                                 $log->logconfess("expected regex in ", dump( $r )) unless defined($r->{regex});
310                                                 eval '$l =~ ' . $r->{regex};
311                                                 if ($old_l ne $l) {
312                                                         my $d = "|$old_l| -> |$l| "; # . $r->{regex};
313                                                         $d .= ' +' . $r->{line} . ' ' . $r->{file} if defined($r->{line});
314                                                         $d .= ' ' . $r->{debug} if defined($r->{debug});
315                                                         $log->debug("MODIFY $d");
316                                                         warn "*** $d\n" if ($debug);
317
318                                                 }
319                                                 $log->error("error applying regex: $r") if ($@);
320                                         }
321                                 }
322
323                                 $log->debug("<=- $f_nr ## |$l|");
324                                 warn "<=- $f_nr ## $l\n" if ($debug);
325                                 return $l;
326                 });
327
328                 $log->debug(sub { dump($rec) });
329
330                 if (! $rec) {
331                         $log->warn("record $pos empty? skipping...");
332                         next;
333                 }
334
335                 # store
336                 if ($self->{save_row}) {
337                         $self->{save_row}->({
338                                 id => $pos,
339                                 row => $rec,
340                         });
341                 } else {
342                         $self->{data}->{$pos} = $rec;
343                 }
344
345                 # create lookup
346                 $arg->{'lookup_coderef'}->( $rec ) if ($rec && $arg->{'lookup_coderef'});
347
348                 # update counters for statistics
349                 if ($self->{stats}) {
350
351                         # fetch clean record with regexpes applied for statistics
352                         my $rec = $ll_db->fetch_rec($pos);
353
354                         foreach my $fld (keys %{ $rec }) {
355                                 $self->{_stats}->{fld}->{ $fld }++;
356
357                                 #$log->logdie("invalid record fild $fld, not ARRAY")
358                                 next unless (ref($rec->{ $fld }) eq 'ARRAY');
359         
360                                 foreach my $row (@{ $rec->{$fld} }) {
361
362                                         if (ref($row) eq 'HASH') {
363
364                                                 foreach my $sf (keys %{ $row }) {
365                                                         next if ($sf eq 'subfields');
366                                                         $self->{_stats}->{sf}->{ $fld }->{ $sf }->{count}++;
367                                                         $self->{_stats}->{sf}->{ $fld }->{ $sf }->{repeatable}++
368                                                                         if (ref($row->{$sf}) eq 'ARRAY');
369                                                 }
370
371                                         } else {
372                                                 $self->{_stats}->{repeatable}->{ $fld }++;
373                                         }
374                                 }
375                         }
376                 }
377
378                 $self->progress_bar($pos,$to_rec) unless ($self->{no_progress_bar});
379
380         }
381
382         $self->{pos} = -1;
383         $self->{last_pcnt} = 0;
384
385         # store max mfn and return it.
386         $self->{max_pos} = $to_rec;
387         $log->debug("max_pos: $to_rec");
388
389         # save for dump
390         $self->{ll_db} = $ll_db;
391
392         return $size;
393 }
394
395 =head2 fetch
396
397 Fetch next record from database. It will also displays progress bar.
398
399  my $rec = $isis->fetch;
400
401 Record from this function should probably go to C<data_structure> for
402 normalisation.
403
404 =cut
405
406 sub fetch {
407         my $self = shift;
408
409         my $log = $self->_get_logger();
410
411         $log->logconfess("it seems that you didn't load database!") unless ($self->{pos});
412
413         if ($self->{pos} == -1) {
414                 $self->{pos} = $self->{offset};
415         } else {
416                 $self->{pos}++;
417         }
418
419         my $mfn = $self->{pos};
420
421         if ($mfn > $self->{max_pos}) {
422                 $self->{pos} = $self->{max_pos};
423                 $log->debug("at EOF");
424                 return;
425         }
426
427         $self->progress_bar($mfn,$self->{max_pos}) unless ($self->{no_progress_bar});
428
429         my $rec;
430
431         if ($self->{load_row}) {
432                 $rec = $self->{load_row}->({ id => $mfn });
433         } else {
434                 $rec = $self->{data}->{$mfn};
435         }
436
437         $rec ||= 0E0;
438 }
439
440 =head2 pos
441
442 Returns current record number (MFN).
443
444  print $isis->pos;
445
446 First record in database has position 1.
447
448 =cut
449
450 sub pos {
451         my $self = shift;
452         return $self->{pos};
453 }
454
455
456 =head2 size
457
458 Returns number of records in database
459
460  print $isis->size;
461
462 Result from this function can be used to loop through all records
463
464  foreach my $mfn ( 1 ... $isis->size ) { ... }
465
466 because it takes into account C<offset> and C<limit>.
467
468 =cut
469
470 sub size {
471         my $self = shift;
472         return $self->{size};
473 }
474
475 =head2 seek
476
477 Seek to specified MFN in file.
478
479  $isis->seek(42);
480
481 First record in database has position 1.
482
483 =cut
484
485 sub seek {
486         my $self = shift;
487         my $pos = shift;
488
489         my $log = $self->_get_logger();
490
491         $log->logconfess("called without pos") unless defined($pos);
492
493         if ($pos < 1) {
494                 $log->warn("seek before first record");
495                 $pos = 1;
496         } elsif ($pos > $self->{max_pos}) {
497                 $log->warn("seek beyond last record");
498                 $pos = $self->{max_pos};
499         }
500
501         return $self->{pos} = (($pos - 1) || -1);
502 }
503
504 =head2 stats
505
506 Dump statistics about field and subfield usage
507
508   print $input->stats;
509
510 =cut
511
512 sub stats {
513         my $self = shift;
514
515         my $log = $self->_get_logger();
516
517         my $s = $self->{_stats};
518         if (! $s) {
519                 $log->warn("called stats, but there is no statistics collected");
520                 return;
521         }
522
523         my $max_fld = 0;
524
525         my $out = join("\n",
526                 map {
527                         my $f = $_;
528                         die "no field in ", dump( $s->{fld} ) unless defined( $f );
529                         my $v = $s->{fld}->{$f} || die "no s->{fld}->{$f}";
530                         $max_fld = $v if ($v > $max_fld);
531
532                         my $o = sprintf("%4s %d ~", $f, $v);
533
534                         if (defined($s->{sf}->{$f})) {
535                                 my @subfields = keys %{ $s->{sf}->{$f} };
536                                 map {
537                                         $o .= sprintf(" %s:%d%s", $_, 
538                                                 $s->{sf}->{$f}->{$_}->{count},
539                                                 $s->{sf}->{$f}->{$_}->{repeatable} ? '*' : '',
540                                         );
541                                 } (
542                                         # first indicators and other special subfields
543                                         sort( grep { length($_)  > 1 } @subfields ),
544                                         # then subfileds (single char)
545                                         sort( grep { length($_) == 1 } @subfields ),
546                                 );
547                         }
548
549                         if (my $v_r = $s->{repeatable}->{$f}) {
550                                 $o .= " ($v_r)" if ($v_r != $v);
551                         }
552
553                         $o;
554                 } sort { 
555                         if ( $a =~ m/^\d+$/ && $b =~ m/^\d+$/ ) {
556                                 $a <=> $b
557                         } else {
558                                 $a cmp $b
559                         }
560                 } keys %{ $s->{fld} }
561         );
562
563         $log->debug( sub { dump($s) } );
564
565         return $out;
566 }
567
568 =head2 dump_ascii
569
570 Display humanly readable dump of record
571
572 =cut
573
574 sub dump_ascii {
575         my $self = shift;
576
577         return unless $self->{ll_db};
578
579         if ($self->{ll_db}->can('dump_ascii')) {
580                 return $self->{ll_db}->dump_ascii( $self->{pos} );
581         } else {
582                 return dump( $self->{ll_db}->fetch_rec( $self->{pos} ) );
583         }
584 }
585
586 =head2 _get_regex
587
588 Helper function called which create regexps to be execute on code.
589
590   _get_regex( 900, 'regex:[0-9]+' ,'numbers' );
591   _get_regex( 900, '^b', ' : ^b' );
592
593 It supports perl regexps with C<regex:> prefix to from value and has
594 additional logic to skip empty subfields.
595
596 =cut
597
598 sub _get_regex {
599         my ($sf,$from,$to) = @_;
600
601         # protect /
602         $from =~ s!/!\\/!gs;
603         $to =~ s!/!\\/!gs;
604
605         if ($from =~ m/^regex:(.+)$/) {
606                 $from = $1;
607         } else {
608                 $from = '\Q' . $from . '\E';
609         }
610         if ($sf =~ /^\^/) {
611                 my $need_subfield_data = '*';   # no
612                 # if from is also subfield, require some data in between
613                 # to correctly skip empty subfields
614                 $need_subfield_data = '+' if ($from =~ m/^\\Q\^/);
615                 return
616                         's/\Q'. $sf .'\E([^\^]' . $need_subfield_data . '?)'. $from .'([^\^]*?)/'. $sf .'$1'. $to .'$2/';
617         } else {
618                 return
619                         's/'. $from .'/'. $to .'/g';
620         }
621 }
622
623
624 =head2 modify_record_regexps
625
626 Generate hash with regexpes to be applied using L<filter>.
627
628   my $regexpes = $input->modify_record_regexps(
629                 900 => { '^a' => { ' : ' => '^b' } },
630                 901 => { '*' => { '^b' => ' ; ' } },
631   );
632
633 =cut
634
635 sub modify_record_regexps {
636         my $self = shift;
637         my $modify_record = {@_};
638
639         my $regexpes;
640
641         my $log = $self->_get_logger();
642
643         foreach my $f (keys %$modify_record) {
644                 $log->debug("field: $f");
645
646                 foreach my $sf (keys %{ $modify_record->{$f} }) {
647                         $log->debug("subfield: $sf");
648
649                         foreach my $from (keys %{ $modify_record->{$f}->{$sf} }) {
650                                 my $to = $modify_record->{$f}->{$sf}->{$from};
651                                 #die "no field?" unless defined($to);
652                                 my $d = "|$from| -> |$to|";
653                                 $log->debug("transform: $d");
654
655                                 my $regex = _get_regex($sf,$from,$to);
656                                 push @{ $regexpes->{$f} }, { regex => $regex, debug => $d };
657                                 $log->debug("regex: $regex");
658                         }
659                 }
660         }
661
662         return $regexpes;
663 }
664
665 =head2 modify_file_regexps
666
667 Generate hash with regexpes to be applied using L<filter> from
668 pseudo hash/yaml format for regex mappings.
669
670 It should be obvious:
671
672         200
673           '^a'
674             ' : ' => '^e'
675             ' = ' => '^d'
676
677 In field I<200> find C<'^a'> and then C<' : '>, and replace it with C<'^e'>.
678 In field I<200> find C<'^a'> and then C<' = '>, and replace it with C<'^d'>.
679
680   my $regexpes = $input->modify_file_regexps( 'conf/modify/common.pl' );
681
682 On undef path it will just return.
683
684 =cut
685
686 sub modify_file_regexps {
687         my $self = shift;
688
689         my $modify_path = shift || return;
690
691         my $log = $self->_get_logger();
692
693         my $regexpes;
694
695         CORE::open(my $fh, $modify_path) || $log->logdie("can't open modify file $modify_path: $!");
696
697         my ($f,$sf);
698
699         while(<$fh>) {
700                 chomp;
701                 next if (/^#/ || /^\s*$/);
702
703                 if (/^\s*(\d+)\s*$/) {
704                         $f = $1;
705                         $log->debug("field: $f");
706                         next;
707                 } elsif (/^\s*'([^']*)'\s*$/) {
708                         $sf = $1;
709                         $log->die("can't define subfiled before field in: $_") unless ($f);
710                         $log->debug("subfield: $sf");
711                 } elsif (/^\s*'([^']*)'\s*=>\s*'([^']*)'\s*$/) {
712                         my ($from,$to) = ($1, $2);
713
714                         $log->debug("transform: |$from| -> |$to|");
715
716                         my $regex = _get_regex($sf,$from,$to);
717                         push @{ $regexpes->{$f} }, {
718                                 regex => $regex,
719                                 file => $modify_path,
720                                 line => $.,
721                         };
722                         $log->debug("regex: $regex");
723                 }
724         }
725
726         return $regexpes;
727 }
728
729 =head1 AUTHOR
730
731 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>
732
733 =head1 COPYRIGHT & LICENSE
734
735 Copyright 2005-2006 Dobrica Pavlinusic, All Rights Reserved.
736
737 This program is free software; you can redistribute it and/or modify it
738 under the same terms as Perl itself.
739
740 =cut
741
742 1; # End of WebPAC::Input