add a loading bibs module for mig
[migration-tools.git] / fingerprinter
index 7b20e3e..f388174 100755 (executable)
@@ -1,4 +1,21 @@
 #!/usr/bin/perl
+
+# Copyright 2009-2012, Equinox Software, Inc.
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+
 use strict;
 use warnings;
 use open ':utf8';
@@ -7,6 +24,8 @@ use Getopt::Long;
 use MARC::Batch;
 use Unicode::Normalize;
 use MARC::File::XML ( BinaryEncoding => 'utf-8' );
+use Equinox::Migration::SubfieldMapper;
+use Equinox::Migration::Utils qw/normalize_oclc_number/;
 
 my $conf  = {}; # configuration hashref
 my $count = 0; my $scount = 0;
@@ -15,18 +34,25 @@ $| = 1;
 
 initialize($conf);
 
-open OF, '>', $conf->{output};
-open XF, '>', $conf->{exception};
+open OF, '>', $conf->{output} or die "$0: cannot open output file $conf->{output}: $!\n";
+open XF, '>', $conf->{exception} or die "$0: cannot open exception file $conf->{exception}: $!\n";
 
 for my $file (@ARGV) {
     print XF "Processing $file\n";
-    my $batch = undef; my $record = undef;
 
-    $batch = MARC::Batch->new($conf->{marctype}, $file);
+    my $batch = MARC::Batch->new($conf->{marctype}, $file);
     $batch->strict_off();
     $batch->warnings_off();
 
-    while ( $record = $batch->next ) {
+    my $record;
+    while ( 1 ) {
+        eval { $record = $batch->next; };
+        if ($@) {
+            import MARC::File::XML;
+            print "skipping bad record: $@\n";
+            next;
+        }
+        last unless $record;
         $count++; progress_ticker();
         my $marc = undef;
         unless ( defined $record )
@@ -41,6 +67,8 @@ for my $file (@ARGV) {
 
         # populate and normalize marc
         $marc = populate_marc($record, $id);
+        # check for manual exclusion
+        next if this_record_is_excluded($record, $marc);
         normalize_marc($marc);
         unless (marc_isvalid($marc))
           { dump_exception($marc); next; }
@@ -74,29 +102,33 @@ sub populate_marc {
 
     # date1, date2
     my $my_008 = $record->field('008');
-    $my_008 = $my_008->as_string() if ($my_008);
-    if (defined $my_008) {
-        unless (length $my_008 == 40) {
-            $my_008 = $my_008 . (' ' x (40 - length($my_008)));
-            print XF ">> Short 008 padded to ",length($my_008)," at rec $count\n";
+    $marc{tag008} = $my_008->as_string() if ($my_008);
+    if (defined $marc{tag008}) {
+        unless (length $marc{tag008} == 40) {
+            $marc{tag008} = $marc{tag008} . ('|' x (40 - length($marc{tag008})));
+            print XF ">> Short 008 padded to ",length($marc{tag008})," at rec $count\n";
         }
-        $marc{date1} = substr($my_008,7,4) if ($my_008);
-        $marc{date2} = substr($my_008,11,4) if ($my_008); # UNUSED
+        $marc{date1} = substr($marc{tag008},7,4) if ($marc{tag008});
+        $marc{date2} = substr($marc{tag008},11,4) if ($marc{tag008}); # UNUSED
     }
     unless ($marc{date1} and $marc{date1} =~ /\d{4}/) {
         my $my_260 = $record->field('260');
-        my $date1 = $my_260->subfield('c') if $my_260;
-        if (defined $date1 and $date1 =~ /\d{4}/) {
-            $marc{date1} = $date1;
-            print XF ">> using 260c as date1 at rec $count\n";
+        if ($my_260 and $my_260->subfield('c')) {
+            my $date1 = $my_260->subfield('c');
+            $date1 =~ s/\D//g;
+            if (defined $date1 and $date1 =~ /\d{4}/) {
+                $marc{date1} = $date1;
+                $marc{fudgedate} = 1;
+                print XF ">> using 260c as date1 at rec $count\n";
+            }
         }
     }
 
     # item_form
     if ( $marc{record_type} =~ /[gkroef]/ ) { # MAP, VIS
-        $marc{item_form} = substr($my_008,29,1) if ($my_008);
+        $marc{item_form} = substr($marc{tag008},29,1) if ($marc{tag008});
     } else {
-        $marc{item_form} = substr($my_008,23,1) if ($my_008);
+        $marc{item_form} = substr($marc{tag008},23,1) if ($marc{tag008});
     }
 
     # isbns
@@ -117,18 +149,31 @@ sub populate_marc {
 
     # oclc
     $marc{oclc} = [];
-    push @{ $marc{oclc} }, $record->field('001')->as_string()
-      if ($record->field('001') and $record->field('003') and
-          $record->field('003')->as_string() =~ /OCo{0,1}LC/);
+    if ($record->field('001') &&
+        $record->field('003') &&
+        $record->field('003')->as_string() =~ /OCo{0,1}LC/ &&
+        defined normalize_oclc_number($record->field('001')->as_string())) {
+        push @{ $marc{oclc} }, normalize_oclc_number($record->field('001')->as_string());
+    }
     for ($record->field('035')) {
         my $oclc = $_->subfield('a');
-        push @{ $marc{oclc} }, $oclc
-          if (defined $oclc and $oclc =~ /\(OCoLC\)/ and $oclc =~/([0-9]+)/);
+        if (defined $oclc &&
+            ($oclc =~ /\(OCoLC\)/ || $oclc =~ /(ocm|ocl7|ocn|on)/) &&
+            defined normalize_oclc_number($oclc)) {
+            push @{ $marc{oclc} }, normalize_oclc_number($oclc);
+        }
     }
 
-    # "Accompanying material" (300e)
-    $marc{accomp} = $record->field('300')->subfield('e')
-      if $record->field('300');
+    if ($record->field('999')) {
+        my $koha_bib_id = $record->field('999')->subfield('c');
+        $marc{koha_bib_id} = $koha_bib_id if defined $koha_bib_id and $koha_bib_id =~ /^\d+$/;
+    }
+
+    # "Accompanying material" and check for "copy" (300)
+    if ($record->field('300')) {
+        $marc{accomp} = $record->field('300')->subfield('e');
+        $marc{tag300a} = $record->field('300')->subfield('a');
+    }
 
     # issn, lccn, title, desc, pages, pub, pubyear, edition
     $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
@@ -137,6 +182,10 @@ sub populate_marc {
     $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
     $marc{title} = $record->field('245')->subfield('a')
       if $record->field('245');
+    $marc{title} .= ' ' . $record->field('245')->subfield('b')
+      if ($record->field('245') and 
+          $record->field('245')->subfield('b') and 
+          not $conf->{ignoresubtitle});
     $marc{edition} = $record->field('250')->subfield('a')
       if $record->field('250');
     if ($record->field('260')) {
@@ -208,69 +257,85 @@ sub marc_isvalid {
 
 Assign a score to the record based on various criteria.
 
-Score is constructed by pushing elements onto a list. At the end of
-the routine, the list is flattened into a string via join();
+Score is constructed by pushing elements onto a list, via a dispatch
+table.  This allows order of fingerprints in the output file to be
+varied.
 
 =cut
 
 sub score_marc {
     my ($marc, $record) = @_;
     my @score = ();
-    my $chunk;
-
-    # Is this an OCLC record?
-    if ($conf->{scores}{oclc}) {
-        if ($record->field('008')) {
-            $chunk = $record->field('008')->as_string();
-            push @score, ( $chunk =~ /^o/i ? 1 : 0 );
-        } else {
-            push @score, 0;
-        }
-    }
+    my $json = '{';
 
-    # does 040a contain "dlc"?
-    if ($conf->{scores}{dlc}) {
-        if ($record->field('040') and $record->field('040')->subfield('a')) {
-            $chunk = $record->field('040')->subfield('a');
-            push @score, ( $chunk =~ /dlc/i ? 1 : 0 );
-        } else {
-            push @score, 0;
-        }
-    }
+    #----------------------------------
+    # static criteria scoring
+    #----------------------------------
+    $marc->{misc_score} = 999;
+    $marc->{age_score}  = 999999999999;
 
-    # number of 650 datafields
-    # zero-padded to 4 digits with printf
-    if ($conf->{scores}{num_650}) {
-        if ($record->field('650')) {
-            my @tags = $record->field('650');
-            push @score, scalar @tags;
-        } else {
-            push @score, 0;
-        }
+    # -1 if 008 has been padded, -2 if it doesn't exist
+    if ($marc->{tag008})
+      { $marc->{misc_score}-- if ($marc->{tag008} =~ /\|$/) }
+    else
+      { $marc->{misc_score} -= 2 }
+    # -1 if date has been pulled from 260
+    $marc->{misc_score}-- if $marc->{fudgedate};
+    # -1 if this is a copy record
+    $marc->{misc_score}--
+      if (defined $marc->{tag300a} and $marc->{tag300a} =~ /copy/i);
+
+    # subtract record id if we want older records to win
+    #$marc->{age_score} -= $marc->{id} unless ($conf->{newwins});
+    # handle arbitrary adjustments
+    $marc->{age_score} = 1;
+    if ($conf->{'arbitrarily-lose-above'}) {
+        $marc->{age_score} = 0
+          if ($marc->{id} >= $conf->{'arbitrarily-lose-above'});
     }
-
-    # number of tags in total
-    # zero-padded to 4 digits with printf
-    if ($conf->{scores}{num_tags}) {
-        my @tags = $record->fields;
-        push @score, scalar @tags;
+    if ($conf->{'arbitrarily-lose-below'}) {
+        $marc->{age_score} = 0
+          if ($marc->{id} <= $conf->{'arbitrarily-lose-below'});
     }
 
-    # encoding level
-    if ($conf->{scores}{enc_lvl}) {
-        my $enc = substr($record->leader, 17, 1);
+    #----------------------------------
+    # dynamic calculated scoring
+    #----------------------------------
+    my %scores_code = (
+      oclc    => sub { return $marc->{oclc}[0] ? 1 : 0 },
+      dlc     => sub {
+          if ($record->field('040') and $record->field('040')->subfield('a'))
+            { return scalar($record->subfield( '040', 'a')) =~ /dlc/io ? 1 : 0 }
+          else { return 0 }
+      },
+      num_650 => sub {
+          if ($record->field('650')) {
+              # can't say "scalar $record->field('650')"; MARC::Record
+              # behaves differently in list/scalar contexts
+              my @tags = $record->field('650');
+              return sprintf("%04d", scalar @tags)
+          } else { return '0000' }
+      },
+      num_tags=> sub { return sprintf( '%04d', scalar( $record->fields ) ) },
+      enc_lvl => sub {
+        my $enc = substr($record->leader, 17, 1) || 'u';
         my %levels = ( ' ' => 9, 1 => 8, 2 => 7,  3  => 6,  4  => 5, 5 => 4,
                        6   => 3, 7 => 2, 8 => 1, 'u' => 0, 'z' => 0 );
-        if (defined $enc and $levels{$enc})
-          { push @score, $levels{$enc} }
-        else
-          { push @score, 0 }
+        return $levels{$enc} || 0;
+    }
+                      );
+
+    #----------------------------------
+    # assemble and store scores
+    #----------------------------------
+    for ( @{ $conf->{dyn_scores} } ) {
+        push @score, $scores_code{$_}->($marc, $record);
+        $json .= $_ . ':' . $score[-1] . ',';
     }
+    $json .= 'misc:' . $marc->{misc_score} . '}';
 
-    # put score in marc hash
-    $marc->{score} = join('', '{oclc:', $score[0], ',dlc:', $score[1],
-                          ',num_650:', $score[2], ',num_tags:', $score[3],
-                          ',enc_lvl:', $score[4], '}');
+    my $compact = join('', $marc->{age_score}, $marc->{misc_score}, @score);
+    $marc->{score} = "$compact\t$json";
 }
 
 =head2 dump_fingerprints
@@ -295,6 +360,14 @@ sub dump_fingerprints {
         }
     }
 
+    if ($conf->{fingerprints}{koha_bib_id} and exists $marc->{koha_bib_id}) {
+        print OF join("\t", $marc->{score}, $marc->{id}, "z_koha_bib_id",
+                      $marc->{item_form}, $marc->{date1},
+                      $marc->{record_type},
+                      $marc->{bib_lvl}, $marc->{title},
+                      $marc->{koha_bib_id}), "\n";
+    }
+
     if ($conf->{fingerprints}{isbn}) {
         if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
             foreach my $isbn ( @{ $marc->{isbns}} ) {
@@ -307,11 +380,11 @@ sub dump_fingerprints {
         }
     }
 
-    if ($conf->{fingerprints}{edition} and $marc->{edition}) {
+    if ($conf->{fingerprints}{edition} and $marc->{edition} and $marc->{author}) {
         print OF join("\t", $marc->{score}, $marc->{id}, "edition",
                       $marc->{item_form}, $marc->{date1},
                       $marc->{record_type}, $marc->{bib_lvl},
-                      $marc->{title}, $marc->{edition}), "\n";
+                      $marc->{title}, $marc->{author}, $marc->{edition}), "\n";
     }
 
     if ($conf->{fingerprints}{issn} and $marc->{issn}) {
@@ -355,25 +428,67 @@ Write line of exception report
 =cut
 
 sub dump_exception {
-    my ($marc) = @_;
+    my ($marc, $msg) = @_;
     unless (defined $marc) {
         print XF "Undefined record at line $count; likely bad XML\n";
         return;
     }
-    print XF "Record ", $marc->{id}, " did not make the cut: ";
-    print XF "Missing item_form. " unless ($marc->{item_form});
+
+    print XF "Record ", $marc->{id}, " excluded: ";
+    if (defined $msg) {
+        print XF "$msg\n";
+        return
+    }
+
+    print XF "missing item_form; " unless ($marc->{item_form});
     unless (defined $marc->{date1})
-      { print XF "Missing date1. " }
+      { print XF "missing date1; " }
     else
-      { print XF "Invalid date1: ", $marc->{date1}, " "
+      { print XF "invalid date1: '", $marc->{date1}, "'; "
           unless ($marc->{date1} =~ /\d{4}/); }
-    print XF "Missing record_type. " unless ($marc->{record_type});
-    print XF "Missing bib_lvl. " unless ($marc->{bib_lvl});
-    print XF "Missing title. " unless ($marc->{title});
+    print XF "missing record_type; " unless ($marc->{record_type});
+    print XF "missing bib_lvl; " unless ($marc->{bib_lvl});
+    print XF "missing title " unless ($marc->{title});
     print XF "\n";
 }
 
 
+=head2 this_record_is_excluded
+
+Returns 1 if the record B<is> and 0 if the record B<is not> excluded,
+according to the subfield mapping (generated via the C<--excludelist>
+option).
+
+=cut
+
+sub this_record_is_excluded {
+    my ($rec, $marc) = @_;
+    return 0 unless defined $conf->{excludelist};
+
+    for my $tag (keys %{ $conf->{excludelist}->{tags} }) {
+        for my $sub (keys %{$conf->{excludelist}->{tags}{$tag}}) {
+            my $f = $conf->{excludelist}->field($tag, $sub);
+
+            # if this record doesn't have the right tag/sub, it can't be
+            return 0 unless ($rec->field($tag) and $rec->field($tag)->subfield($sub));
+            # but it does, so if there are no filters to check...
+            unless ($conf->{excludelist}->filters($f))
+              { dump_exception($marc, "exclusion $tag$sub"); return 1 }
+
+            my $sub_contents = $rec->field($tag)->subfield($sub);
+            for my $filter (@{ $conf->{excludelist}->filters($f)}) {
+                if ($sub_contents =~ /$filter/i) {
+                    # filter matches. no fp.
+                    dump_exception($marc, "exclusion $tag$sub '$filter'");
+                    return 1;
+                }
+                # no match, no exclude
+                return 0;
+            }
+        }
+    }
+}
+
 =head2 initialize
 
 Performs boring script initialization. Handles argument parsing,
@@ -389,16 +504,19 @@ sub initialize {
     binmode(STDIN, ':utf8');
 
     my $rc = GetOptions( $c,
-                         'incoming',
-                         'incumbent',
                          'exception|x=s',
-                         'marctype|m=s',
                          'output|o=s',
-                         'runtype|r=s',
+                         'prefix|p=s',
+                         'marctype|m=s',
                          'subfield|s=s',
                          'tag|t=s',
                          'fingerprints=s',
                          'scores=s',
+                         'arbitrarily-lose-above=i',
+                         'arbitrarily-lose-below=i',
+                         'newwins',
+                         'excludelist=s',
+                         'ignoresubtitle|i',
                          'quiet|q',
                          'help|h',
                        );
@@ -411,6 +529,7 @@ sub initialize {
         my %valid_fps = ( oclc => 1, isbn => 1, issn => 1, lccn => 1,
                           edition => 1, accomp => 1, authpub => 1,
                           baseline => 1, crap => 1,
+                          koha_bib_id => 1,
                         );
         for (split /,/, $c->{fingerprints}) {
             die "Invalid fingerprint '$_'\n" unless $valid_fps{$_};
@@ -421,6 +540,7 @@ sub initialize {
         $c->{fingerprints} = {oclc => 1, isbn => 1, edition => 1, issn => 1,
                               lccn => 1, accomp => 1, authpub => 1};
     }
+
     # check scores list for validity
     if ($c->{scores}) {
         my %scores = ();
@@ -431,25 +551,27 @@ sub initialize {
             die "Invalid score mode '$_'\n" unless $valid_scores{$_};
             $scores{$_} = 1;
         }
+        $c->{dyn_scores} = [split /,/, $c->{scores}];
         $c->{scores} = \%scores;
     } else {
         $c->{scores} = {oclc => 1, dlc => 1, num_650 => 1,
                         num_tags => 1, enc_lvl => 1};
+        $c->{dyn_scores} = [ qw/oclc dlc num_650 num_tags enc_lvl/ ];
     }
 
-    # set defaults if told to do so
-    if ($c->{incoming}) {
-        $c->{tag} = 903 unless defined $c->{tag};
-        $c->{subfield} = 'a' unless defined $c->{subfield};
-        $c->{marctype} = 'XML' unless defined $c->{marctype};
-        $c->{output} = 'incoming.fp' unless defined $c->{output};
-        $c->{exception} = 'incoming.ex' unless defined $c->{exception};
-    } elsif ($c->{incumbent}) {
-        $c->{tag} = 901 unless defined $c->{tag};
-        $c->{subfield} = 'c' unless defined $c->{subfield};
-        $c->{marctype} = 'XML' unless defined $c->{marctype};
-        $c->{output} = 'incumbent.fp' unless defined $c->{output};
-        $c->{exception} = 'incumbent.ex' unless defined $c->{exception};
+    # set defaults
+    $c->{tag} = 903 unless defined $c->{tag};
+    $c->{subfield} = 'a' unless defined $c->{subfield};
+    $c->{marctype} = 'XML' unless defined $c->{marctype};
+    if ($c->{prefix}) {
+        $c->{output} = join('.',$c->{prefix},'fp');
+        $c->{exception} = join('.',$c->{prefix},'fp','ex');
+    }
+
+    # get SFM object if excludelist was specified
+    if ($c->{excludelist}) {
+        $c->{excludelist} =
+          Equinox::Migration::SubfieldMapper->new( file => $c->{excludelist} );
     }
 
     my @keys = keys %{$c};
@@ -484,20 +606,32 @@ sub show_help {
 print <<HELP;
 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
 Req'd Arguments
-  --tag=N                  -t  Which tag to use
-  --subfield=X             -s  Which subfield to use
-  --output=<file>          -o  Output filename
-  --exceptions=<file>      -x  Exception report filename
+  --output=<FILE>      -o  Output filename
+  --exceptions=<FILE>  -x  Exception report filename
+       or
+  --prefix=<PREFIX>>   -p  Shared prefix for output/exception files. Will
+                           produce PREFIX.fp and PREFIX.fp.ex
 Options
-  --incoming   '-t 903 -s a -o incoming.fp -x incoming.ex'
-  --incumbent  '-t 901 -s c -o incumbent.fp -x incumbent.ex'
+  --tag=N           -t  Which tag to use (default 903)
+  --subfield=X      -s  Which subfield to use (default 'a')
+  --quiet           -q  Don't write status messages to STDOUT
+  --ignoresubtitle  -i  Ignore 245\$b and construct the title from 245\$a alone.
 
   --fingerprints=LIST  Fingerprints to generate, comma separated
                        Default: oclc,isbn,edition,issn,lccn,accomp,authpub
-                       Others:  baseline
+                       Others:  baseline,koha_bib_id
+  --excludelist=FILE   Name of fingerprints exclusions file
+
   --scores=LIST  Scores to calculate, comma separated
                  Default: oclc,dlc,num_650,num_tags,enc_level
-  --quiet    -q  Don't write status messages to STDOUT
+  --newwins      New record IDs score higher (default is old wins)
+  --arbitrarily-lose-above
+  --arbitrarily-lose-below
+  --arbitrarily-decrease-score-by
+      Modify fingerprint scoring of records whose EG id is above or below a
+      given value, inclusive (so 5 is <= 5 or >= 5) such that they lose.
+
+  --marctype=TYPE Defaults to 'XML'
 HELP
 exit 1;
 }