functionally removing case b from the matchsets
[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
217 =pod
218
219 Looks like case b isn't a terribly good idea most of the time -- it
220 will generate many spurious matches in series books in particular. So
221 for now, simply turning it off.
222
223         if ($marc->{edition}) { # case b : edition
224             print OF join("\t", $marc->{id}, "case b",
225                               $marc->{item_form}, $marc->{date1},
226                               $marc->{record_type}, $marc->{bib_lvl},
227                               $marc->{title}, $marc->{edition}), "\n";
228         }
229
230 =cut
231
232         if ($marc->{issn}) { # case c : issn
233             print OF join("\t", $marc->{id}, "case c",
234                               $marc->{item_form}, $marc->{date1},
235                               $marc->{record_type}, $marc->{bib_lvl},
236                               $marc->{title}, $marc->{issn}), "\n";
237         }
238
239         if ($marc->{lccn}) { # case d : lccn
240             print OF join("\t", $marc->{id}, "case d",
241                               $marc->{item_form}, $marc->{date1},
242                               $marc->{record_type}, $marc->{bib_lvl},
243                               $marc->{title}, $marc->{lccn}) ,"\n";
244         }
245
246         if ($marc->{accomp}) { # case e : accomp
247             print OF join("\t", $marc->{id}, "case d",
248                               $marc->{item_form}, $marc->{date1},
249                               $marc->{record_type}, $marc->{bib_lvl},
250                               $marc->{title}, $marc->{accomp}) ,"\n";
251         }
252
253         # case z : author, publisher, pubyear, pages
254         if ($marc->{author} and $marc->{publisher} and $marc->{pubyear}
255             and $marc->{pages}) {
256             print OF join("\t", $marc->{id}, "case e",
257                               $marc->{item_form}, $marc->{date1},
258                               $marc->{record_type}, $marc->{bib_lvl},
259                               $marc->{title}, $marc->{author},
260                               $marc->{publisher}, $marc->{pubyear},
261                               $marc->{pages}), "\n";
262         }
263     }
264 }
265
266
267
268 =head2 dump_exception
269
270 Write line of exception report
271
272 =cut
273
274 sub dump_exception {
275     my ($marc) = @_;
276     unless (defined $marc) {
277         print XF "Undefined record at line $count; likely bad XML\n";
278         return;
279     }
280     print XF "Record ", $marc->{id}, " did not make the cut: ";
281     print XF "Missing item_form. " unless ($marc->{item_form});
282     unless (defined $marc->{date1})
283       { print XF "Missing date1. " }
284     else
285       { print XF "Invalid date1: ", $marc->{date1}, " "
286           unless ($marc->{date1} =~ /\d{4}/); }
287     print XF "Missing record_type. " unless ($marc->{record_type});
288     print XF "Missing bib_lvl. " unless ($marc->{bib_lvl});
289     print XF "Missing title. " unless ($marc->{title});
290     print XF "\n";
291 }
292
293
294 =head2 initialize
295
296 Performs boring script initialization. Handles argument parsing,
297 mostly.
298
299 =cut
300
301 sub initialize {
302     my ($c) = @_;
303     my @missing = ();
304
305     # set mode on existing filehandles
306     binmode(STDIN, ':utf8');
307
308     my $rc = GetOptions( $c,
309                          'incoming',
310                          'incumbent',
311                          'exception|x=s',
312                          'marctype|m=s',
313                          'output|o=s',
314                          'runtype|r=s',
315                          'subfield|s=s',
316                          'tag|t=s',
317                          'quiet|q',
318                          'help|h',
319                        );
320     show_help() unless $rc;
321     show_help() if ($c->{help});
322
323     # set defaults if told to do so
324     if ($c->{incoming}) {
325         $c->{tag} = 903 unless defined $c->{tag};
326         $c->{subfield} = 'a' unless defined $c->{subfield};
327         $c->{marctype} = 'XML' unless defined $c->{marctype};
328         $c->{output} = 'incoming.fp' unless defined $c->{output};
329         $c->{exception} = 'incoming.ex' unless defined $c->{exception};
330         $c->{runtype} = 'full' unless defined $c->{runtype};
331     } elsif ($c->{incumbent}) {
332         $c->{tag} = 901 unless defined $c->{tag};
333         $c->{subfield} = 'c' unless defined $c->{subfield};
334         $c->{marctype} = 'XML' unless defined $c->{marctype};
335         $c->{output} = 'incumbent.fp' unless defined $c->{output};
336         $c->{exception} = 'incumbent.ex' unless defined $c->{exception};
337         $c->{runtype} = 'full' unless defined $c->{runtype};
338     }
339
340     my @keys = keys %{$c};
341     show_help() unless (@ARGV and @keys);
342     for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
343       { push @missing, $key unless $c->{$key} }
344     if (@missing) {
345         print "Required option: ", join(', ', @missing), " missing!\n";
346         show_help();
347     }
348 }
349
350
351 =head2 progress_ticker
352
353 =cut
354
355 sub progress_ticker {
356     return if $conf->{quiet};
357     printf("\r> %d recs seen; %d processed", $count, $scount);
358     printf(" (%d/s)", ($count / (time - $start + 1)))
359       if ($count % 500 == 0);
360 }
361
362 =head2 show_help
363
364 Display usage message when things go wrong
365
366 =cut
367
368 sub show_help {
369 print <<HELP;
370 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
371 Req'd Arguments
372   --runtype=(primary|full) -r  Do 'primary' or 'full' fingerprinting
373   --tag=N                  -t  Which tag to use
374   --subfield=X             -s  Which subfield to use
375   --output=<file>          -o  Output filename
376   --exceptions=<file>      -x  Exception report filename
377 Options
378   --incoming     Set -r to 'full'; -t, -s, -o, -x to incoming defaults
379   --incumbent    Set -r to 'full'; -t, -s, -o, -x to incumbent defaults
380
381   Example: '$0 --incoming' is equivalent to
382            '$0 -r full -t 903 -s a -o incoming.fp -x incoming.ex'
383
384   --quiet    -q  Don't write status messages to STDOUT
385 HELP
386 exit 1;
387 }