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