also set grace period when applying circ policies
[migration-tools.git] / fingerprinter
1 #!/usr/bin/perl
2
3 # Copyright 2009-2012, Equinox Software, Inc.
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 use strict;
20 use warnings;
21 use open ':utf8';
22
23 use Getopt::Long;
24 use MARC::Batch;
25 use Unicode::Normalize;
26 use MARC::File::XML ( BinaryEncoding => 'utf-8' );
27 use Equinox::Migration::SubfieldMapper;
28
29 my $conf  = {}; # configuration hashref
30 my $count = 0; my $scount = 0;
31 my $start = time;
32 $| = 1;
33
34 initialize($conf);
35
36 open OF, '>', $conf->{output} or die "$0: cannot open output file $conf->{output}: $!\n";
37 open XF, '>', $conf->{exception} or die "$0: cannot open exception file $conf->{exception}: $!\n";
38
39 for my $file (@ARGV) {
40     print XF "Processing $file\n";
41
42     my $batch = MARC::Batch->new($conf->{marctype}, $file);
43     $batch->strict_off();
44     $batch->warnings_off();
45
46     my $record;
47     while ( 1 ) {
48         eval { $record = $batch->next; };
49         if ($@) {
50             import MARC::File::XML;
51             print "skipping bad record: $@\n";
52             next;
53         }
54         last unless $record;
55         $count++; progress_ticker();
56         my $marc = undef;
57         unless ( defined $record )
58           { dump_exception($marc); next; }
59
60         my $id = $record->field($conf->{tag});
61         unless ($id) {
62             print XF "ERROR: Record $count in $file is missing a ",
63               $conf->{tag}, " field.\n", $record->as_formatted(), "\n=====\n";
64             next;
65         }
66
67         # populate and normalize marc
68         $marc = populate_marc($record, $id);
69         # check for manual exclusion
70         next if this_record_is_excluded($record, $marc);
71         normalize_marc($marc);
72         unless (marc_isvalid($marc))
73           { dump_exception($marc); next; }
74
75         # if everything looks good, score it and dump fingerprints
76         score_marc($marc, $record);
77         dump_fingerprints($marc);
78         $scount++; progress_ticker();
79     }
80 }
81
82 print "\nSuccessfully processed:\t$count\n" unless $conf->{quiet};
83
84 =head2 populate_marc
85
86 Constructs a hash containing the relevant MARC data for a record and
87 returns a reference to it.
88
89 =cut
90
91 sub populate_marc {
92     my ($record, $id) = @_;
93     my %marc = (); $marc{isbns} = [];
94
95     # id, stringified
96     $marc{id} = $id->as_string($conf->{subfield});
97
98     # record_type, bib_lvl
99     $marc{record_type} = substr($record->leader, 6, 1);
100     $marc{bib_lvl}     = substr($record->leader, 7, 1);
101
102     # date1, date2
103     my $my_008 = $record->field('008');
104     $marc{tag008} = $my_008->as_string() if ($my_008);
105     if (defined $marc{tag008}) {
106         unless (length $marc{tag008} == 40) {
107             $marc{tag008} = $marc{tag008} . ('|' x (40 - length($marc{tag008})));
108             print XF ">> Short 008 padded to ",length($marc{tag008})," at rec $count\n";
109         }
110         $marc{date1} = substr($marc{tag008},7,4) if ($marc{tag008});
111         $marc{date2} = substr($marc{tag008},11,4) if ($marc{tag008}); # UNUSED
112     }
113     unless ($marc{date1} and $marc{date1} =~ /\d{4}/) {
114         my $my_260 = $record->field('260');
115         if ($my_260 and $my_260->subfield('c')) {
116             my $date1 = $my_260->subfield('c');
117             $date1 =~ s/\D//g;
118             if (defined $date1 and $date1 =~ /\d{4}/) {
119                 $marc{date1} = $date1;
120                 $marc{fudgedate} = 1;
121                 print XF ">> using 260c as date1 at rec $count\n";
122             }
123         }
124     }
125
126     # item_form
127     if ( $marc{record_type} =~ /[gkroef]/ ) { # MAP, VIS
128         $marc{item_form} = substr($marc{tag008},29,1) if ($marc{tag008});
129     } else {
130         $marc{item_form} = substr($marc{tag008},23,1) if ($marc{tag008});
131     }
132
133     # isbns
134     my @isbns = $record->field('020') if $record->field('020');
135     push @isbns, $record->field('024') if $record->field('024');
136     for my $f ( @isbns ) {
137         push @{ $marc{isbns} }, $1 if ( defined $f->subfield('a') and
138                                         $f->subfield('a')=~/(\S+)/ );
139     }
140
141     # author
142     for my $rec_field (100, 110, 111) {
143         if ($record->field($rec_field)) {
144             $marc{author} = $record->field($rec_field)->subfield('a');
145             last;
146         }
147     }
148
149     # oclc
150     $marc{oclc} = [];
151     push @{ $marc{oclc} }, $record->field('001')->as_string()
152       if ($record->field('001') and $record->field('003') and
153           $record->field('003')->as_string() =~ /OCo{0,1}LC/);
154     for ($record->field('035')) {
155         my $oclc = $_->subfield('a');
156         push @{ $marc{oclc} }, $oclc
157           if (defined $oclc and $oclc =~ /\(OCoLC\)/ and $oclc =~/([0-9]+)/);
158     }
159
160     if ($record->field('999')) {
161         my $koha_bib_id = $record->field('999')->subfield('c');
162         $marc{koha_bib_id} = $koha_bib_id if defined $koha_bib_id and $koha_bib_id =~ /^\d+$/;
163     }
164
165     # "Accompanying material" and check for "copy" (300)
166     if ($record->field('300')) {
167         $marc{accomp} = $record->field('300')->subfield('e');
168         $marc{tag300a} = $record->field('300')->subfield('a');
169     }
170
171     # issn, lccn, title, desc, pages, pub, pubyear, edition
172     $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
173     $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
174     $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
175     $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
176     $marc{title} = $record->field('245')->subfield('a')
177       if $record->field('245');
178     $marc{title} .= ' ' . $record->field('245')->subfield('b')
179       if ($record->field('245') and 
180           $record->field('245')->subfield('b') and 
181           not $conf->{ignoresubtitle});
182     $marc{edition} = $record->field('250')->subfield('a')
183       if $record->field('250');
184     if ($record->field('260')) {
185         $marc{publisher} = $record->field('260')->subfield('b');
186         $marc{pubyear} = $record->field('260')->subfield('c');
187         $marc{pubyear} =
188           (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
189     }
190     return \%marc;
191 }
192
193
194
195 =head2 normalize_marc
196
197 Gently massages your data.
198
199 =cut
200
201 sub normalize_marc {
202     my ($marc) = @_;
203
204     $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
205     if ($marc->{title}) {
206         $marc->{title} = NFD($marc->{title});
207         $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
208         $marc->{title} = lc($marc->{title});
209         $marc->{title} =~ s/\W+$//go;
210     }
211     if ($marc->{author}) {
212         $marc->{author} = NFD($marc->{author});
213         $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
214         $marc->{author} = lc($marc->{author});
215         $marc->{author} =~ s/\W+$//go;
216         if ($marc->{author} =~ /^(\w+)/) {
217             $marc->{author} = $1;
218         }
219     }
220     if ($marc->{publisher}) {
221         $marc->{publisher} = NFD($marc->{publisher});
222         $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
223         $marc->{publisher} = lc($marc->{publisher});
224         $marc->{publisher} =~ s/\W+$//go;
225         if ($marc->{publisher} =~ /^(\w+)/) {
226             $marc->{publisher} = $1;
227         }
228     }
229     return $marc;
230 }
231
232
233
234 =head2 marc_isvalid
235
236 Checks MARC record to see if neccessary fingerprinting data is
237 available
238
239 =cut
240
241 sub marc_isvalid {
242     my ($marc) = @_;
243     return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
244                  $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
245     return 0;
246 }
247
248
249 =head2 score_marc
250
251 Assign a score to the record based on various criteria.
252
253 Score is constructed by pushing elements onto a list, via a dispatch
254 table.  This allows order of fingerprints in the output file to be
255 varied.
256
257 =cut
258
259 sub score_marc {
260     my ($marc, $record) = @_;
261     my @score = ();
262     my $json = '{';
263
264     #----------------------------------
265     # static criteria scoring
266     #----------------------------------
267     $marc->{misc_score} = 999;
268     $marc->{age_score}  = 999999999999;
269
270     # -1 if 008 has been padded, -2 if it doesn't exist
271     if ($marc->{tag008})
272       { $marc->{misc_score}-- if ($marc->{tag008} =~ /\|$/) }
273     else
274       { $marc->{misc_score} -= 2 }
275     # -1 if date has been pulled from 260
276     $marc->{misc_score}-- if $marc->{fudgedate};
277     # -1 if this is a copy record
278     $marc->{misc_score}--
279       if (defined $marc->{tag300a} and $marc->{tag300a} =~ /copy/i);
280
281     # subtract record id if we want older records to win
282     #$marc->{age_score} -= $marc->{id} unless ($conf->{newwins});
283     # handle arbitrary adjustments
284     $marc->{age_score} = 1;
285     if ($conf->{'arbitrarily-lose-above'}) {
286         $marc->{age_score} = 0
287           if ($marc->{id} >= $conf->{'arbitrarily-lose-above'});
288     }
289     if ($conf->{'arbitrarily-lose-below'}) {
290         $marc->{age_score} = 0
291           if ($marc->{id} <= $conf->{'arbitrarily-lose-below'});
292     }
293
294     #----------------------------------
295     # dynamic calculated scoring
296     #----------------------------------
297     my %scores_code = (
298       oclc    => sub { return $marc->{oclc}[0] ? 1 : 0 },
299       dlc     => sub {
300           if ($record->field('040') and $record->field('040')->subfield('a'))
301             { return scalar($record->subfield( '040', 'a')) =~ /dlc/io ? 1 : 0 }
302           else { return 0 }
303       },
304       num_650 => sub {
305           if ($record->field('650')) {
306               # can't say "scalar $record->field('650')"; MARC::Record
307               # behaves differently in list/scalar contexts
308               my @tags = $record->field('650');
309               return sprintf("%04d", scalar @tags)
310           } else { return '0000' }
311       },
312       num_tags=> sub { return sprintf( '%04d', scalar( $record->fields ) ) },
313       enc_lvl => sub {
314         my $enc = substr($record->leader, 17, 1) || 'u';
315         my %levels = ( ' ' => 9, 1 => 8, 2 => 7,  3  => 6,  4  => 5, 5 => 4,
316                        6   => 3, 7 => 2, 8 => 1, 'u' => 0, 'z' => 0 );
317         return $levels{$enc} || 0;
318     }
319                       );
320
321     #----------------------------------
322     # assemble and store scores
323     #----------------------------------
324     for ( @{ $conf->{dyn_scores} } ) {
325         push @score, $scores_code{$_}->($marc, $record);
326         $json .= $_ . ':' . $score[-1] . ',';
327     }
328     $json .= 'misc:' . $marc->{misc_score} . '}';
329
330     my $compact = join('', $marc->{age_score}, $marc->{misc_score}, @score);
331     $marc->{score} = "$compact\t$json";
332 }
333
334 =head2 dump_fingerprints
335
336 =cut
337
338 sub dump_fingerprints {
339     my ($marc) = @_;
340
341     if ($conf->{fingerprints}{baseline}) {
342         print OF join("\t", $marc->{score}, $marc->{id}, 'baseline',
343                       $marc->{item_form}, $marc->{date1}, $marc->{record_type},
344                       $marc->{bib_lvl}, $marc->{title}), "\n";
345     }
346
347     if ($conf->{fingerprints}{oclc} and scalar @{$marc->{oclc} }) {
348         for (@{$marc->{oclc} }) {
349             print OF join("\t", $marc->{score}, $marc->{id}, "oclc",
350                           $marc->{item_form}, $marc->{date1},
351                           $marc->{record_type}, $marc->{bib_lvl},
352                           $marc->{title}, $_, "\n");
353         }
354     }
355
356     if ($conf->{fingerprints}{koha_bib_id} and exists $marc->{koha_bib_id}) {
357         print OF join("\t", $marc->{score}, $marc->{id}, "z_koha_bib_id",
358                       $marc->{item_form}, $marc->{date1},
359                       $marc->{record_type},
360                       $marc->{bib_lvl}, $marc->{title},
361                       $marc->{koha_bib_id}), "\n";
362     }
363
364     if ($conf->{fingerprints}{isbn}) {
365         if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
366             foreach my $isbn ( @{ $marc->{isbns}} ) {
367                 print OF join("\t", $marc->{score}, $marc->{id}, "isbn",
368                               $marc->{item_form}, $marc->{date1},
369                               $marc->{record_type},
370                               $marc->{bib_lvl}, $marc->{title},
371                               $isbn, $marc->{pages}), "\n";
372             }
373         }
374     }
375
376     if ($conf->{fingerprints}{edition} and $marc->{edition}) {
377         print OF join("\t", $marc->{score}, $marc->{id}, "edition",
378                       $marc->{item_form}, $marc->{date1},
379                       $marc->{record_type}, $marc->{bib_lvl},
380                       $marc->{title}, $marc->{edition}), "\n";
381     }
382
383     if ($conf->{fingerprints}{issn} and $marc->{issn}) {
384         print OF join("\t", $marc->{score}, $marc->{id}, "issn",
385                       $marc->{item_form}, $marc->{date1},
386                       $marc->{record_type}, $marc->{bib_lvl},
387                       $marc->{title}, $marc->{issn}), "\n";
388     }
389
390     if ($conf->{fingerprints}{lccn} and $marc->{lccn}) {
391         print OF join("\t", $marc->{score}, $marc->{id}, "lccn",
392                       $marc->{item_form}, $marc->{date1},
393                       $marc->{record_type}, $marc->{bib_lvl},
394                       $marc->{title}, $marc->{lccn}) ,"\n";
395     }
396
397     if ($conf->{fingerprints}{accomp} and $marc->{accomp}) {
398         print OF join("\t", $marc->{score}, $marc->{id}, "accomp",
399                       $marc->{item_form}, $marc->{date1},
400                       $marc->{record_type}, $marc->{bib_lvl},
401                       $marc->{title}, $marc->{accomp}) ,"\n";
402     }
403
404     if ($conf->{fingerprints}{authpub} and $marc->{author} and
405         $marc->{publisher} and $marc->{pubyear} and $marc->{pages}) {
406         print OF join("\t", $marc->{score}, $marc->{id}, "authpub",
407                       $marc->{item_form}, $marc->{date1},
408                       $marc->{record_type}, $marc->{bib_lvl},
409                       $marc->{title}, $marc->{author},
410                       $marc->{publisher}, $marc->{pubyear},
411                       $marc->{pages}), "\n";
412     }
413 }
414
415
416
417 =head2 dump_exception
418
419 Write line of exception report
420
421 =cut
422
423 sub dump_exception {
424     my ($marc, $msg) = @_;
425     unless (defined $marc) {
426         print XF "Undefined record at line $count; likely bad XML\n";
427         return;
428     }
429
430     print XF "Record ", $marc->{id}, " excluded: ";
431     if (defined $msg) {
432         print XF "$msg\n";
433         return
434     }
435
436     print XF "missing item_form; " unless ($marc->{item_form});
437     unless (defined $marc->{date1})
438       { print XF "missing date1; " }
439     else
440       { print XF "invalid date1: '", $marc->{date1}, "'; "
441           unless ($marc->{date1} =~ /\d{4}/); }
442     print XF "missing record_type; " unless ($marc->{record_type});
443     print XF "missing bib_lvl; " unless ($marc->{bib_lvl});
444     print XF "missing title " unless ($marc->{title});
445     print XF "\n";
446 }
447
448
449 =head2 this_record_is_excluded
450
451 Returns 1 if the record B<is> and 0 if the record B<is not> excluded,
452 according to the subfield mapping (generated via the C<--excludelist>
453 option).
454
455 =cut
456
457 sub this_record_is_excluded {
458     my ($rec, $marc) = @_;
459     return 0 unless defined $conf->{excludelist};
460
461     for my $tag (keys %{ $conf->{excludelist}->{tags} }) {
462         for my $sub (keys %{$conf->{excludelist}->{tags}{$tag}}) {
463             my $f = $conf->{excludelist}->field($tag, $sub);
464
465             # if this record doesn't have the right tag/sub, it can't be
466             return 0 unless ($rec->field($tag) and $rec->field($tag)->subfield($sub));
467             # but it does, so if there are no filters to check...
468             unless ($conf->{excludelist}->filters($f))
469               { dump_exception($marc, "exclusion $tag$sub"); return 1 }
470
471             my $sub_contents = $rec->field($tag)->subfield($sub);
472             for my $filter (@{ $conf->{excludelist}->filters($f)}) {
473                 if ($sub_contents =~ /$filter/i) {
474                     # filter matches. no fp.
475                     dump_exception($marc, "exclusion $tag$sub '$filter'");
476                     return 1;
477                 }
478                 # no match, no exclude
479                 return 0;
480             }
481         }
482     }
483 }
484
485 =head2 initialize
486
487 Performs boring script initialization. Handles argument parsing,
488 mostly.
489
490 =cut
491
492 sub initialize {
493     my ($c) = @_;
494     my @missing = ();
495
496     # set mode on existing filehandles
497     binmode(STDIN, ':utf8');
498
499     my $rc = GetOptions( $c,
500                          'exception|x=s',
501                          'output|o=s',
502                          'prefix|p=s',
503                          'marctype|m=s',
504                          'subfield|s=s',
505                          'tag|t=s',
506                          'fingerprints=s',
507                          'scores=s',
508                          'arbitrarily-lose-above=i',
509                          'arbitrarily-lose-below=i',
510                          'newwins',
511                          'excludelist=s',
512                          'ignoresubtitle|i',
513                          'quiet|q',
514                          'help|h',
515                        );
516     show_help() unless $rc;
517     show_help() if ($c->{help});
518
519     # check fingerprints list for validity
520     if ($c->{fingerprints}) {
521         my %fps = ();
522         my %valid_fps = ( oclc => 1, isbn => 1, issn => 1, lccn => 1,
523                           edition => 1, accomp => 1, authpub => 1,
524                           baseline => 1, crap => 1,
525                           koha_bib_id => 1,
526                         );
527         for (split /,/, $c->{fingerprints}) {
528             die "Invalid fingerprint '$_'\n" unless $valid_fps{$_};
529             $fps{$_} = 1;
530         }
531         $c->{fingerprints} = \%fps
532     } else {
533         $c->{fingerprints} = {oclc => 1, isbn => 1, edition => 1, issn => 1,
534                               lccn => 1, accomp => 1, authpub => 1};
535     }
536
537     # check scores list for validity
538     if ($c->{scores}) {
539         my %scores = ();
540         my %valid_scores = ( oclc => 1, dlc => 1, num_650 => 1,
541                              num_tags => 1, enc_lvl => 1,
542                            );
543         for (split /,/, $c->{scores}) {
544             die "Invalid score mode '$_'\n" unless $valid_scores{$_};
545             $scores{$_} = 1;
546         }
547         $c->{dyn_scores} = [split /,/, $c->{scores}];
548         $c->{scores} = \%scores;
549     } else {
550         $c->{scores} = {oclc => 1, dlc => 1, num_650 => 1,
551                         num_tags => 1, enc_lvl => 1};
552         $c->{dyn_scores} = [ qw/oclc dlc num_650 num_tags enc_lvl/ ];
553     }
554
555     # set defaults
556     $c->{tag} = 903 unless defined $c->{tag};
557     $c->{subfield} = 'a' unless defined $c->{subfield};
558     $c->{marctype} = 'XML' unless defined $c->{marctype};
559     if ($c->{prefix}) {
560         $c->{output} = join('.',$c->{prefix},'fp');
561         $c->{exception} = join('.',$c->{prefix},'fp','ex');
562     }
563
564     # get SFM object if excludelist was specified
565     if ($c->{excludelist}) {
566         $c->{excludelist} =
567           Equinox::Migration::SubfieldMapper->new( file => $c->{excludelist} );
568     }
569
570     my @keys = keys %{$c};
571     show_help() unless (@ARGV and @keys);
572     for my $key ('tag', 'subfield', 'output', 'exception')
573       { push @missing, $key unless $c->{$key} }
574     if (@missing) {
575         print "Required option: ", join(', ', @missing), " missing!\n";
576         show_help();
577     }
578 }
579
580
581 =head2 progress_ticker
582
583 =cut
584
585 sub progress_ticker {
586     return if $conf->{quiet};
587     printf("\r> %d recs seen; %d processed", $count, $scount);
588     printf(" (%d/s)", ($count / (time - $start + 1)))
589       if ($count % 500 == 0);
590 }
591
592 =head2 show_help
593
594 Display usage message when things go wrong
595
596 =cut
597
598 sub show_help {
599 print <<HELP;
600 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
601 Req'd Arguments
602   --output=<FILE>      -o  Output filename
603   --exceptions=<FILE>  -x  Exception report filename
604        or
605   --prefix=<PREFIX>>   -p  Shared prefix for output/exception files. Will
606                            produce PREFIX.fp and PREFIX.fp.ex
607 Options
608   --tag=N           -t  Which tag to use (default 903)
609   --subfield=X      -s  Which subfield to use (default 'a')
610   --quiet           -q  Don't write status messages to STDOUT
611   --ignoresubtitle  -i  Ignore 245\$b and construct the title from 245\$a alone.
612
613   --fingerprints=LIST  Fingerprints to generate, comma separated
614                        Default: oclc,isbn,edition,issn,lccn,accomp,authpub
615                        Others:  baseline,koha_bib_id
616   --excludelist=FILE   Name of fingerprints exclusions file
617
618   --scores=LIST  Scores to calculate, comma separated
619                  Default: oclc,dlc,num_650,num_tags,enc_level
620   --newwins      New record IDs score higher (default is old wins)
621   --arbitrarily-lose-above
622   --arbitrarily-lose-below
623   --arbitrarily-decrease-score-by
624       Modify fingerprint scoring of records whose EG id is above or below a
625       given value, inclusive (so 5 is <= 5 or >= 5) such that they lose.
626
627   --marctype=TYPE Defaults to 'XML'
628 HELP
629 exit 1;
630 }