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