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