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