added Case Poo for record so crappy they don't meet any of the other cases
[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 binmode(OF, ':utf8');
20 open XF, '>', $conf->{exception};
21 binmode(XF, ':utf8');
22
23 for my $file (@ARGV) {
24     print XF "Processing $file\n";
25     #open my $records, '<:utf8', $file; # This hack dosn't play nice with the use MARC::File::XML ( BinaryEncoding => 'utf-8' ); hack
26     my $batch = undef; my $record = undef;
27
28     #$batch = MARC::Batch->new('XML', $records); # The other part of the hack
29     $batch = MARC::Batch->new($conf->{marctype}, $file);
30     $batch->strict_off();
31     $batch->warnings_off();
32
33     while ( $record = $batch->next ) {
34         $count++; progress_ticker();
35         my $marc = undef;
36         unless ( defined $record )
37           { dump_exception($marc); next; }
38
39         my $id = $record->field($conf->{tag});
40         unless ($id) {
41             print XF "ERROR: Record $count in $file is missing a ",
42               $conf->{tag}, " field.\n", $record->as_formatted(), "\n=====\n";
43             next;
44         }
45
46         $marc = populate_marc($record, $id);
47         $marc = normalize_marc($marc);
48         unless (marc_isvalid($marc))
49           { dump_exception($marc); next; }
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 dump_fingerprints
208
209 =cut
210
211 sub dump_fingerprints {
212     my ($marc) = @_;
213     my $good_fp = 0;
214
215     if ($conf->{runtype} eq "primary") {
216         print OF join("\t",$marc->{id}, $marc->{item_form},
217                           $marc->{date1}, $marc->{record_type},
218                           $marc->{bib_lvl}, $marc->{title}), "\n";
219     } else {
220         if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
221             # case a : isbn and pages
222             foreach my $isbn ( @{ $marc->{isbns}} ) {
223                 print OF join("\t", $marc->{id}, "case a",
224                                   $marc->{item_form}, $marc->{date1},
225                                   $marc->{record_type},
226                                   $marc->{bib_lvl}, $marc->{title},
227                                   $isbn, $marc->{pages}), "\n";
228             }
229             $good_fp = 1;
230         }
231
232 =pod
233
234 Looks like case b isn't a terribly good idea most of the time -- it
235 will generate many spurious matches in series books in particular. So
236 for now, simply turning it off.
237
238         if ($marc->{edition}) { # case b : edition
239             print OF join("\t", $marc->{id}, "case b",
240                               $marc->{item_form}, $marc->{date1},
241                               $marc->{record_type}, $marc->{bib_lvl},
242                               $marc->{title}, $marc->{edition}), "\n";
243             $good_fp = 1;
244         }
245
246 =cut
247
248         if ($marc->{issn}) { # case c : issn
249             print OF join("\t", $marc->{id}, "case c",
250                               $marc->{item_form}, $marc->{date1},
251                               $marc->{record_type}, $marc->{bib_lvl},
252                               $marc->{title}, $marc->{issn}), "\n";
253             $good_fp = 1;
254         }
255
256         if ($marc->{lccn}) { # case d : lccn
257             print OF join("\t", $marc->{id}, "case d",
258                               $marc->{item_form}, $marc->{date1},
259                               $marc->{record_type}, $marc->{bib_lvl},
260                               $marc->{title}, $marc->{lccn}) ,"\n";
261             $good_fp = 1;
262         }
263
264         if ($marc->{accomp}) { # case e : accomp
265             print OF join("\t", $marc->{id}, "case e",
266                               $marc->{item_form}, $marc->{date1},
267                               $marc->{record_type}, $marc->{bib_lvl},
268                               $marc->{title}, $marc->{accomp}) ,"\n";
269             $good_fp = 1;
270         }
271
272         # case o: oclc
273         if (scalar @{$marc->{oclc} }) {
274             for (@{$marc->{oclc} }) {
275                 print OF join("\t", $marc->{id}, "case o",
276                               $marc->{item_form}, $marc->{date1},
277                               $marc->{record_type}, $marc->{bib_lvl},
278                               $marc->{title}, $_, "\n");
279             }
280             $good_fp = 1;
281         }
282
283         # case z : author, publisher, pubyear, pages
284         if ($marc->{author} and $marc->{publisher} and $marc->{pubyear}
285             and $marc->{pages}) {
286             print OF join("\t", $marc->{id}, "case z",
287                               $marc->{item_form}, $marc->{date1},
288                               $marc->{record_type}, $marc->{bib_lvl},
289                               $marc->{title}, $marc->{author},
290                               $marc->{publisher}, $marc->{pubyear},
291                               $marc->{pages}), "\n";
292             $good_fp = 1;
293         }
294
295         # case poo : nothing good; dump a primary and move on
296         unless ($good_fp) {
297             print OF join("\t", $marc->{id}, "case poo", $marc->{item_form},
298                           $marc->{date1}, $marc->{record_type},
299                           $marc->{bib_lvl}, $marc->{title}), "\n";
300         }
301     }
302 }
303
304
305
306 =head2 dump_exception
307
308 Write line of exception report
309
310 =cut
311
312 sub dump_exception {
313     my ($marc) = @_;
314     unless (defined $marc) {
315         print XF "Undefined record at line $count; likely bad XML\n";
316         return;
317     }
318     print XF "Record ", $marc->{id}, " did not make the cut: ";
319     print XF "Missing item_form. " unless ($marc->{item_form});
320     unless (defined $marc->{date1})
321       { print XF "Missing date1. " }
322     else
323       { print XF "Invalid date1: ", $marc->{date1}, " "
324           unless ($marc->{date1} =~ /\d{4}/); }
325     print XF "Missing record_type. " unless ($marc->{record_type});
326     print XF "Missing bib_lvl. " unless ($marc->{bib_lvl});
327     print XF "Missing title. " unless ($marc->{title});
328     print XF "\n";
329 }
330
331
332 =head2 initialize
333
334 Performs boring script initialization. Handles argument parsing,
335 mostly.
336
337 =cut
338
339 sub initialize {
340     my ($c) = @_;
341     my @missing = ();
342
343     # set mode on existing filehandles
344     binmode(STDIN, ':utf8');
345
346     my $rc = GetOptions( $c,
347                          'incoming',
348                          'incumbent',
349                          'exception|x=s',
350                          'marctype|m=s',
351                          'output|o=s',
352                          'runtype|r=s',
353                          'subfield|s=s',
354                          'tag|t=s',
355                          'quiet|q',
356                          'help|h',
357                        );
358     show_help() unless $rc;
359     show_help() if ($c->{help});
360
361     # set defaults if told to do so
362     if ($c->{incoming}) {
363         $c->{tag} = 903 unless defined $c->{tag};
364         $c->{subfield} = 'a' unless defined $c->{subfield};
365         $c->{marctype} = 'XML' unless defined $c->{marctype};
366         $c->{output} = 'incoming.fp' unless defined $c->{output};
367         $c->{exception} = 'incoming.ex' unless defined $c->{exception};
368         $c->{runtype} = 'full' unless defined $c->{runtype};
369     } elsif ($c->{incumbent}) {
370         $c->{tag} = 901 unless defined $c->{tag};
371         $c->{subfield} = 'c' unless defined $c->{subfield};
372         $c->{marctype} = 'XML' unless defined $c->{marctype};
373         $c->{output} = 'incumbent.fp' unless defined $c->{output};
374         $c->{exception} = 'incumbent.ex' unless defined $c->{exception};
375         $c->{runtype} = 'full' unless defined $c->{runtype};
376     }
377
378     my @keys = keys %{$c};
379     show_help() unless (@ARGV and @keys);
380     for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
381       { push @missing, $key unless $c->{$key} }
382     if (@missing) {
383         print "Required option: ", join(', ', @missing), " missing!\n";
384         show_help();
385     }
386 }
387
388
389 =head2 progress_ticker
390
391 =cut
392
393 sub progress_ticker {
394     return if $conf->{quiet};
395     printf("\r> %d recs seen; %d processed", $count, $scount);
396     printf(" (%d/s)", ($count / (time - $start + 1)))
397       if ($count % 500 == 0);
398 }
399
400 =head2 show_help
401
402 Display usage message when things go wrong
403
404 =cut
405
406 sub show_help {
407 print <<HELP;
408 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
409 Req'd Arguments
410   --runtype=(primary|full) -r  Do 'primary' or 'full' fingerprinting
411   --tag=N                  -t  Which tag to use
412   --subfield=X             -s  Which subfield to use
413   --output=<file>          -o  Output filename
414   --exceptions=<file>      -x  Exception report filename
415 Options
416   --incoming     Set -r to 'full'; -t, -s, -o, -x to incoming defaults
417   --incumbent    Set -r to 'full'; -t, -s, -o, -x to incumbent defaults
418
419   Example: '$0 --incoming' is equivalent to
420            '$0 -r full -t 903 -s a -o incoming.fp -x incoming.ex'
421
422   --quiet    -q  Don't write status messages to STDOUT
423 HELP
424 exit 1;
425 }