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