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