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