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