OCLC stuffs
[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     # oclc
116     $marc{oclc} = [];
117     push @{ $marc{oclc} }, $record->field('001')->as_string()
118       if ($record->field('001') and $record->field('003') and
119           $record->field('003')->as_string() =~ /OCo{0,1}LC/);
120     for ($record->field('035')) {
121         my $oclc = $_->subfield('a');
122         push @{ $marc{oclc} }, $oclc
123           if (defined $oclc and $oclc =~ /\(OCoLC\)/ and $oclc =~/([0-9]+)/);
124     }
125
126     # "Accompanying material" (300e)
127     $marc{accomp} = $record->field('300')->subfield('e')
128       if $record->field('300');
129
130     # issn, lccn, title, desc, pages, pub, pubyear, edition
131     $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
132     $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
133     $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
134     $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
135     $marc{title} = $record->field('245')->subfield('a')
136       if $record->field('245');
137     $marc{edition} = $record->field('250')->subfield('a')
138       if $record->field('250');
139     if ($record->field('260')) {
140         $marc{publisher} = $record->field('260')->subfield('b');
141         $marc{pubyear} = $record->field('260')->subfield('c');
142         $marc{pubyear} =
143           (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
144     }
145     return \%marc;
146 }
147
148
149
150 =head2 normalize_marc
151
152 Gently massages your data.
153
154 =cut
155
156 sub normalize_marc {
157     my ($marc) = @_;
158
159     $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
160     if ($marc->{title}) {
161         $marc->{title} = NFD($marc->{title});
162         $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
163         $marc->{title} = lc($marc->{title});
164         $marc->{title} =~ s/\W+$//go;
165     }
166     if ($marc->{author}) {
167         $marc->{author} = NFD($marc->{author});
168         $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
169         $marc->{author} = lc($marc->{author});
170         $marc->{author} =~ s/\W+$//go;
171         if ($marc->{author} =~ /^(\w+)/) {
172             $marc->{author} = $1;
173         }
174     }
175     if ($marc->{publisher}) {
176         $marc->{publisher} = NFD($marc->{publisher});
177         $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
178         $marc->{publisher} = lc($marc->{publisher});
179         $marc->{publisher} =~ s/\W+$//go;
180         if ($marc->{publisher} =~ /^(\w+)/) {
181             $marc->{publisher} = $1;
182         }
183     }
184     return $marc;
185 }
186
187
188
189 =head2 marc_isvalid
190
191 Checks MARC record to see if neccessary fingerprinting data is
192 available
193
194 =cut
195
196 sub marc_isvalid {
197     my ($marc) = @_;
198     return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
199                  $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
200     return 0;
201 }
202
203
204 =head2 dump_fingerprints
205
206 =cut
207
208 sub dump_fingerprints {
209     my ($marc) = @_;
210
211     if ($conf->{runtype} eq "primary") {
212         print OF join("\t",$marc->{id}, $marc->{item_form},
213                           $marc->{date1}, $marc->{record_type},
214                           $marc->{bib_lvl}, $marc->{title}), "\n";
215     } else {
216         if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
217             # case a : isbn and pages
218             foreach my $isbn ( @{ $marc->{isbns}} ) {
219                 print OF join("\t", $marc->{id}, "case a",
220                                   $marc->{item_form}, $marc->{date1},
221                                   $marc->{record_type},
222                                   $marc->{bib_lvl}, $marc->{title},
223                                   $isbn, $marc->{pages}), "\n";
224             }
225         }
226
227
228 =pod
229
230 Looks like case b isn't a terribly good idea most of the time -- it
231 will generate many spurious matches in series books in particular. So
232 for now, simply turning it off.
233
234         if ($marc->{edition}) { # case b : edition
235             print OF join("\t", $marc->{id}, "case b",
236                               $marc->{item_form}, $marc->{date1},
237                               $marc->{record_type}, $marc->{bib_lvl},
238                               $marc->{title}, $marc->{edition}), "\n";
239         }
240
241 =cut
242
243         if ($marc->{issn}) { # case c : issn
244             print OF join("\t", $marc->{id}, "case c",
245                               $marc->{item_form}, $marc->{date1},
246                               $marc->{record_type}, $marc->{bib_lvl},
247                               $marc->{title}, $marc->{issn}), "\n";
248         }
249
250         if ($marc->{lccn}) { # case d : lccn
251             print OF join("\t", $marc->{id}, "case d",
252                               $marc->{item_form}, $marc->{date1},
253                               $marc->{record_type}, $marc->{bib_lvl},
254                               $marc->{title}, $marc->{lccn}) ,"\n";
255         }
256
257         if ($marc->{accomp}) { # case e : accomp
258             print OF join("\t", $marc->{id}, "case e",
259                               $marc->{item_form}, $marc->{date1},
260                               $marc->{record_type}, $marc->{bib_lvl},
261                               $marc->{title}, $marc->{accomp}) ,"\n";
262         }
263
264         # case o: oclc
265         if (scalar @{$marc->{oclc} }) {
266             for (@{$marc->{oclc} }) {
267                 print OF join("\t", $marc->{id}, "case o",
268                               $marc->{item_form}, $marc->{date1},
269                               $marc->{record_type}, $marc->{bib_lvl},
270                               $marc->{title}, $_, "\n");
271             }
272         }
273
274         # case z : author, publisher, pubyear, pages
275         if ($marc->{author} and $marc->{publisher} and $marc->{pubyear}
276             and $marc->{pages}) {
277             print OF join("\t", $marc->{id}, "case z",
278                               $marc->{item_form}, $marc->{date1},
279                               $marc->{record_type}, $marc->{bib_lvl},
280                               $marc->{title}, $marc->{author},
281                               $marc->{publisher}, $marc->{pubyear},
282                               $marc->{pages}), "\n";
283         }
284     }
285 }
286
287
288
289 =head2 dump_exception
290
291 Write line of exception report
292
293 =cut
294
295 sub dump_exception {
296     my ($marc) = @_;
297     unless (defined $marc) {
298         print XF "Undefined record at line $count; likely bad XML\n";
299         return;
300     }
301     print XF "Record ", $marc->{id}, " did not make the cut: ";
302     print XF "Missing item_form. " unless ($marc->{item_form});
303     unless (defined $marc->{date1})
304       { print XF "Missing date1. " }
305     else
306       { print XF "Invalid date1: ", $marc->{date1}, " "
307           unless ($marc->{date1} =~ /\d{4}/); }
308     print XF "Missing record_type. " unless ($marc->{record_type});
309     print XF "Missing bib_lvl. " unless ($marc->{bib_lvl});
310     print XF "Missing title. " unless ($marc->{title});
311     print XF "\n";
312 }
313
314
315 =head2 initialize
316
317 Performs boring script initialization. Handles argument parsing,
318 mostly.
319
320 =cut
321
322 sub initialize {
323     my ($c) = @_;
324     my @missing = ();
325
326     # set mode on existing filehandles
327     binmode(STDIN, ':utf8');
328
329     my $rc = GetOptions( $c,
330                          'incoming',
331                          'incumbent',
332                          'exception|x=s',
333                          'marctype|m=s',
334                          'output|o=s',
335                          'runtype|r=s',
336                          'subfield|s=s',
337                          'tag|t=s',
338                          'quiet|q',
339                          'help|h',
340                        );
341     show_help() unless $rc;
342     show_help() if ($c->{help});
343
344     # set defaults if told to do so
345     if ($c->{incoming}) {
346         $c->{tag} = 903 unless defined $c->{tag};
347         $c->{subfield} = 'a' unless defined $c->{subfield};
348         $c->{marctype} = 'XML' unless defined $c->{marctype};
349         $c->{output} = 'incoming.fp' unless defined $c->{output};
350         $c->{exception} = 'incoming.ex' unless defined $c->{exception};
351         $c->{runtype} = 'full' unless defined $c->{runtype};
352     } elsif ($c->{incumbent}) {
353         $c->{tag} = 901 unless defined $c->{tag};
354         $c->{subfield} = 'c' unless defined $c->{subfield};
355         $c->{marctype} = 'XML' unless defined $c->{marctype};
356         $c->{output} = 'incumbent.fp' unless defined $c->{output};
357         $c->{exception} = 'incumbent.ex' unless defined $c->{exception};
358         $c->{runtype} = 'full' unless defined $c->{runtype};
359     }
360
361     my @keys = keys %{$c};
362     show_help() unless (@ARGV and @keys);
363     for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
364       { push @missing, $key unless $c->{$key} }
365     if (@missing) {
366         print "Required option: ", join(', ', @missing), " missing!\n";
367         show_help();
368     }
369 }
370
371
372 =head2 progress_ticker
373
374 =cut
375
376 sub progress_ticker {
377     return if $conf->{quiet};
378     printf("\r> %d recs seen; %d processed", $count, $scount);
379     printf(" (%d/s)", ($count / (time - $start + 1)))
380       if ($count % 500 == 0);
381 }
382
383 =head2 show_help
384
385 Display usage message when things go wrong
386
387 =cut
388
389 sub show_help {
390 print <<HELP;
391 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
392 Req'd Arguments
393   --runtype=(primary|full) -r  Do 'primary' or 'full' fingerprinting
394   --tag=N                  -t  Which tag to use
395   --subfield=X             -s  Which subfield to use
396   --output=<file>          -o  Output filename
397   --exceptions=<file>      -x  Exception report filename
398 Options
399   --incoming     Set -r to 'full'; -t, -s, -o, -x to incoming defaults
400   --incumbent    Set -r to 'full'; -t, -s, -o, -x to incumbent defaults
401
402   Example: '$0 --incoming' is equivalent to
403            '$0 -r full -t 903 -s a -o incoming.fp -x incoming.ex'
404
405   --quiet    -q  Don't write status messages to STDOUT
406 HELP
407 exit 1;
408 }