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