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