9 use base qw/WebPAC::Common/;
11 use Encode qw/from_to/;
15 WebPAC::Input - read different file formats into WebPAC
23 our $VERSION = '0.13';
27 This module implements input as database which have fixed and known
28 I<size> while indexing and single unique numeric identifier for database
29 position ranging from 1 to I<size>.
31 Simply, something that is indexed by unmber from 1 .. I<size>.
33 Examples of such databases are CDS/ISIS files, MARC files, lines in
36 Specific file formats are implemented using low-level interface modules,
37 located in C<WebPAC::Input::*> namespace which export C<open_db>,
38 C<fetch_rec> and optional C<init> functions.
40 Perhaps a little code snippet.
44 my $db = WebPAC::Input->new(
45 module => 'WebPAC::Input::ISIS',
49 $db->open( path => '/path/to/database' );
50 print "database size: ",$db->size,"\n";
51 while (my $rec = $db->fetch) {
52 # do something with $rec
61 Create new input database object.
63 my $db = new WebPAC::Input(
64 module => 'WebPAC::Input::MARC',
65 encoding => 'ISO-8859-2',
67 recode => 'char pairs',
71 C<module> is low-level file format module. See L<WebPAC::Input::ISIS> and
72 L<WebPAC::Input::MARC>.
74 Optional parametar C<encoding> specify application code page (which will be
75 used internally). This should probably be your terminal encoding, and by
76 default, it C<ISO-8859-2>.
78 Default is not to use C<low_mem> options (see L<MEMORY USAGE> below).
80 C<recode> is optional string constisting of character or words pairs that
81 should be replaced in input stream.
83 C<no_progress_bar> disables progress bar output on C<STDOUT>
85 This function will also call low-level C<init> if it exists with same
95 my $log = $self->_get_logger;
97 $log->logconfess("code_page argument is not suppored any more. change it to encoding") if ($self->{lookup});
98 $log->logconfess("lookup argument is not suppored any more. rewrite call to lookup_ref") if ($self->{lookup});
100 $log->logconfess("specify low-level file format module") unless ($self->{module});
101 my $module_path = $self->{module};
102 $module_path =~ s#::#/#g;
103 $module_path .= '.pm';
104 $log->debug("require low-level module $self->{module} from $module_path");
106 require $module_path;
108 # check if required subclasses are implemented
109 foreach my $subclass (qw/open_db fetch_rec init dump_rec/) {
113 $self->{'encoding'} ||= 'ISO-8859-2';
115 $self ? return $self : return undef;
120 This function will read whole database in memory and produce lookups.
123 path => '/path/to/database/file',
124 code_page => 'cp852',
128 lookup_coderef => sub {
133 900 => { '^a' => { ' : ' => '^b' } },
134 901 => { '*' => { '^b' => ' ; ' } },
136 modify_file => 'conf/modify/mapping.map',
139 By default, C<code_page> is assumed to be C<cp852>.
141 C<offset> is optional parametar to position at some offset before reading from database.
143 C<limit> is optional parametar to read just C<limit> records from database
145 C<stats> create optional report about usage of fields and subfields
147 C<lookup_coderef> is closure to called to save data into lookups
149 C<modify_records> specify mapping from subfields to delimiters or from
150 delimiters to subfields, as well as oprations on fields (if subfield is
153 C<modify_file> is alternative for C<modify_records> above which preserves order and offers
154 (hopefully) simplier sintax than YAML or perl (see L</modify_file_regex>). This option
155 overrides C<modify_records> if both exists for same input.
157 Returns size of database, regardless of C<offset> and C<limit>
158 parametars, see also C<size>.
166 my $log = $self->_get_logger();
168 $log->logconfess("lookup argument is not suppored any more. rewrite call to lookup_coderef") if ($arg->{lookup});
169 $log->logconfess("lookup_coderef must be CODE, not ",ref($arg->{lookup_coderef}))
170 if ($arg->{lookup_coderef} && ref($arg->{lookup_coderef}) ne 'CODE');
172 $log->debug( $arg->{lookup_coderef} ? '' : 'not ', "using lookup_coderef");
174 $log->logcroak("need path") if (! $arg->{'path'});
175 my $code_page = $arg->{'code_page'} || 'cp852';
177 # store data in object
178 $self->{'input_code_page'} = $code_page;
179 foreach my $v (qw/path offset limit/) {
180 $self->{$v} = $arg->{$v} if ($arg->{$v});
187 if ($self->{recode}) {
188 my @r = split(/\s/, $self->{recode});
190 $log->logwarn("recode needs even number of elements (some number of valid pairs)");
195 $recode_map->{$from} = $to;
198 $recode_regex = join '|' => keys %{ $recode_map };
200 $log->debug("using recode regex: $recode_regex");
206 if (my $p = $arg->{modify_file}) {
207 $log->debug("using modify_file $p");
208 $rec_regex = $self->modify_file_regexps( $p );
209 } elsif (my $h = $arg->{modify_records}) {
210 $log->debug("using modify_records ", Dumper( $h ));
211 $rec_regex = $self->modify_record_regexps(%{ $h });
213 $log->debug("rec_regex: ", Dumper($rec_regex)) if ($rec_regex);
215 my $class = $self->{module} || $log->logconfess("can't get low-level module name!");
217 my $ll_db = $class->new(
218 path => $arg->{path},
220 # my ($l,$f_nr) = @_;
221 # return unless defined($l);
222 # from_to($l, $code_page, $self->{'encoding'});
223 # $l =~ s/($recode_regex)/$recode_map->{$1}/g if ($recode_regex && $recode_map);
229 unless (defined($ll_db)) {
230 $log->logwarn("can't open database $arg->{path}, skipping...");
234 my $size = $ll_db->size;
237 $log->logwarn("no records in database $arg->{path}, skipping...");
244 if (my $s = $self->{offset}) {
245 $log->debug("skipping to MFN $s");
248 $self->{offset} = $from_rec;
251 if ($self->{limit}) {
252 $log->debug("limiting to ",$self->{limit}," records");
253 $to_rec = $from_rec + $self->{limit} - 1;
254 $to_rec = $size if ($to_rec > $size);
257 # store size for later
258 $self->{size} = ($to_rec - $from_rec) ? ($to_rec - $from_rec + 1) : 0;
260 $log->info("processing $self->{size}/$size records [$from_rec-$to_rec] convert $code_page -> $self->{encoding}", $self->{stats} ? ' [stats]' : '');
262 # turn on low_mem for databases with more than 100000 records!
263 if (! $self->{low_mem} && $size > 100000) {
264 $log->warn("Using on-disk storage instead of memory for input data. This will affect performance.");
268 # running with low_mem flag? well, use DBM::Deep then.
269 if ($self->{'low_mem'}) {
270 $log->info("running with low_mem which impacts performance (<32 Mb memory usage)");
272 my $db_file = "data.db";
275 unlink $db_file or $log->logdie("can't remove '$db_file' from last run");
276 $log->debug("removed '$db_file' from last run");
281 my $db = new DBM::Deep $db_file;
283 $log->logdie("DBM::Deep error: $!") unless ($db);
286 $log->logdie("can't open '$db_file' under low_mem: ",$db->error());
288 $log->debug("using file '$db_file' for DBM::Deep");
295 for (my $pos = $from_rec; $pos <= $to_rec; $pos++) {
297 $log->debug("position: $pos\n");
299 my $rec = $ll_db->fetch_rec($pos, sub {
301 # return unless defined($l);
302 # return $l unless ($rec_regex && $f_nr);
304 $log->debug("-=> $f_nr ## $l");
306 # codepage conversion and recode_regex
307 from_to($l, $code_page, $self->{'encoding'});
308 $l =~ s/($recode_regex)/$recode_map->{$1}/g if ($recode_regex && $recode_map);
311 if ($rec_regex && defined($rec_regex->{$f_nr})) {
312 $log->logconfess("regexps->{$f_nr} must be ARRAY") if (ref($rec_regex->{$f_nr}) ne 'ARRAY');
314 foreach my $r (@{ $rec_regex->{$f_nr} }) {
318 $log->debug("REGEX on $f_nr eval \$l =~ $r\n## old l: [$old_l]\n## new l: [$l]");
320 $log->error("error applying regex: $r") if ($@);
324 $log->debug("<=- $f_nr ## $l");
328 $log->debug(sub { Dumper($rec) });
331 $log->warn("record $pos empty? skipping...");
336 if ($self->{low_mem}) {
337 $self->{db}->put($pos, $rec);
339 $self->{data}->{$pos} = $rec;
343 $arg->{'lookup_coderef'}->( $rec ) if ($rec && $arg->{'lookup_coderef'});
345 # update counters for statistics
346 if ($self->{stats}) {
348 # fetch clean record with regexpes applied for statistics
349 my $rec = $ll_db->fetch_rec($pos);
351 foreach my $fld (keys %{ $rec }) {
352 $self->{_stats}->{fld}->{ $fld }++;
354 $log->logdie("invalid record fild $fld, not ARRAY")
355 unless (ref($rec->{ $fld }) eq 'ARRAY');
357 foreach my $row (@{ $rec->{$fld} }) {
359 if (ref($row) eq 'HASH') {
361 foreach my $sf (keys %{ $row }) {
362 next if ($sf eq 'subfields');
363 $self->{_stats}->{sf}->{ $fld }->{ $sf }->{count}++;
364 $self->{_stats}->{sf}->{ $fld }->{ $sf }->{repeatable}++
365 if (ref($row->{$sf}) eq 'ARRAY');
369 $self->{_stats}->{repeatable}->{ $fld }++;
375 $self->progress_bar($pos,$to_rec) unless ($self->{no_progress_bar});
380 $self->{last_pcnt} = 0;
382 # store max mfn and return it.
383 $self->{max_pos} = $to_rec;
384 $log->debug("max_pos: $to_rec");
387 $self->{ll_db} = $ll_db;
394 Fetch next record from database. It will also displays progress bar.
396 my $rec = $isis->fetch;
398 Record from this function should probably go to C<data_structure> for
406 my $log = $self->_get_logger();
408 $log->logconfess("it seems that you didn't load database!") unless ($self->{pos});
410 if ($self->{pos} == -1) {
411 $self->{pos} = $self->{offset};
416 my $mfn = $self->{pos};
418 if ($mfn > $self->{max_pos}) {
419 $self->{pos} = $self->{max_pos};
420 $log->debug("at EOF");
424 $self->progress_bar($mfn,$self->{max_pos}) unless ($self->{no_progress_bar});
428 if ($self->{low_mem}) {
429 $rec = $self->{db}->get($mfn);
431 $rec = $self->{data}->{$mfn};
439 Returns current record number (MFN).
443 First record in database has position 1.
455 Returns number of records in database
459 Result from this function can be used to loop through all records
461 foreach my $mfn ( 1 ... $isis->size ) { ... }
463 because it takes into account C<offset> and C<limit>.
469 return $self->{size};
474 Seek to specified MFN in file.
478 First record in database has position 1.
484 my $pos = shift || return;
486 my $log = $self->_get_logger();
489 $log->warn("seek before first record");
491 } elsif ($pos > $self->{max_pos}) {
492 $log->warn("seek beyond last record");
493 $pos = $self->{max_pos};
496 return $self->{pos} = (($pos - 1) || -1);
501 Dump statistics about field and subfield usage
510 my $log = $self->_get_logger();
512 my $s = $self->{_stats};
514 $log->warn("called stats, but there is no statistics collected");
522 my $f = $_ || die "no field";
523 my $v = $s->{fld}->{$f} || die "no s->{fld}->{$f}";
524 $max_fld = $v if ($v > $max_fld);
526 my $o = sprintf("%4s %d ~", $f, $v);
528 if (defined($s->{sf}->{$f})) {
530 $o .= sprintf(" %s:%d%s", $_,
531 $s->{sf}->{$f}->{$_}->{count},
532 $s->{sf}->{$f}->{$_}->{repeatable} ? '*' : '',
534 } sort keys %{ $s->{sf}->{$f} };
537 if (my $v_r = $s->{repeatable}->{$f}) {
538 $o .= " ($v_r)" if ($v_r != $v);
542 } sort { $a cmp $b } keys %{ $s->{fld} }
545 $log->debug( sub { Dumper($s) } );
552 Display humanly readable dump of record
559 return $self->{ll_db}->dump_rec( $self->{pos} );
563 =head2 modify_record_regexps
565 Generate hash with regexpes to be applied using l<filter>.
567 my $regexpes = $input->modify_record_regexps(
568 900 => { '^a' => { ' : ' => '^b' } },
569 901 => { '*' => { '^b' => ' ; ' } },
575 my ($sf,$from,$to) = @_;
578 's/\Q'. $sf .'\E([^\^]*?)\Q'. $from .'\E([^\^]*?)/'. $sf .'$1'. $to .'$2/';
581 's/\Q'. $from .'\E/'. $to .'/g';
585 sub modify_record_regexps {
587 my $modify_record = {@_};
591 my $log = $self->_get_logger();
593 foreach my $f (keys %$modify_record) {
594 $log->debug("field: $f");
596 foreach my $sf (keys %{ $modify_record->{$f} }) {
597 $log->debug("subfield: $sf");
599 foreach my $from (keys %{ $modify_record->{$f}->{$sf} }) {
600 my $to = $modify_record->{$f}->{$sf}->{$from};
601 #die "no field?" unless defined($to);
602 $log->debug("transform: |$from| -> |$to|");
604 my $regex = _get_regex($sf,$from,$to);
605 push @{ $regexpes->{$f} }, $regex;
606 $log->debug("regex: $regex");
614 =head2 modify_file_regexps
616 Generate hash with regexpes to be applied using l<filter> from
617 pseudo hash/yaml format for regex mappings.
619 It should be obvious:
626 In field I<200> find C<'^a'> and then C<' : '>, and replace it with C<'^e'>.
627 In field I<200> find C<'^a'> and then C<' = '>, and replace it with C<'^d'>.
629 my $regexpes = $input->modify_file_regexps( 'conf/modify/common.pl' );
631 On undef path it will just return.
635 sub modify_file_regexps {
638 my $modify_path = shift || return;
640 my $log = $self->_get_logger();
644 CORE::open(my $fh, $modify_path) || $log->logdie("can't open modify file $modify_path: $!");
650 next if (/^#/ || /^\s*$/);
652 if (/^\s*(\d+)\s*$/) {
654 $log->debug("field: $f");
656 } elsif (/^\s*'([^']*)'\s*$/) {
658 $log->die("can't define subfiled before field in: $_") unless ($f);
659 $log->debug("subfield: $sf");
660 } elsif (/^\s*'([^']*)'\s*=>\s*'([^']*)'\s*$/) {
661 my ($from,$to) = ($1, $2);
663 $log->debug("transform: |$from| -> |$to|");
665 my $regex = _get_regex($sf,$from,$to);
666 push @{ $regexpes->{$f} }, $regex;
667 $log->debug("regex: $regex");
676 C<low_mem> options is double-edged sword. If enabled, WebPAC
677 will run on memory constraint machines (which doesn't have enough
678 physical RAM to create memory structure for whole source database).
680 If your machine has 512Mb or more of RAM and database is around 10000 records,
681 memory shouldn't be an issue. If you don't have enough physical RAM, you
682 might consider using virtual memory (if your operating system is handling it
683 well, like on FreeBSD or Linux) instead of dropping to L<DBM::Deep> to handle
684 parsed structure of ISIS database (this is what C<low_mem> option does).
686 Hitting swap at end of reading source database is probably o.k. However,
687 hitting swap before 90% will dramatically decrease performance and you will
688 be better off with C<low_mem> and using rest of availble memory for
689 operating system disk cache (Linux is particuallary good about this).
690 However, every access to database record will require disk access, so
691 generation phase will be slower 10-100 times.
693 Parsed structures are essential - you just have option to trade RAM memory
694 (which is fast) for disk space (which is slow). Be sure to have planty of
695 disk space if you are using C<low_mem> and thus L<DBM::Deep>.
697 However, when WebPAC is running on desktop machines (or laptops :-), it's
698 highly undesireable for system to start swapping. Using C<low_mem> option can
699 reduce WecPAC memory usage to around 64Mb for same database with lookup
700 fields and sorted indexes which stay in RAM. Performance will suffer, but
701 memory usage will really be minimal. It might be also more confortable to
702 run WebPAC reniced on those machines.
707 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>
709 =head1 COPYRIGHT & LICENSE
711 Copyright 2005-2006 Dobrica Pavlinusic, All Rights Reserved.
713 This program is free software; you can redistribute it and/or modify it
714 under the same terms as Perl itself.
718 1; # End of WebPAC::Input