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