8d14ae3744d6f9bb3c9d941a4c0c81c57d044bea
[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     # reset misc score
69     $conf->{misc_score} = 999;
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     $my_008 = $my_008->as_string() if ($my_008);
81     if (defined $my_008) {
82         unless (length $my_008 == 40) {
83             $my_008 = $my_008 . (' ' x (40 - length($my_008)));
84             print XF ">> Short 008 padded to ",length($my_008)," at rec $count\n";
85         }
86         $marc{date1} = substr($my_008,7,4) if ($my_008);
87         $marc{date2} = substr($my_008,11,4) if ($my_008); # UNUSED
88     }
89     unless ($marc{date1} and $marc{date1} =~ /\d{4}/) {
90         my $my_260 = $record->field('260');
91         my $date1 = $my_260->subfield('c') if $my_260;
92         if (defined $date1 and $date1 =~ /\d{4}/) {
93             $marc{date1} = $date1;
94             print XF ">> using 260c as date1 at rec $count\n";
95         }
96     }
97
98     # item_form
99     if ( $marc{record_type} =~ /[gkroef]/ ) { # MAP, VIS
100         $marc{item_form} = substr($my_008,29,1) if ($my_008);
101     } else {
102         $marc{item_form} = substr($my_008,23,1) if ($my_008);
103     }
104
105     # isbns
106     my @isbns = $record->field('020') if $record->field('020');
107     push @isbns, $record->field('024') if $record->field('024');
108     for my $f ( @isbns ) {
109         push @{ $marc{isbns} }, $1 if ( defined $f->subfield('a') and
110                                         $f->subfield('a')=~/(\S+)/ );
111     }
112
113     # author
114     for my $rec_field (100, 110, 111) {
115         if ($record->field($rec_field)) {
116             $marc{author} = $record->field($rec_field)->subfield('a');
117             last;
118         }
119     }
120
121     # oclc
122     $marc{oclc} = [];
123     push @{ $marc{oclc} }, $record->field('001')->as_string()
124       if ($record->field('001') and $record->field('003') and
125           $record->field('003')->as_string() =~ /OCo{0,1}LC/);
126     for ($record->field('035')) {
127         my $oclc = $_->subfield('a');
128         push @{ $marc{oclc} }, $oclc
129           if (defined $oclc and $oclc =~ /\(OCoLC\)/ and $oclc =~/([0-9]+)/);
130     }
131
132     # "Accompanying material" (300e)
133     $marc{accomp} = $record->field('300')->subfield('e')
134       if $record->field('300');
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     my %scores_code = (
226       oclc    => sub { return $marc->{oclc}[0] ? 1 : 0 },
227       dlc     => sub {
228           if ($record->field('040') and $record->field('040')->subfield('a'))
229             { return scalar($record->subfield( '040', 'a')) =~ /dlc/io ? 1 : 0 }
230           else { return 0 }
231       },
232       num_650 => sub {
233           if ($record->field('650')) {
234               # can't say "scalar $record->field('650')"; MARC::Record
235               # behaves differently in list/scalar contexts
236               my @tags = $record->field('650');
237               return sprintf("%04d", scalar @tags)
238           } else { return '0000' }
239       },
240       num_tags=> sub { return sprintf( '%04d', scalar( $record->fields ) ) },
241       enc_lvl => sub {
242         my $enc = substr($record->leader, 17, 1) || 'u';
243         my %levels = ( ' ' => 9, 1 => 8, 2 => 7,  3  => 6,  4  => 5, 5 => 4,
244                        6   => 3, 7 => 2, 8 => 1, 'u' => 0, 'z' => 0 );
245         return $levels{$enc} || 0;
246       }
247       );
248
249     for ( @{ $conf->{dyn_scores} } ) {
250         push @score, $scores_code{$_}->($marc, $record);
251         $json .= $_ . ':' . $score[-1] . ',';
252     }
253
254     # add misc score
255     $json .= 'misc:' . $conf->{misc_score};
256     $json .= '}';
257
258     my $compact = join('', @score, $conf->{misc_score});
259     $marc->{score} = "$compact\t$json";
260 }
261
262 =head2 dump_fingerprints
263
264 =cut
265
266 sub dump_fingerprints {
267     my ($marc) = @_;
268
269     if ($conf->{fingerprints}{baseline}) {
270         print OF join("\t", $marc->{score}, $marc->{id}, 'baseline',
271                       $marc->{item_form}, $marc->{date1}, $marc->{record_type},
272                       $marc->{bib_lvl}, $marc->{title}), "\n";
273     }
274
275     if ($conf->{fingerprints}{oclc} and scalar @{$marc->{oclc} }) {
276         for (@{$marc->{oclc} }) {
277             print OF join("\t", $marc->{score}, $marc->{id}, "oclc",
278                           $marc->{item_form}, $marc->{date1},
279                           $marc->{record_type}, $marc->{bib_lvl},
280                           $marc->{title}, $_, "\n");
281         }
282     }
283
284     if ($conf->{fingerprints}{isbn}) {
285         if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
286             foreach my $isbn ( @{ $marc->{isbns}} ) {
287                 print OF join("\t", $marc->{score}, $marc->{id}, "isbn",
288                               $marc->{item_form}, $marc->{date1},
289                               $marc->{record_type},
290                               $marc->{bib_lvl}, $marc->{title},
291                               $isbn, $marc->{pages}), "\n";
292             }
293         }
294     }
295
296     if ($conf->{fingerprints}{edition} and $marc->{edition}) {
297         print OF join("\t", $marc->{score}, $marc->{id}, "edition",
298                       $marc->{item_form}, $marc->{date1},
299                       $marc->{record_type}, $marc->{bib_lvl},
300                       $marc->{title}, $marc->{edition}), "\n";
301     }
302
303     if ($conf->{fingerprints}{issn} and $marc->{issn}) {
304         print OF join("\t", $marc->{score}, $marc->{id}, "issn",
305                       $marc->{item_form}, $marc->{date1},
306                       $marc->{record_type}, $marc->{bib_lvl},
307                       $marc->{title}, $marc->{issn}), "\n";
308     }
309
310     if ($conf->{fingerprints}{lccn} and $marc->{lccn}) {
311         print OF join("\t", $marc->{score}, $marc->{id}, "lccn",
312                       $marc->{item_form}, $marc->{date1},
313                       $marc->{record_type}, $marc->{bib_lvl},
314                       $marc->{title}, $marc->{lccn}) ,"\n";
315     }
316
317     if ($conf->{fingerprints}{accomp} and $marc->{accomp}) {
318         print OF join("\t", $marc->{score}, $marc->{id}, "accomp",
319                       $marc->{item_form}, $marc->{date1},
320                       $marc->{record_type}, $marc->{bib_lvl},
321                       $marc->{title}, $marc->{accomp}) ,"\n";
322     }
323
324     if ($conf->{fingerprints}{authpub} and $marc->{author} and
325         $marc->{publisher} and $marc->{pubyear} and $marc->{pages}) {
326         print OF join("\t", $marc->{score}, $marc->{id}, "authpub",
327                       $marc->{item_form}, $marc->{date1},
328                       $marc->{record_type}, $marc->{bib_lvl},
329                       $marc->{title}, $marc->{author},
330                       $marc->{publisher}, $marc->{pubyear},
331                       $marc->{pages}), "\n";
332     }
333 }
334
335
336
337 =head2 dump_exception
338
339 Write line of exception report
340
341 =cut
342
343 sub dump_exception {
344     my ($marc) = @_;
345     unless (defined $marc) {
346         print XF "Undefined record at line $count; likely bad XML\n";
347         return;
348     }
349     print XF "Record ", $marc->{id}, " did not make the cut: ";
350     print XF "Missing item_form. " unless ($marc->{item_form});
351     unless (defined $marc->{date1})
352       { print XF "Missing date1. " }
353     else
354       { print XF "Invalid date1: ", $marc->{date1}, " "
355           unless ($marc->{date1} =~ /\d{4}/); }
356     print XF "Missing record_type. " unless ($marc->{record_type});
357     print XF "Missing bib_lvl. " unless ($marc->{bib_lvl});
358     print XF "Missing title. " unless ($marc->{title});
359     print XF "\n";
360 }
361
362
363 =head2 initialize
364
365 Performs boring script initialization. Handles argument parsing,
366 mostly.
367
368 =cut
369
370 sub initialize {
371     my ($c) = @_;
372     my @missing = ();
373
374     # set mode on existing filehandles
375     binmode(STDIN, ':utf8');
376
377     my $rc = GetOptions( $c,
378                          'exception|x=s',
379                          'output|o=s',
380                          'prefix|p=s',
381                          'marctype|m=s',
382                          'subfield|s=s',
383                          'tag|t=s',
384                          'fingerprints=s',
385                          'scores=s',
386                          'quiet|q',
387                          'help|h',
388                        );
389     show_help() unless $rc;
390     show_help() if ($c->{help});
391
392     # check fingerprints list for validity
393     if ($c->{fingerprints}) {
394         my %fps = ();
395         my %valid_fps = ( oclc => 1, isbn => 1, issn => 1, lccn => 1,
396                           edition => 1, accomp => 1, authpub => 1,
397                           baseline => 1, crap => 1,
398                         );
399         for (split /,/, $c->{fingerprints}) {
400             die "Invalid fingerprint '$_'\n" unless $valid_fps{$_};
401             $fps{$_} = 1;
402         }
403         $c->{fingerprints} = \%fps
404     } else {
405         $c->{fingerprints} = {oclc => 1, isbn => 1, edition => 1, issn => 1,
406                               lccn => 1, accomp => 1, authpub => 1};
407     }
408
409     # check scores list for validity
410     if ($c->{scores}) {
411         my %scores = ();
412         my %valid_scores = ( oclc => 1, dlc => 1, num_650 => 1,
413                              num_tags => 1, enc_lvl => 1,
414                            );
415         for (split /,/, $c->{scores}) {
416             die "Invalid score mode '$_'\n" unless $valid_scores{$_};
417             $scores{$_} = 1;
418         }
419         $c->{dyn_scores} = [split /,/, $c->{scores}];
420         $c->{scores} = \%scores;
421     } else {
422         $c->{scores} = {oclc => 1, dlc => 1, num_650 => 1,
423                         num_tags => 1, enc_lvl => 1};
424         $c->{dyn_scores} = [ qw/oclc dlc num_650 num_tags enc_lvl/ ];
425     }
426
427     # set defaults
428     $c->{tag} = 903 unless defined $c->{tag};
429     $c->{subfield} = 'a' unless defined $c->{subfield};
430     $c->{marctype} = 'XML' unless defined $c->{marctype};
431     if ($c->{prefix}) {
432         $c->{output} = join('.',$c->{prefix},'fp');
433         $c->{exception} = join('.',$c->{prefix},'fp','ex');
434     }
435
436     my @keys = keys %{$c};
437     show_help() unless (@ARGV and @keys);
438     for my $key ('tag', 'subfield', 'output', 'exception')
439       { push @missing, $key unless $c->{$key} }
440     if (@missing) {
441         print "Required option: ", join(', ', @missing), " missing!\n";
442         show_help();
443     }
444 }
445
446
447 =head2 progress_ticker
448
449 =cut
450
451 sub progress_ticker {
452     return if $conf->{quiet};
453     printf("\r> %d recs seen; %d processed", $count, $scount);
454     printf(" (%d/s)", ($count / (time - $start + 1)))
455       if ($count % 500 == 0);
456 }
457
458 =head2 show_help
459
460 Display usage message when things go wrong
461
462 =cut
463
464 sub show_help {
465 print <<HELP;
466 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
467 Req'd Arguments
468   --output=<FILE>      -o  Output filename
469   --exceptions=<FILE>  -x  Exception report filename
470        or
471   --prefix=<PREFIX>>   -p  Shared prefix for output/exception files. Will
472                            produce PREFIX.fp and PREFIX.fp.ex
473 Options
474   --tag=N       -t  Which tag to use (default 903)
475   --subfield=X  -s  Which subfield to use (default 'a')
476   --quiet       -q  Don't write status messages to STDOUT
477
478   --fingerprints=LIST  Fingerprints to generate, comma separated
479                        Default: oclc,isbn,edition,issn,lccn,accomp,authpub
480                        Others:  baseline
481
482   --scores=LIST  Scores to calculate, comma separated
483                  Default: oclc,dlc,num_650,num_tags,enc_level
484
485   --marctype=TYPE Defaults to 'XML'
486 HELP
487 exit 1;
488 }