1fa1f73327ea54e893f9103a58e15660870e26fd
[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     #open my $records, '<:utf8', $file; # This hack dosn't play nice with the use MARC::File::XML ( BinaryEncoding => 'utf-8' ); hack
24     my $batch = undef; my $record = undef;
25
26     #$batch = MARC::Batch->new('XML', $records); # The other part of the hack
27     $batch = MARC::Batch->new($conf->{marctype}, $file);
28     $batch->strict_off();
29     $batch->warnings_off();
30
31     while ( $record = $batch->next ) {
32         $count++; progress_ticker();
33         my $marc = undef;
34         unless ( defined $record )
35           { dump_exception($marc); next; }
36
37         my $id = $record->field($conf->{tag});
38         unless ($id) {
39             print XF "ERROR: Record $count in $file is missing a ",
40               $conf->{tag}, " field.\n", $record->as_formatted(), "\n=====\n";
41             next;
42         }
43
44         $marc = populate_marc($record, $id);
45         $marc = normalize_marc($marc);
46         unless (marc_isvalid($marc))
47           { dump_exception($marc); next; }
48         dump_fingerprints($marc);
49         $scount++; progress_ticker();
50     }
51 }
52
53 print "\nSuccessfully processed:\t$count\n" unless $conf->{quiet};
54
55 =head2 populate_marc
56
57 Constructs a hash containing the relevant MARC data for a record and
58 returns a reference to it.
59
60 =cut
61
62 sub populate_marc {
63     my ($record, $id) = @_;
64     my %marc = (); $marc{isbns} = [];
65
66     # id, stringified
67     $marc{id} = $id->as_string($conf->{subfield});
68
69     # record_type, bib_lvl
70     $marc{record_type} = substr($record->leader, 6, 1);
71     $marc{bib_lvl}     = substr($record->leader, 7, 1);
72
73     # date1, date2
74     my $my_008 = $record->field('008');
75     $my_008 = $my_008->as_string() if ($my_008);
76     if (defined $my_008) {
77         unless (length $my_008 == 40) {
78             $my_008 = $my_008 . (' ' x (40 - length($my_008)));
79             print XF ">> Short 008 padded to ",length($my_008)," at rec $count\n";
80         }
81         $marc{date1} = substr($my_008,7,4) if ($my_008);
82         $marc{date2} = substr($my_008,11,4) if ($my_008); # UNUSED
83     }
84     unless ($marc{date1} and $marc{date1} =~ /\d{4}/) {
85         my $my_260 = $record->field('260');
86         my $date1 = $my_260->subfield('c') if $my_260;
87         if (defined $date1 and $date1 =~ /\d{4}/) {
88             $marc{date1} = $date1;
89             print XF ">> using 260c as date1 at rec $count\n";
90         }
91     }
92
93     # item_form
94     if ( $marc{record_type} =~ /[gkroef]/ ) { # MAP, VIS
95         $marc{item_form} = substr($my_008,29,1) if ($my_008);
96     } else {
97         $marc{item_form} = substr($my_008,23,1) if ($my_008);
98     }
99
100     # isbns
101     my @isbns = $record->field('020') if $record->field('020');
102     push @isbns, $record->field('024') if $record->field('024');
103     for my $f ( @isbns ) {
104         push @{ $marc{isbns} }, $1 if ( defined $f->subfield('a') and
105                                         $f->subfield('a')=~/(\S+)/ );
106     }
107
108     # author
109     for my $rec_field (100, 110, 111) {
110         if ($record->field($rec_field)) {
111             $marc{author} = $record->field($rec_field)->subfield('a');
112             last;
113         }
114     }
115
116     # oclc
117     $marc{oclc} = [];
118     push @{ $marc{oclc} }, $record->field('001')->as_string()
119       if ($record->field('001') and $record->field('003') and
120           $record->field('003')->as_string() =~ /OCo{0,1}LC/);
121     for ($record->field('035')) {
122         my $oclc = $_->subfield('a');
123         push @{ $marc{oclc} }, $oclc
124           if (defined $oclc and $oclc =~ /\(OCoLC\)/ and $oclc =~/([0-9]+)/);
125     }
126
127     # "Accompanying material" (300e)
128     $marc{accomp} = $record->field('300')->subfield('e')
129       if $record->field('300');
130
131     # issn, lccn, title, desc, pages, pub, pubyear, edition
132     $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
133     $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
134     $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
135     $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
136     $marc{title} = $record->field('245')->subfield('a')
137       if $record->field('245');
138     $marc{edition} = $record->field('250')->subfield('a')
139       if $record->field('250');
140     if ($record->field('260')) {
141         $marc{publisher} = $record->field('260')->subfield('b');
142         $marc{pubyear} = $record->field('260')->subfield('c');
143         $marc{pubyear} =
144           (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
145     }
146     return \%marc;
147 }
148
149
150
151 =head2 normalize_marc
152
153 Gently massages your data.
154
155 =cut
156
157 sub normalize_marc {
158     my ($marc) = @_;
159
160     $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
161     if ($marc->{title}) {
162         $marc->{title} = NFD($marc->{title});
163         $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
164         $marc->{title} = lc($marc->{title});
165         $marc->{title} =~ s/\W+$//go;
166     }
167     if ($marc->{author}) {
168         $marc->{author} = NFD($marc->{author});
169         $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
170         $marc->{author} = lc($marc->{author});
171         $marc->{author} =~ s/\W+$//go;
172         if ($marc->{author} =~ /^(\w+)/) {
173             $marc->{author} = $1;
174         }
175     }
176     if ($marc->{publisher}) {
177         $marc->{publisher} = NFD($marc->{publisher});
178         $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
179         $marc->{publisher} = lc($marc->{publisher});
180         $marc->{publisher} =~ s/\W+$//go;
181         if ($marc->{publisher} =~ /^(\w+)/) {
182             $marc->{publisher} = $1;
183         }
184     }
185     return $marc;
186 }
187
188
189
190 =head2 marc_isvalid
191
192 Checks MARC record to see if neccessary fingerprinting data is
193 available
194
195 =cut
196
197 sub marc_isvalid {
198     my ($marc) = @_;
199     return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
200                  $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
201     return 0;
202 }
203
204
205 =head2 dump_fingerprints
206
207 =cut
208
209 sub dump_fingerprints {
210     my ($marc) = @_;
211     my $good_fp = 0;
212
213     if ($conf->{runtype} eq "primary") {
214         print OF join("\t",$marc->{id}, $marc->{item_form},
215                           $marc->{date1}, $marc->{record_type},
216                           $marc->{bib_lvl}, $marc->{title}), "\n";
217     } else {
218         if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
219             # case a : isbn and pages
220             foreach my $isbn ( @{ $marc->{isbns}} ) {
221                 print OF join("\t", $marc->{id}, "case a",
222                                   $marc->{item_form}, $marc->{date1},
223                                   $marc->{record_type},
224                                   $marc->{bib_lvl}, $marc->{title},
225                                   $isbn, $marc->{pages}), "\n";
226             }
227             $good_fp = 1;
228         }
229
230 =pod
231
232 Looks like case b isn't a terribly good idea most of the time -- it
233 will generate many spurious matches in series books in particular. So
234 for now, simply turning it off.
235
236         if ($marc->{edition}) { # case b : edition
237             print OF join("\t", $marc->{id}, "case b",
238                               $marc->{item_form}, $marc->{date1},
239                               $marc->{record_type}, $marc->{bib_lvl},
240                               $marc->{title}, $marc->{edition}), "\n";
241             $good_fp = 1;
242         }
243
244 =cut
245
246         if ($marc->{issn}) { # case c : issn
247             print OF join("\t", $marc->{id}, "case c",
248                               $marc->{item_form}, $marc->{date1},
249                               $marc->{record_type}, $marc->{bib_lvl},
250                               $marc->{title}, $marc->{issn}), "\n";
251             $good_fp = 1;
252         }
253
254         if ($marc->{lccn}) { # case d : lccn
255             print OF join("\t", $marc->{id}, "case d",
256                               $marc->{item_form}, $marc->{date1},
257                               $marc->{record_type}, $marc->{bib_lvl},
258                               $marc->{title}, $marc->{lccn}) ,"\n";
259             $good_fp = 1;
260         }
261
262         if ($marc->{accomp}) { # case e : accomp
263             print OF join("\t", $marc->{id}, "case e",
264                               $marc->{item_form}, $marc->{date1},
265                               $marc->{record_type}, $marc->{bib_lvl},
266                               $marc->{title}, $marc->{accomp}) ,"\n";
267             $good_fp = 1;
268         }
269
270         # case o: oclc
271         if (scalar @{$marc->{oclc} }) {
272             for (@{$marc->{oclc} }) {
273                 print OF join("\t", $marc->{id}, "case o",
274                               $marc->{item_form}, $marc->{date1},
275                               $marc->{record_type}, $marc->{bib_lvl},
276                               $marc->{title}, $_, "\n");
277             }
278             $good_fp = 1;
279         }
280
281         # case z : author, publisher, pubyear, pages
282         if ($marc->{author} and $marc->{publisher} and $marc->{pubyear}
283             and $marc->{pages}) {
284             print OF join("\t", $marc->{id}, "case z",
285                               $marc->{item_form}, $marc->{date1},
286                               $marc->{record_type}, $marc->{bib_lvl},
287                               $marc->{title}, $marc->{author},
288                               $marc->{publisher}, $marc->{pubyear},
289                               $marc->{pages}), "\n";
290             $good_fp = 1;
291         }
292
293         # case poo : nothing good; dump a primary and move on
294         unless ($good_fp) {
295             print OF join("\t", $marc->{id}, "case poo", $marc->{item_form},
296                           $marc->{date1}, $marc->{record_type},
297                           $marc->{bib_lvl}, $marc->{title}), "\n";
298         }
299     }
300 }
301
302
303
304 =head2 dump_exception
305
306 Write line of exception report
307
308 =cut
309
310 sub dump_exception {
311     my ($marc) = @_;
312     unless (defined $marc) {
313         print XF "Undefined record at line $count; likely bad XML\n";
314         return;
315     }
316     print XF "Record ", $marc->{id}, " did not make the cut: ";
317     print XF "Missing item_form. " unless ($marc->{item_form});
318     unless (defined $marc->{date1})
319       { print XF "Missing date1. " }
320     else
321       { print XF "Invalid date1: ", $marc->{date1}, " "
322           unless ($marc->{date1} =~ /\d{4}/); }
323     print XF "Missing record_type. " unless ($marc->{record_type});
324     print XF "Missing bib_lvl. " unless ($marc->{bib_lvl});
325     print XF "Missing title. " unless ($marc->{title});
326     print XF "\n";
327 }
328
329
330 =head2 initialize
331
332 Performs boring script initialization. Handles argument parsing,
333 mostly.
334
335 =cut
336
337 sub initialize {
338     my ($c) = @_;
339     my @missing = ();
340
341     # set mode on existing filehandles
342     binmode(STDIN, ':utf8');
343
344     my $rc = GetOptions( $c,
345                          'incoming',
346                          'incumbent',
347                          'exception|x=s',
348                          'marctype|m=s',
349                          'output|o=s',
350                          'runtype|r=s',
351                          'subfield|s=s',
352                          'tag|t=s',
353                          'quiet|q',
354                          'help|h',
355                        );
356     show_help() unless $rc;
357     show_help() if ($c->{help});
358
359     # set defaults if told to do so
360     if ($c->{incoming}) {
361         $c->{tag} = 903 unless defined $c->{tag};
362         $c->{subfield} = 'a' unless defined $c->{subfield};
363         $c->{marctype} = 'XML' unless defined $c->{marctype};
364         $c->{output} = 'incoming.fp' unless defined $c->{output};
365         $c->{exception} = 'incoming.ex' unless defined $c->{exception};
366         $c->{runtype} = 'full' unless defined $c->{runtype};
367     } elsif ($c->{incumbent}) {
368         $c->{tag} = 901 unless defined $c->{tag};
369         $c->{subfield} = 'c' unless defined $c->{subfield};
370         $c->{marctype} = 'XML' unless defined $c->{marctype};
371         $c->{output} = 'incumbent.fp' unless defined $c->{output};
372         $c->{exception} = 'incumbent.ex' unless defined $c->{exception};
373         $c->{runtype} = 'full' unless defined $c->{runtype};
374     }
375
376     my @keys = keys %{$c};
377     show_help() unless (@ARGV and @keys);
378     for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
379       { push @missing, $key unless $c->{$key} }
380     if (@missing) {
381         print "Required option: ", join(', ', @missing), " missing!\n";
382         show_help();
383     }
384 }
385
386
387 =head2 progress_ticker
388
389 =cut
390
391 sub progress_ticker {
392     return if $conf->{quiet};
393     printf("\r> %d recs seen; %d processed", $count, $scount);
394     printf(" (%d/s)", ($count / (time - $start + 1)))
395       if ($count % 500 == 0);
396 }
397
398 =head2 show_help
399
400 Display usage message when things go wrong
401
402 =cut
403
404 sub show_help {
405 print <<HELP;
406 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
407 Req'd Arguments
408   --runtype=(primary|full) -r  Do 'primary' or 'full' fingerprinting
409   --tag=N                  -t  Which tag to use
410   --subfield=X             -s  Which subfield to use
411   --output=<file>          -o  Output filename
412   --exceptions=<file>      -x  Exception report filename
413 Options
414   --incoming     Set -r to 'full'; -t, -s, -o, -x to incoming defaults
415   --incumbent    Set -r to 'full'; -t, -s, -o, -x to incumbent defaults
416
417   Example: '$0 --incoming' is equivalent to
418            '$0 -r full -t 903 -s a -o incoming.fp -x incoming.ex'
419
420   --quiet    -q  Don't write status messages to STDOUT
421 HELP
422 exit 1;
423 }