adding compact score
[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     $my_008 = $my_008->as_string() if ($my_008);
78     if (defined $my_008) {
79         unless (length $my_008 == 40) {
80             $my_008 = $my_008 . (' ' x (40 - length($my_008)));
81             print XF ">> Short 008 padded to ",length($my_008)," at rec $count\n";
82         }
83         $marc{date1} = substr($my_008,7,4) if ($my_008);
84         $marc{date2} = substr($my_008,11,4) if ($my_008); # 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             print XF ">> using 260c as date1 at rec $count\n";
92         }
93     }
94
95     # item_form
96     if ( $marc{record_type} =~ /[gkroef]/ ) { # MAP, VIS
97         $marc{item_form} = substr($my_008,29,1) if ($my_008);
98     } else {
99         $marc{item_form} = substr($my_008,23,1) if ($my_008);
100     }
101
102     # isbns
103     my @isbns = $record->field('020') if $record->field('020');
104     push @isbns, $record->field('024') if $record->field('024');
105     for my $f ( @isbns ) {
106         push @{ $marc{isbns} }, $1 if ( defined $f->subfield('a') and
107                                         $f->subfield('a')=~/(\S+)/ );
108     }
109
110     # author
111     for my $rec_field (100, 110, 111) {
112         if ($record->field($rec_field)) {
113             $marc{author} = $record->field($rec_field)->subfield('a');
114             last;
115         }
116     }
117
118     # oclc
119     $marc{oclc} = [];
120     push @{ $marc{oclc} }, $record->field('001')->as_string()
121       if ($record->field('001') and $record->field('003') and
122           $record->field('003')->as_string() =~ /OCo{0,1}LC/);
123     for ($record->field('035')) {
124         my $oclc = $_->subfield('a');
125         push @{ $marc{oclc} }, $oclc
126           if (defined $oclc and $oclc =~ /\(OCoLC\)/ and $oclc =~/([0-9]+)/);
127     }
128
129     # "Accompanying material" (300e)
130     $marc{accomp} = $record->field('300')->subfield('e')
131       if $record->field('300');
132
133     # issn, lccn, title, desc, pages, pub, pubyear, edition
134     $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
135     $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
136     $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
137     $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
138     $marc{title} = $record->field('245')->subfield('a')
139       if $record->field('245');
140     $marc{edition} = $record->field('250')->subfield('a')
141       if $record->field('250');
142     if ($record->field('260')) {
143         $marc{publisher} = $record->field('260')->subfield('b');
144         $marc{pubyear} = $record->field('260')->subfield('c');
145         $marc{pubyear} =
146           (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
147     }
148     return \%marc;
149 }
150
151
152
153 =head2 normalize_marc
154
155 Gently massages your data.
156
157 =cut
158
159 sub normalize_marc {
160     my ($marc) = @_;
161
162     $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
163     if ($marc->{title}) {
164         $marc->{title} = NFD($marc->{title});
165         $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
166         $marc->{title} = lc($marc->{title});
167         $marc->{title} =~ s/\W+$//go;
168     }
169     if ($marc->{author}) {
170         $marc->{author} = NFD($marc->{author});
171         $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
172         $marc->{author} = lc($marc->{author});
173         $marc->{author} =~ s/\W+$//go;
174         if ($marc->{author} =~ /^(\w+)/) {
175             $marc->{author} = $1;
176         }
177     }
178     if ($marc->{publisher}) {
179         $marc->{publisher} = NFD($marc->{publisher});
180         $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
181         $marc->{publisher} = lc($marc->{publisher});
182         $marc->{publisher} =~ s/\W+$//go;
183         if ($marc->{publisher} =~ /^(\w+)/) {
184             $marc->{publisher} = $1;
185         }
186     }
187     return $marc;
188 }
189
190
191
192 =head2 marc_isvalid
193
194 Checks MARC record to see if neccessary fingerprinting data is
195 available
196
197 =cut
198
199 sub marc_isvalid {
200     my ($marc) = @_;
201     return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
202                  $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
203     return 0;
204 }
205
206
207 =head2 score_marc
208
209 Assign a score to the record based on various criteria.
210
211 Score is constructed by pushing elements onto a list. At the end of
212 the routine, the list is flattened into a string via join();
213
214 =cut
215
216 sub score_marc {
217     my ($marc, $record) = @_;
218     my @score = ();
219     my $chunk;
220
221     # Is this an OCLC record?
222     if ($conf->{scores}{oclc})
223       { push @score, ( defined $marc->{oclc}[0] ? 1 : 0 ) }
224
225     # does 040a contain "dlc"?
226     if ($conf->{scores}{dlc}) {
227         if ($record->field('040') and $record->field('040')->subfield('a')) {
228             $chunk = $record->field('040')->subfield('a');
229             push @score, ( $chunk =~ /dlc/i ? 1 : 0 );
230         } else {
231             push @score, 0;
232         }
233     }
234
235     # number of 650 datafields
236     # zero-padded to 4 digits with printf
237     if ($conf->{scores}{num_650}) {
238         if ($record->field('650')) {
239             my @tags = $record->field('650');
240             push @score, ( sprintf("%04d", scalar @tags) );
241         } else {
242             push @score, '0000';
243         }
244     }
245
246     # number of tags in total
247     # zero-padded to 4 digits with printf
248     if ($conf->{scores}{num_tags}) {
249         my @tags = $record->fields;
250         push @score, ( sprintf("%04d", scalar @tags) );
251     }
252
253     # encoding level
254     if ($conf->{scores}{enc_lvl}) {
255         my $enc = substr($record->leader, 17, 1);
256         my %levels = ( ' ' => 9, 1 => 8, 2 => 7,  3  => 6,  4  => 5, 5 => 4,
257                        6   => 3, 7 => 2, 8 => 1, 'u' => 0, 'z' => 0 );
258         if (defined $enc and $levels{$enc})
259           { push @score, $levels{$enc} }
260         else
261           { push @score, 0 }
262     }
263
264     # put score in marc hash
265     my $json = join('', '{oclc:', $score[0], ',dlc:', $score[1],
266                     ',num_650:', $score[2], ',num_tags:', $score[3],
267                     ',enc_lvl:', $score[4], '}');
268     my $compact = join('', @score);
269     $marc->{score} = "$compact\t$json";
270 }
271
272 =head2 dump_fingerprints
273
274 =cut
275
276 sub dump_fingerprints {
277     my ($marc) = @_;
278
279     if ($conf->{fingerprints}{baseline}) {
280         print OF join("\t", $marc->{score}, $marc->{id}, 'baseline',
281                       $marc->{item_form}, $marc->{date1}, $marc->{record_type},
282                       $marc->{bib_lvl}, $marc->{title}), "\n";
283     }
284
285     if ($conf->{fingerprints}{oclc} and scalar @{$marc->{oclc} }) {
286         for (@{$marc->{oclc} }) {
287             print OF join("\t", $marc->{score}, $marc->{id}, "oclc",
288                           $marc->{item_form}, $marc->{date1},
289                           $marc->{record_type}, $marc->{bib_lvl},
290                           $marc->{title}, $_, "\n");
291         }
292     }
293
294     if ($conf->{fingerprints}{isbn}) {
295         if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
296             foreach my $isbn ( @{ $marc->{isbns}} ) {
297                 print OF join("\t", $marc->{score}, $marc->{id}, "isbn",
298                               $marc->{item_form}, $marc->{date1},
299                               $marc->{record_type},
300                               $marc->{bib_lvl}, $marc->{title},
301                               $isbn, $marc->{pages}), "\n";
302             }
303         }
304     }
305
306     if ($conf->{fingerprints}{edition} and $marc->{edition}) {
307         print OF join("\t", $marc->{score}, $marc->{id}, "edition",
308                       $marc->{item_form}, $marc->{date1},
309                       $marc->{record_type}, $marc->{bib_lvl},
310                       $marc->{title}, $marc->{edition}), "\n";
311     }
312
313     if ($conf->{fingerprints}{issn} and $marc->{issn}) {
314         print OF join("\t", $marc->{score}, $marc->{id}, "issn",
315                       $marc->{item_form}, $marc->{date1},
316                       $marc->{record_type}, $marc->{bib_lvl},
317                       $marc->{title}, $marc->{issn}), "\n";
318     }
319
320     if ($conf->{fingerprints}{lccn} and $marc->{lccn}) {
321         print OF join("\t", $marc->{score}, $marc->{id}, "lccn",
322                       $marc->{item_form}, $marc->{date1},
323                       $marc->{record_type}, $marc->{bib_lvl},
324                       $marc->{title}, $marc->{lccn}) ,"\n";
325     }
326
327     if ($conf->{fingerprints}{accomp} and $marc->{accomp}) {
328         print OF join("\t", $marc->{score}, $marc->{id}, "accomp",
329                       $marc->{item_form}, $marc->{date1},
330                       $marc->{record_type}, $marc->{bib_lvl},
331                       $marc->{title}, $marc->{accomp}) ,"\n";
332     }
333
334     if ($conf->{fingerprints}{authpub} and $marc->{author} and
335         $marc->{publisher} and $marc->{pubyear} and $marc->{pages}) {
336         print OF join("\t", $marc->{score}, $marc->{id}, "authpub",
337                       $marc->{item_form}, $marc->{date1},
338                       $marc->{record_type}, $marc->{bib_lvl},
339                       $marc->{title}, $marc->{author},
340                       $marc->{publisher}, $marc->{pubyear},
341                       $marc->{pages}), "\n";
342     }
343 }
344
345
346
347 =head2 dump_exception
348
349 Write line of exception report
350
351 =cut
352
353 sub dump_exception {
354     my ($marc) = @_;
355     unless (defined $marc) {
356         print XF "Undefined record at line $count; likely bad XML\n";
357         return;
358     }
359     print XF "Record ", $marc->{id}, " did not make the cut: ";
360     print XF "Missing item_form. " unless ($marc->{item_form});
361     unless (defined $marc->{date1})
362       { print XF "Missing date1. " }
363     else
364       { print XF "Invalid date1: ", $marc->{date1}, " "
365           unless ($marc->{date1} =~ /\d{4}/); }
366     print XF "Missing record_type. " unless ($marc->{record_type});
367     print XF "Missing bib_lvl. " unless ($marc->{bib_lvl});
368     print XF "Missing title. " unless ($marc->{title});
369     print XF "\n";
370 }
371
372
373 =head2 initialize
374
375 Performs boring script initialization. Handles argument parsing,
376 mostly.
377
378 =cut
379
380 sub initialize {
381     my ($c) = @_;
382     my @missing = ();
383
384     # set mode on existing filehandles
385     binmode(STDIN, ':utf8');
386
387     my $rc = GetOptions( $c,
388                          'incoming',
389                          'incumbent',
390                          'exception|x=s',
391                          'marctype|m=s',
392                          'output|o=s',
393                          'runtype|r=s',
394                          'subfield|s=s',
395                          'tag|t=s',
396                          'fingerprints=s',
397                          'scores=s',
398                          'quiet|q',
399                          'help|h',
400                        );
401     show_help() unless $rc;
402     show_help() if ($c->{help});
403
404     # check fingerprints list for validity
405     if ($c->{fingerprints}) {
406         my %fps = ();
407         my %valid_fps = ( oclc => 1, isbn => 1, issn => 1, lccn => 1,
408                           edition => 1, accomp => 1, authpub => 1,
409                           baseline => 1, crap => 1,
410                         );
411         for (split /,/, $c->{fingerprints}) {
412             die "Invalid fingerprint '$_'\n" unless $valid_fps{$_};
413             $fps{$_} = 1;
414         }
415         $c->{fingerprints} = \%fps
416     } else {
417         $c->{fingerprints} = {oclc => 1, isbn => 1, edition => 1, issn => 1,
418                               lccn => 1, accomp => 1, authpub => 1};
419     }
420     # check scores list for validity
421     if ($c->{scores}) {
422         my %scores = ();
423         my %valid_scores = ( oclc => 1, dlc => 1, num_650 => 1,
424                              num_tags => 1, enc_lvl => 1,
425                            );
426         for (split /,/, $c->{scores}) {
427             die "Invalid score mode '$_'\n" unless $valid_scores{$_};
428             $scores{$_} = 1;
429         }
430         $c->{scores} = \%scores;
431     } else {
432         $c->{scores} = {oclc => 1, dlc => 1, num_650 => 1,
433                         num_tags => 1, enc_lvl => 1};
434     }
435
436     # set defaults if told to do so
437     if ($c->{incoming}) {
438         $c->{tag} = 903 unless defined $c->{tag};
439         $c->{subfield} = 'a' unless defined $c->{subfield};
440         $c->{marctype} = 'XML' unless defined $c->{marctype};
441         $c->{output} = 'incoming.fp' unless defined $c->{output};
442         $c->{exception} = 'incoming.ex' unless defined $c->{exception};
443     } elsif ($c->{incumbent}) {
444         $c->{tag} = 901 unless defined $c->{tag};
445         $c->{subfield} = 'c' unless defined $c->{subfield};
446         $c->{marctype} = 'XML' unless defined $c->{marctype};
447         $c->{output} = 'incumbent.fp' unless defined $c->{output};
448         $c->{exception} = 'incumbent.ex' unless defined $c->{exception};
449     }
450
451     my @keys = keys %{$c};
452     show_help() unless (@ARGV and @keys);
453     for my $key ('tag', 'subfield', 'output', 'exception')
454       { push @missing, $key unless $c->{$key} }
455     if (@missing) {
456         print "Required option: ", join(', ', @missing), " missing!\n";
457         show_help();
458     }
459 }
460
461
462 =head2 progress_ticker
463
464 =cut
465
466 sub progress_ticker {
467     return if $conf->{quiet};
468     printf("\r> %d recs seen; %d processed", $count, $scount);
469     printf(" (%d/s)", ($count / (time - $start + 1)))
470       if ($count % 500 == 0);
471 }
472
473 =head2 show_help
474
475 Display usage message when things go wrong
476
477 =cut
478
479 sub show_help {
480 print <<HELP;
481 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
482 Req'd Arguments
483   --tag=N                  -t  Which tag to use
484   --subfield=X             -s  Which subfield to use
485   --output=<file>          -o  Output filename
486   --exceptions=<file>      -x  Exception report filename
487 Options
488   --incoming   '-t 903 -s a -o incoming.fp -x incoming.ex'
489   --incumbent  '-t 901 -s c -o incumbent.fp -x incumbent.ex'
490
491   --fingerprints=LIST  Fingerprints to generate, comma separated
492                        Default: oclc,isbn,edition,issn,lccn,accomp,authpub
493                        Others:  baseline
494   --scores=LIST  Scores to calculate, comma separated
495                  Default: oclc,dlc,num_650,num_tags,enc_level
496   --quiet    -q  Don't write status messages to STDOUT
497 HELP
498 exit 1;
499 }