ticker improvements
[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('XML', $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     # 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 $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                          'incoming',
292                          'incumbent',
293                          'exception|x=s',
294                          'output|o=s',
295                          'runtype|r=s',
296                          'subfield|s=s',
297                          'tag|t=s',
298                          'quiet|q',
299                          'help|h',
300                        );
301     show_help() unless $rc;
302     show_help() if ($c->{help});
303
304     # set defaults if told to do so
305     if ($c->{incoming}) {
306         $c->{tag} = 903 unless defined $c->{tag};
307         $c->{subfield} = 'a' unless defined $c->{subfield};
308         $c->{output} = 'incoming.fp' unless defined $c->{output};
309         $c->{exception} = 'incoming.ex' unless defined $c->{exception};
310         $c->{runtype} = 'full' unless defined $c->{runtype};
311     } elsif ($c->{incumbent}) {
312         $c->{tag} = 901 unless defined $c->{tag};
313         $c->{subfield} = 'c' unless defined $c->{subfield};
314         $c->{output} = 'incumbent.fp' unless defined $c->{output};
315         $c->{exception} = 'incumbent.ex' unless defined $c->{exception};
316         $c->{runtype} = 'full' unless defined $c->{runtype};
317     }
318
319     my @keys = keys %{$c};
320     show_help() unless (@ARGV and @keys);
321     for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
322       { push @missing, $key unless $c->{$key} }
323     if (@missing) {
324         print "Required option: ", join(', ', @missing), " missing!\n";
325         show_help();
326     }
327 }
328
329
330 =head2 progress_ticker
331
332 =cut
333
334 sub progress_ticker {
335     return if $conf->{quiet};
336     printf("\r> %d recs seen; %d processed", $count, $scount);
337     printf(" (%d/s)", ($count / (time - $start + 1)))
338       if ($count % 500 == 0);
339 }
340
341 =head2 show_help
342
343 Display usage message when things go wrong
344
345 =cut
346
347 sub show_help {
348 print <<HELP;
349 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
350 Req'd Arguments
351   --runtype=(primary|full) -r  Do 'primary' or 'full' fingerprinting
352   --tag=N                  -t  Which tag to use
353   --subfield=X             -s  Which subfield to use
354   --output=<file>          -o  Output filename
355   --exceptions=<file>      -x  Exception report filename
356 Options
357   --incoming     Set -r to 'full'; -t, -s, -o, -x to incoming defaults
358   --incumbent    Set -r to 'full'; -t, -s, -o, -x to incumbent defaults
359
360   Example: '$0 --incoming' is equivalent to
361            '$0 -r full -t 903 -s a -o incoming.fp -x incoming.ex'
362
363   --quiet    -q  Don't write status messages to STDOUT
364 HELP
365 exit 1;
366 }