8 use Unicode::Normalize;
9 use MARC::File::XML ( BinaryEncoding => 'utf-8' );
10 use Equinox::Migration::SubfieldMapper;
12 my $conf = {}; # configuration hashref
13 my $count = 0; my $scount = 0;
19 open OF, '>', $conf->{output};
20 open XF, '>', $conf->{exception};
22 for my $file (@ARGV) {
23 print XF "Processing $file\n";
24 my $batch = undef; my $record = undef;
26 $batch = MARC::Batch->new($conf->{marctype}, $file);
28 $batch->warnings_off();
30 while ( $record = $batch->next ) {
31 $count++; progress_ticker();
33 unless ( defined $record )
34 { dump_exception($marc); next; }
36 my $id = $record->field($conf->{tag});
38 print XF "ERROR: Record $count in $file is missing a ",
39 $conf->{tag}, " field.\n", $record->as_formatted(), "\n=====\n";
43 # populate and normalize marc
44 $marc = populate_marc($record, $id);
45 # check for manual exclusion
46 next if this_record_is_excluded($record, $marc);
47 normalize_marc($marc);
48 unless (marc_isvalid($marc))
49 { dump_exception($marc); next; }
51 # if everything looks good, score it and dump fingerprints
52 score_marc($marc, $record);
53 dump_fingerprints($marc);
54 $scount++; progress_ticker();
58 print "\nSuccessfully processed:\t$count\n" unless $conf->{quiet};
62 Constructs a hash containing the relevant MARC data for a record and
63 returns a reference to it.
68 my ($record, $id) = @_;
69 my %marc = (); $marc{isbns} = [];
72 $marc{id} = $id->as_string($conf->{subfield});
74 # record_type, bib_lvl
75 $marc{record_type} = substr($record->leader, 6, 1);
76 $marc{bib_lvl} = substr($record->leader, 7, 1);
79 my $my_008 = $record->field('008');
80 $marc{tag008} = $my_008->as_string() if ($my_008);
81 if (defined $marc{tag008}) {
82 unless (length $marc{tag008} == 40) {
83 $marc{tag008} = $marc{tag008} . ('|' x (40 - length($marc{tag008})));
84 print XF ">> Short 008 padded to ",length($marc{tag008})," at rec $count\n";
86 $marc{date1} = substr($marc{tag008},7,4) if ($marc{tag008});
87 $marc{date2} = substr($marc{tag008},11,4) if ($marc{tag008}); # UNUSED
89 unless ($marc{date1} and $marc{date1} =~ /\d{4}/) {
90 my $my_260 = $record->field('260');
91 my $date1 = $my_260->subfield('c') if $my_260;
92 if (defined $date1 and $date1 =~ /\d{4}/) {
93 $marc{date1} = $date1;
95 print XF ">> using 260c as date1 at rec $count\n";
100 if ( $marc{record_type} =~ /[gkroef]/ ) { # MAP, VIS
101 $marc{item_form} = substr($marc{tag008},29,1) if ($marc{tag008});
103 $marc{item_form} = substr($marc{tag008},23,1) if ($marc{tag008});
107 my @isbns = $record->field('020') if $record->field('020');
108 push @isbns, $record->field('024') if $record->field('024');
109 for my $f ( @isbns ) {
110 push @{ $marc{isbns} }, $1 if ( defined $f->subfield('a') and
111 $f->subfield('a')=~/(\S+)/ );
115 for my $rec_field (100, 110, 111) {
116 if ($record->field($rec_field)) {
117 $marc{author} = $record->field($rec_field)->subfield('a');
124 push @{ $marc{oclc} }, $record->field('001')->as_string()
125 if ($record->field('001') and $record->field('003') and
126 $record->field('003')->as_string() =~ /OCo{0,1}LC/);
127 for ($record->field('035')) {
128 my $oclc = $_->subfield('a');
129 push @{ $marc{oclc} }, $oclc
130 if (defined $oclc and $oclc =~ /\(OCoLC\)/ and $oclc =~/([0-9]+)/);
133 # "Accompanying material" and check for "copy" (300)
134 if ($record->field('300')) {
135 $marc{accomp} = $record->field('300')->subfield('e');
136 $marc{tag300a} = $record->field('300')->subfield('a');
139 # issn, lccn, title, desc, pages, pub, pubyear, edition
140 $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
141 $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
142 $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
143 $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
144 $marc{title} = $record->field('245')->subfield('a')
145 if $record->field('245');
146 $marc{edition} = $record->field('250')->subfield('a')
147 if $record->field('250');
148 if ($record->field('260')) {
149 $marc{publisher} = $record->field('260')->subfield('b');
150 $marc{pubyear} = $record->field('260')->subfield('c');
152 (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
159 =head2 normalize_marc
161 Gently massages your data.
168 $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
169 if ($marc->{title}) {
170 $marc->{title} = NFD($marc->{title});
171 $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
172 $marc->{title} = lc($marc->{title});
173 $marc->{title} =~ s/\W+$//go;
175 if ($marc->{author}) {
176 $marc->{author} = NFD($marc->{author});
177 $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
178 $marc->{author} = lc($marc->{author});
179 $marc->{author} =~ s/\W+$//go;
180 if ($marc->{author} =~ /^(\w+)/) {
181 $marc->{author} = $1;
184 if ($marc->{publisher}) {
185 $marc->{publisher} = NFD($marc->{publisher});
186 $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
187 $marc->{publisher} = lc($marc->{publisher});
188 $marc->{publisher} =~ s/\W+$//go;
189 if ($marc->{publisher} =~ /^(\w+)/) {
190 $marc->{publisher} = $1;
200 Checks MARC record to see if neccessary fingerprinting data is
207 return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
208 $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
215 Assign a score to the record based on various criteria.
217 Score is constructed by pushing elements onto a list, via a dispatch
218 table. This allows order of fingerprints in the output file to be
224 my ($marc, $record) = @_;
228 #----------------------------------
229 # static criteria scoring
230 #----------------------------------
231 $marc->{misc_score} = 999;
232 $marc->{age_score} = 999999999999;
234 # -1 if 008 has been padded, -2 if it doesn't exist
236 { $marc->{misc_score}-- if ($marc->{tag008} =~ /\|$/) }
238 { $marc->{misc_score} -= 2 }
239 # -1 if date has been pulled from 260
240 $marc->{misc_score}-- if $marc->{fudgedate};
241 # -1 if this is a copy record
242 $marc->{misc_score}--
243 if (defined $marc->{tag300a} and $marc->{tag300a} =~ /copy/i);
245 # subtract record id if we want older records to win
246 #$marc->{age_score} -= $marc->{id} unless ($conf->{newwins});
247 # handle arbitrary adjustments
248 $marc->{age_score} = 1;
249 if ($conf->{'arbitrarily-lose-above'}) {
250 $marc->{age_score} = 0
251 if ($marc->{id} >= $conf->{'arbitrarily-lose-above'});
253 if ($conf->{'arbitrarily-lose-below'}) {
254 $marc->{age_score} = 0
255 if ($marc->{id} <= $conf->{'arbitrarily-lose-below'});
258 #----------------------------------
259 # dynamic calculated scoring
260 #----------------------------------
262 oclc => sub { return $marc->{oclc}[0] ? 1 : 0 },
264 if ($record->field('040') and $record->field('040')->subfield('a'))
265 { return scalar($record->subfield( '040', 'a')) =~ /dlc/io ? 1 : 0 }
269 if ($record->field('650')) {
270 # can't say "scalar $record->field('650')"; MARC::Record
271 # behaves differently in list/scalar contexts
272 my @tags = $record->field('650');
273 return sprintf("%04d", scalar @tags)
274 } else { return '0000' }
276 num_tags=> sub { return sprintf( '%04d', scalar( $record->fields ) ) },
278 my $enc = substr($record->leader, 17, 1) || 'u';
279 my %levels = ( ' ' => 9, 1 => 8, 2 => 7, 3 => 6, 4 => 5, 5 => 4,
280 6 => 3, 7 => 2, 8 => 1, 'u' => 0, 'z' => 0 );
281 return $levels{$enc} || 0;
285 #----------------------------------
286 # assemble and store scores
287 #----------------------------------
288 for ( @{ $conf->{dyn_scores} } ) {
289 push @score, $scores_code{$_}->($marc, $record);
290 $json .= $_ . ':' . $score[-1] . ',';
292 $json .= 'misc:' . $marc->{misc_score} . '}';
294 my $compact = join('', $marc->{age_score}, $marc->{misc_score}, @score);
295 $marc->{score} = "$compact\t$json";
298 =head2 dump_fingerprints
302 sub dump_fingerprints {
305 if ($conf->{fingerprints}{baseline}) {
306 print OF join("\t", $marc->{score}, $marc->{id}, 'baseline',
307 $marc->{item_form}, $marc->{date1}, $marc->{record_type},
308 $marc->{bib_lvl}, $marc->{title}), "\n";
311 if ($conf->{fingerprints}{oclc} and scalar @{$marc->{oclc} }) {
312 for (@{$marc->{oclc} }) {
313 print OF join("\t", $marc->{score}, $marc->{id}, "oclc",
314 $marc->{item_form}, $marc->{date1},
315 $marc->{record_type}, $marc->{bib_lvl},
316 $marc->{title}, $_, "\n");
320 if ($conf->{fingerprints}{isbn}) {
321 if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
322 foreach my $isbn ( @{ $marc->{isbns}} ) {
323 print OF join("\t", $marc->{score}, $marc->{id}, "isbn",
324 $marc->{item_form}, $marc->{date1},
325 $marc->{record_type},
326 $marc->{bib_lvl}, $marc->{title},
327 $isbn, $marc->{pages}), "\n";
332 if ($conf->{fingerprints}{edition} and $marc->{edition}) {
333 print OF join("\t", $marc->{score}, $marc->{id}, "edition",
334 $marc->{item_form}, $marc->{date1},
335 $marc->{record_type}, $marc->{bib_lvl},
336 $marc->{title}, $marc->{edition}), "\n";
339 if ($conf->{fingerprints}{issn} and $marc->{issn}) {
340 print OF join("\t", $marc->{score}, $marc->{id}, "issn",
341 $marc->{item_form}, $marc->{date1},
342 $marc->{record_type}, $marc->{bib_lvl},
343 $marc->{title}, $marc->{issn}), "\n";
346 if ($conf->{fingerprints}{lccn} and $marc->{lccn}) {
347 print OF join("\t", $marc->{score}, $marc->{id}, "lccn",
348 $marc->{item_form}, $marc->{date1},
349 $marc->{record_type}, $marc->{bib_lvl},
350 $marc->{title}, $marc->{lccn}) ,"\n";
353 if ($conf->{fingerprints}{accomp} and $marc->{accomp}) {
354 print OF join("\t", $marc->{score}, $marc->{id}, "accomp",
355 $marc->{item_form}, $marc->{date1},
356 $marc->{record_type}, $marc->{bib_lvl},
357 $marc->{title}, $marc->{accomp}) ,"\n";
360 if ($conf->{fingerprints}{authpub} and $marc->{author} and
361 $marc->{publisher} and $marc->{pubyear} and $marc->{pages}) {
362 print OF join("\t", $marc->{score}, $marc->{id}, "authpub",
363 $marc->{item_form}, $marc->{date1},
364 $marc->{record_type}, $marc->{bib_lvl},
365 $marc->{title}, $marc->{author},
366 $marc->{publisher}, $marc->{pubyear},
367 $marc->{pages}), "\n";
373 =head2 dump_exception
375 Write line of exception report
380 my ($marc, $msg) = @_;
381 unless (defined $marc) {
382 print XF "Undefined record at line $count; likely bad XML\n";
386 print XF "Record ", $marc->{id}, " excluded: ";
392 print XF "missing item_form; " unless ($marc->{item_form});
393 unless (defined $marc->{date1})
394 { print XF "missing date1; " }
396 { print XF "invalid date1: '", $marc->{date1}, "'; "
397 unless ($marc->{date1} =~ /\d{4}/); }
398 print XF "missing record_type; " unless ($marc->{record_type});
399 print XF "missing bib_lvl; " unless ($marc->{bib_lvl});
400 print XF "missing title " unless ($marc->{title});
405 =head2 this_record_is_excluded
407 Returns 1 if the record B<is> and 0 if the record B<is not> excluded,
408 according to the subfield mapping (generated via the C<--excludelist>
413 sub this_record_is_excluded {
414 my ($rec, $marc) = @_;
415 return 0 unless defined $conf->{excludelist};
417 for my $tag (keys %{ $conf->{excludelist}->{tags} }) {
418 for my $sub (keys %{$conf->{excludelist}->{tags}{$tag}}) {
419 my $f = $conf->{excludelist}->field($tag, $sub);
421 # if this record doesn't have the right tag/sub, it can't be
422 return 0 unless ($rec->field($tag) and $rec->field($tag)->subfield($sub));
423 # but it does, so if there are no filters to check...
424 unless ($conf->{excludelist}->filters($f))
425 { dump_exception($marc, "exclusion $tag$sub"); return 1 }
427 my $sub_contents = $rec->field($tag)->subfield($sub);
428 for my $filter (@{ $conf->{excludelist}->filters($f)}) {
429 if ($sub_contents =~ /$filter/i) {
430 # filter matches. no fp.
431 dump_exception($marc, "exclusion $tag$sub '$filter'");
434 # no match, no exclude
443 Performs boring script initialization. Handles argument parsing,
452 # set mode on existing filehandles
453 binmode(STDIN, ':utf8');
455 my $rc = GetOptions( $c,
464 'arbitrarily-lose-above=i',
465 'arbitrarily-lose-below=i',
471 show_help() unless $rc;
472 show_help() if ($c->{help});
474 # check fingerprints list for validity
475 if ($c->{fingerprints}) {
477 my %valid_fps = ( oclc => 1, isbn => 1, issn => 1, lccn => 1,
478 edition => 1, accomp => 1, authpub => 1,
479 baseline => 1, crap => 1,
481 for (split /,/, $c->{fingerprints}) {
482 die "Invalid fingerprint '$_'\n" unless $valid_fps{$_};
485 $c->{fingerprints} = \%fps
487 $c->{fingerprints} = {oclc => 1, isbn => 1, edition => 1, issn => 1,
488 lccn => 1, accomp => 1, authpub => 1};
491 # check scores list for validity
494 my %valid_scores = ( oclc => 1, dlc => 1, num_650 => 1,
495 num_tags => 1, enc_lvl => 1,
497 for (split /,/, $c->{scores}) {
498 die "Invalid score mode '$_'\n" unless $valid_scores{$_};
501 $c->{dyn_scores} = [split /,/, $c->{scores}];
502 $c->{scores} = \%scores;
504 $c->{scores} = {oclc => 1, dlc => 1, num_650 => 1,
505 num_tags => 1, enc_lvl => 1};
506 $c->{dyn_scores} = [ qw/oclc dlc num_650 num_tags enc_lvl/ ];
510 $c->{tag} = 903 unless defined $c->{tag};
511 $c->{subfield} = 'a' unless defined $c->{subfield};
512 $c->{marctype} = 'XML' unless defined $c->{marctype};
514 $c->{output} = join('.',$c->{prefix},'fp');
515 $c->{exception} = join('.',$c->{prefix},'fp','ex');
518 # get SFM object if excludelist was specified
519 if ($c->{excludelist}) {
521 Equinox::Migration::SubfieldMapper->new( file => $c->{excludelist} );
524 my @keys = keys %{$c};
525 show_help() unless (@ARGV and @keys);
526 for my $key ('tag', 'subfield', 'output', 'exception')
527 { push @missing, $key unless $c->{$key} }
529 print "Required option: ", join(', ', @missing), " missing!\n";
535 =head2 progress_ticker
539 sub progress_ticker {
540 return if $conf->{quiet};
541 printf("\r> %d recs seen; %d processed", $count, $scount);
542 printf(" (%d/s)", ($count / (time - $start + 1)))
543 if ($count % 500 == 0);
548 Display usage message when things go wrong
554 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
556 --output=<FILE> -o Output filename
557 --exceptions=<FILE> -x Exception report filename
559 --prefix=<PREFIX>> -p Shared prefix for output/exception files. Will
560 produce PREFIX.fp and PREFIX.fp.ex
562 --tag=N -t Which tag to use (default 903)
563 --subfield=X -s Which subfield to use (default 'a')
564 --quiet -q Don't write status messages to STDOUT
566 --fingerprints=LIST Fingerprints to generate, comma separated
567 Default: oclc,isbn,edition,issn,lccn,accomp,authpub
569 --excludelist=FILE Name of fingerprints exclusions file
571 --scores=LIST Scores to calculate, comma separated
572 Default: oclc,dlc,num_650,num_tags,enc_level
573 --newwins New record IDs score higher (default is old wins)
574 --arbitrarily-lose-above
575 --arbitrarily-lose-below
576 --arbitrarily-decrease-score-by
577 Modify fingerprint scoring of records whose EG id is above or below a
578 given value, inclusive (so 5 is <= 5 or >= 5) such that they lose.
580 --marctype=TYPE Defaults to 'XML'