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