7cadd539dcaea1ccf95a6af8532cc2626e669d97
[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 MARC::File::XML ( BinaryEncoding => 'utf-8' );
9 use MARC::Field;
10 use Unicode::Normalize;
11
12 my $conf  = {}; # configuration hashref
13 my $count = 0;
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 (length $my_008 == 40)
78       { print XF ">> Bad 008 field length in rec. $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     
106
107     # issn, lccn, title, desc, pages, pub, pubyear, edition
108     $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
109     $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
110     $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
111     $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
112     $marc{title} = $record->field('245')->subfield('a')
113       if defined $record->field('245');
114     $marc{edition} = $record->field('250')->subfield('a')
115       if $record->field('250');
116     if ($record->field('260')) {
117         $marc{publisher} = $record->field('260')->subfield('b');
118         $marc{pubyear} = $record->field('260')->subfield('c');
119         $marc{pubyear} =
120           (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
121     }
122     return \%marc;
123 }
124
125
126
127 =head2 normalize_marc
128
129 Gently massages your data.
130
131 =cut
132
133 sub normalize_marc {
134     my ($marc) = @_;
135
136     $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
137     if ($marc->{title}) {
138         $marc->{title} = NFD($marc->{title});
139         $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
140         $marc->{title} = lc($marc->{title});
141         $marc->{title} =~ s/\W+$//go;
142     }
143     if ($marc->{author}) {
144         $marc->{author} = NFD($marc->{author});
145         $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
146         $marc->{author} = lc($marc->{author});
147         $marc->{author} =~ s/\W+$//go;
148         if ($marc->{author} =~ /^(\w+)/) {
149             $marc->{author} = $1;
150         }
151     }
152     if ($marc->{publisher}) {
153         $marc->{publisher} = NFD($marc->{publisher});
154         $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
155         $marc->{publisher} = lc($marc->{publisher});
156         $marc->{publisher} =~ s/\W+$//go;
157         if ($marc->{publisher} =~ /^(\w+)/) {
158             $marc->{publisher} = $1;
159         }
160     }
161     return $marc;
162 }
163
164
165
166 =head2 marc_isvalid
167
168 Checks MARC record to see if neccessary fingerprinting data is
169 available
170
171 =cut
172
173 sub marc_isvalid {
174     my ($marc) = @_;
175     return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
176                  $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
177     return 0;
178 }
179
180
181 =head2 dump_fingerprints
182
183 =cut
184
185 sub dump_fingerprints {
186     my ($marc) = @_;
187
188     if ($conf->{runtype} eq "primary") {
189         print OF join("\t",$marc->{id}, $marc->{item_form},
190                           $marc->{date1}, $marc->{record_type},
191                           $marc->{bib_lvl}, $marc->{title}), "\n";
192     } else {
193         if ((scalar @{ $marc->{isbns} } > 0) && $marc->{pages}) {
194             # case a : isbn and pages
195             foreach my $isbn ( @{ $marc->{isbns}} ) {
196                 print OF join("\t", $marc->{id}, "case a",
197                                   $marc->{item_form}, $marc->{date1},
198                                   $marc->{record_type},
199                                   $marc->{bib_lvl}, $marc->{title},
200                                   $isbn, $marc->{pages}), "\n";
201             }
202         }
203
204         if ($marc->{edition}) { # case b : edition
205             print OF join("\t", $marc->{id}, "case b",
206                               $marc->{item_form}, $marc->{date1},
207                               $marc->{record_type}, $marc->{bib_lvl},
208                               $marc->{title}, $marc->{edition}), "\n";
209         }
210
211         if ($marc->{issn}) { # case c : issn
212             print OF join("\t", $marc->{id}, "case c",
213                               $marc->{item_form}, $marc->{date1},
214                               $marc->{record_type}, $marc->{bib_lvl},
215                               $marc->{title}, $marc->{issn}), "\n";
216         }
217
218         if ($marc->{lccn}) { # case d : lccn
219             print OF join("\t", $marc->{id}, "case d",
220                               $marc->{item_form}, $marc->{date1},
221                               $marc->{record_type}, $marc->{bib_lvl},
222                               $marc->{title}, $marc->{lccn}) ,"\n";
223         }
224
225         # case e : author, publisher, pubyear, pages
226         if ($marc->{author} and $marc->{publisher} and $marc->{pubyear}
227             and $marc->{pages}) {
228             print OF join("\t", $marc->{id}, "case e",
229                               $marc->{item_form}, $marc->{date1},
230                               $marc->{record_type}, $marc->{bib_lvl},
231                               $marc->{title}, $marc->{author},
232                               $marc->{publisher}, $marc->{pubyear},
233                               $marc->{pages}), "\n";
234         }
235     }
236 }
237
238
239
240 =head2 dump_exception
241
242 Write line of exception report
243
244 =cut
245
246 sub dump_exception {
247     my ($marc) = @_;
248     unless (defined $marc) {
249         print XF "Undefined record at line $count; likely bad XML\n";
250         return;
251     }
252     print XF "Record ", $marc->{id}, " did not make the cut: ";
253     print XF "Missing item_form. " unless ($marc->{item_form});
254     print XF "Missing date1. " unless (defined $marc->{date1});
255     print XF "Invalid date1: ", $marc->{date1}
256       unless ($marc->{date1} =~ /\d{4}/);
257     print XF "Missing record_type. " unless ($marc->{record_type});
258     print XF "Missing bib_lvl. " unless ($marc->{bib_lvl});
259     print XF "Missing title. " unless ($marc->{title});
260     print XF "\n";
261 }
262
263
264 =head2 initialize
265
266 Performs boring script initialization. Handles argument parsing,
267 mostly.
268
269 =cut
270
271 sub initialize {
272     my ($c) = @_;
273     my @missing = ();
274
275     # set mode on existing filehandles
276     binmode(STDIN, ':utf8');
277
278     my $rc = GetOptions( $c,
279                          'exception|x=s',
280                          'output|o=s',
281                          'runtype|r=s',
282                          'subfield|s=s',
283                          'tag|t=s',
284                          'quiet|q',
285                          'help|h',
286                        );
287     show_help() unless $rc;
288
289     my @keys = keys %{$c};
290     show_help() unless (@ARGV and @keys);
291     for my $key ('runtype', 'tag', 'subfield', 'output', 'exception') {
292         push @missing, $key unless $c->{$key}
293     }
294     if (@missing) {
295         print "Required option: ", join(', ', @missing), " missing!\n";
296         show_help();
297     }
298
299     show_help() if ($c->{help});
300 }
301
302
303 =head2 progress_ticker
304
305 =cut
306
307 sub progress_ticker {
308     return if $conf->{quiet};
309
310     if ($count % 100 == 0) {
311         print '|';
312         print " $count \n" unless ($count % 1400);
313     } elsif ($count % 20 == 0) {
314         print '.';
315     }
316 }
317
318 =head2 show_help
319
320 Display usage message when things go wrong
321
322 =cut
323
324 sub show_help {
325 print <<HELP;
326 Usage is: fingerprinter [REQUIRED ARGS] [OPTIONS] <filelist>
327 Req'd Arguments
328   --runtype=(primary|full) -r  Do 'primary' or 'full' fingerprinting
329   --tag=N                  -t  Which tag to use
330   --subfield=X             -s  Which subfield to use
331   --output=<file>          -o  Output filename
332   --exceptions=<file>      -x  Exception report filename
333 Options
334   --quiet  -q  Don't write status messages to STDOUT
335 HELP
336 exit 1;
337 }