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