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 if ($my_260 and $my_260->subfield('c')) {
92 my $date1 = $my_260->subfield('c');
94 if (defined $date1 and $date1 =~ /\d{4}/) {
95 $marc{date1} = $date1;
97 print XF ">> using 260c as date1 at rec $count\n";
103 if ( $marc{record_type} =~ /[gkroef]/ ) { # MAP, VIS
104 $marc{item_form} = substr($marc{tag008},29,1) if ($marc{tag008});
106 $marc{item_form} = substr($marc{tag008},23,1) if ($marc{tag008});
110 my @isbns = $record->field('020') if $record->field('020');
111 push @isbns, $record->field('024') if $record->field('024');
112 for my $f ( @isbns ) {
113 push @{ $marc{isbns} }, $1 if ( defined $f->subfield('a') and
114 $f->subfield('a')=~/(\S+)/ );
118 for my $rec_field (100, 110, 111) {
119 if ($record->field($rec_field)) {
120 $marc{author} = $record->field($rec_field)->subfield('a');
127 push @{ $marc{oclc} }, $record->field('001')->as_string()
128 if ($record->field('001') and $record->field('003') and
129 $record->field('003')->as_string() =~ /OCo{0,1}LC/);
130 for ($record->field('035')) {
131 my $oclc = $_->subfield('a');
132 push @{ $marc{oclc} }, $oclc
133 if (defined $oclc and $oclc =~ /\(OCoLC\)/ and $oclc =~/([0-9]+)/);
136 # "Accompanying material" and check for "copy" (300)
137 if ($record->field('300')) {
138 $marc{accomp} = $record->field('300')->subfield('e');
139 $marc{tag300a} = $record->field('300')->subfield('a');
142 # issn, lccn, title, desc, pages, pub, pubyear, edition
143 $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
144 $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
145 $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
146 $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
147 $marc{title} = $record->field('245')->subfield('a')
148 if $record->field('245');
149 $marc{edition} = $record->field('250')->subfield('a')
150 if $record->field('250');
151 if ($record->field('260')) {
152 $marc{publisher} = $record->field('260')->subfield('b');
153 $marc{pubyear} = $record->field('260')->subfield('c');
155 (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
162 =head2 normalize_marc
164 Gently massages your data.
171 $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
172 if ($marc->{title}) {
173 $marc->{title} = NFD($marc->{title});
174 $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
175 $marc->{title} = lc($marc->{title});
176 $marc->{title} =~ s/\W+$//go;
178 if ($marc->{author}) {
179 $marc->{author} = NFD($marc->{author});
180 $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
181 $marc->{author} = lc($marc->{author});
182 $marc->{author} =~ s/\W+$//go;
183 if ($marc->{author} =~ /^(\w+)/) {
184 $marc->{author} = $1;
187 if ($marc->{publisher}) {
188 $marc->{publisher} = NFD($marc->{publisher});
189 $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
190 $marc->{publisher} = lc($marc->{publisher});
191 $marc->{publisher} =~ s/\W+$//go;
192 if ($marc->{publisher} =~ /^(\w+)/) {
193 $marc->{publisher} = $1;
203 Checks MARC record to see if neccessary fingerprinting data is
210 return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
211 $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
218 Assign a score to the record based on various criteria.
220 Score is constructed by pushing elements onto a list, via a dispatch
221 table. This allows order of fingerprints in the output file to be
227 my ($marc, $record) = @_;
231 #----------------------------------
232 # static criteria scoring
233 #----------------------------------
234 $marc->{misc_score} = 999;
235 $marc->{age_score} = 999999999999;
237 # -1 if 008 has been padded, -2 if it doesn't exist
239 { $marc->{misc_score}-- if ($marc->{tag008} =~ /\|$/) }
241 { $marc->{misc_score} -= 2 }
242 # -1 if date has been pulled from 260
243 $marc->{misc_score}-- if $marc->{fudgedate};
244 # -1 if this is a copy record
245 $marc->{misc_score}--
246 if (defined $marc->{tag300a} and $marc->{tag300a} =~ /copy/i);
248 # subtract record id if we want older records to win
249 #$marc->{age_score} -= $marc->{id} unless ($conf->{newwins});
250 # handle arbitrary adjustments
251 $marc->{age_score} = 1;
252 if ($conf->{'arbitrarily-lose-above'}) {
253 $marc->{age_score} = 0
254 if ($marc->{id} >= $conf->{'arbitrarily-lose-above'});
256 if ($conf->{'arbitrarily-lose-below'}) {
257 $marc->{age_score} = 0
258 if ($marc->{id} <= $conf->{'arbitrarily-lose-below'});
261 #----------------------------------
262 # dynamic calculated scoring
263 #----------------------------------
265 oclc => sub { return $marc->{oclc}[0] ? 1 : 0 },
267 if ($record->field('040') and $record->field('040')->subfield('a'))
268 { return scalar($record->subfield( '040', 'a')) =~ /dlc/io ? 1 : 0 }
272 if ($record->field('650')) {
273 # can't say "scalar $record->field('650')"; MARC::Record
274 # behaves differently in list/scalar contexts
275 my @tags = $record->field('650');
276 return sprintf("%04d", scalar @tags)
277 } else { return '0000' }
279 num_tags=> sub { return sprintf( '%04d', scalar( $record->fields ) ) },
281 my $enc = substr($record->leader, 17, 1) || 'u';
282 my %levels = ( ' ' => 9, 1 => 8, 2 => 7, 3 => 6, 4 => 5, 5 => 4,
283 6 => 3, 7 => 2, 8 => 1, 'u' => 0, 'z' => 0 );
284 return $levels{$enc} || 0;
288 #----------------------------------
289 # assemble and store scores
290 #----------------------------------
291 for ( @{ $conf->{dyn_scores} } ) {
292 push @score, $scores_code{$_}->($marc, $record);
293 $json .= $_ . ':' . $score[-1] . ',';
295 $json .= 'misc:' . $marc->{misc_score} . '}';
297 my $compact = join('', $marc->{age_score}, $marc->{misc_score}, @score);
298 $marc->{score} = "$compact\t$json";
301 =head2 dump_fingerprints
305 sub dump_fingerprints {
308 if ($conf->{fingerprints}{baseline}) {
309 print OF join("\t", $marc->{score}, $marc->{id}, 'baseline',
310 $marc->{item_form}, $marc->{date1}, $marc->{record_type},
311 $marc->{bib_lvl}, $marc->{title}), "\n";
314 if ($conf->{fingerprints}{oclc} and scalar @{$marc->{oclc} }) {
315 for (@{$marc->{oclc} }) {
316 print OF join("\t", $marc->{score}, $marc->{id}, "oclc",
317 $marc->{item_form}, $marc->{date1},
318 $marc->{record_type}, $marc->{bib_lvl},
319 $marc->{title}, $_, "\n");
323 if ($conf->{fingerprints}{isbn}) {
324 if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
325 foreach my $isbn ( @{ $marc->{isbns}} ) {
326 print OF join("\t", $marc->{score}, $marc->{id}, "isbn",
327 $marc->{item_form}, $marc->{date1},
328 $marc->{record_type},
329 $marc->{bib_lvl}, $marc->{title},
330 $isbn, $marc->{pages}), "\n";
335 if ($conf->{fingerprints}{edition} and $marc->{edition}) {
336 print OF join("\t", $marc->{score}, $marc->{id}, "edition",
337 $marc->{item_form}, $marc->{date1},
338 $marc->{record_type}, $marc->{bib_lvl},
339 $marc->{title}, $marc->{edition}), "\n";
342 if ($conf->{fingerprints}{issn} and $marc->{issn}) {
343 print OF join("\t", $marc->{score}, $marc->{id}, "issn",
344 $marc->{item_form}, $marc->{date1},
345 $marc->{record_type}, $marc->{bib_lvl},
346 $marc->{title}, $marc->{issn}), "\n";
349 if ($conf->{fingerprints}{lccn} and $marc->{lccn}) {
350 print OF join("\t", $marc->{score}, $marc->{id}, "lccn",
351 $marc->{item_form}, $marc->{date1},
352 $marc->{record_type}, $marc->{bib_lvl},
353 $marc->{title}, $marc->{lccn}) ,"\n";
356 if ($conf->{fingerprints}{accomp} and $marc->{accomp}) {
357 print OF join("\t", $marc->{score}, $marc->{id}, "accomp",
358 $marc->{item_form}, $marc->{date1},
359 $marc->{record_type}, $marc->{bib_lvl},
360 $marc->{title}, $marc->{accomp}) ,"\n";
363 if ($conf->{fingerprints}{authpub} and $marc->{author} and
364 $marc->{publisher} and $marc->{pubyear} and $marc->{pages}) {
365 print OF join("\t", $marc->{score}, $marc->{id}, "authpub",
366 $marc->{item_form}, $marc->{date1},
367 $marc->{record_type}, $marc->{bib_lvl},
368 $marc->{title}, $marc->{author},
369 $marc->{publisher}, $marc->{pubyear},
370 $marc->{pages}), "\n";
376 =head2 dump_exception
378 Write line of exception report
383 my ($marc, $msg) = @_;
384 unless (defined $marc) {
385 print XF "Undefined record at line $count; likely bad XML\n";
389 print XF "Record ", $marc->{id}, " excluded: ";
395 print XF "missing item_form; " unless ($marc->{item_form});
396 unless (defined $marc->{date1})
397 { print XF "missing date1; " }
399 { print XF "invalid date1: '", $marc->{date1}, "'; "
400 unless ($marc->{date1} =~ /\d{4}/); }
401 print XF "missing record_type; " unless ($marc->{record_type});
402 print XF "missing bib_lvl; " unless ($marc->{bib_lvl});
403 print XF "missing title " unless ($marc->{title});
408 =head2 this_record_is_excluded
410 Returns 1 if the record B<is> and 0 if the record B<is not> excluded,
411 according to the subfield mapping (generated via the C<--excludelist>
416 sub this_record_is_excluded {
417 my ($rec, $marc) = @_;
418 return 0 unless defined $conf->{excludelist};
420 for my $tag (keys %{ $conf->{excludelist}->{tags} }) {
421 for my $sub (keys %{$conf->{excludelist}->{tags}{$tag}}) {
422 my $f = $conf->{excludelist}->field($tag, $sub);
424 # if this record doesn't have the right tag/sub, it can't be
425 return 0 unless ($rec->field($tag) and $rec->field($tag)->subfield($sub));
426 # but it does, so if there are no filters to check...
427 unless ($conf->{excludelist}->filters($f))
428 { dump_exception($marc, "exclusion $tag$sub"); return 1 }
430 my $sub_contents = $rec->field($tag)->subfield($sub);
431 for my $filter (@{ $conf->{excludelist}->filters($f)}) {
432 if ($sub_contents =~ /$filter/i) {
433 # filter matches. no fp.
434 dump_exception($marc, "exclusion $tag$sub '$filter'");
437 # no match, no exclude
446 Performs boring script initialization. Handles argument parsing,
455 # set mode on existing filehandles
456 binmode(STDIN, ':utf8');
458 my $rc = GetOptions( $c,
467 'arbitrarily-lose-above=i',
468 'arbitrarily-lose-below=i',
474 show_help() unless $rc;
475 show_help() if ($c->{help});
477 # check fingerprints list for validity
478 if ($c->{fingerprints}) {
480 my %valid_fps = ( oclc => 1, isbn => 1, issn => 1, lccn => 1,
481 edition => 1, accomp => 1, authpub => 1,
482 baseline => 1, crap => 1,
484 for (split /,/, $c->{fingerprints}) {
485 die "Invalid fingerprint '$_'\n" unless $valid_fps{$_};
488 $c->{fingerprints} = \%fps
490 $c->{fingerprints} = {oclc => 1, isbn => 1, edition => 1, issn => 1,
491 lccn => 1, accomp => 1, authpub => 1};
494 # check scores list for validity
497 my %valid_scores = ( oclc => 1, dlc => 1, num_650 => 1,
498 num_tags => 1, enc_lvl => 1,
500 for (split /,/, $c->{scores}) {
501 die "Invalid score mode '$_'\n" unless $valid_scores{$_};
504 $c->{dyn_scores} = [split /,/, $c->{scores}];
505 $c->{scores} = \%scores;
507 $c->{scores} = {oclc => 1, dlc => 1, num_650 => 1,
508 num_tags => 1, enc_lvl => 1};
509 $c->{dyn_scores} = [ qw/oclc dlc num_650 num_tags enc_lvl/ ];
513 $c->{tag} = 903 unless defined $c->{tag};
514 $c->{subfield} = 'a' unless defined $c->{subfield};
515 $c->{marctype} = 'XML' unless defined $c->{marctype};
517 $c->{output} = join('.',$c->{prefix},'fp');
518 $c->{exception} = join('.',$c->{prefix},'fp','ex');
521 # get SFM object if excludelist was specified
522 if ($c->{excludelist}) {
524 Equinox::Migration::SubfieldMapper->new( file => $c->{excludelist} );
527 my @keys = keys %{$c};
528 show_help() unless (@ARGV and @keys);
529 for my $key ('tag', 'subfield', 'output', 'exception')
530 { push @missing, $key unless $c->{$key} }
532 print "Required option: ", join(', ', @missing), " missing!\n";
538 =head2 progress_ticker
542 sub progress_ticker {
543 return if $conf->{quiet};
544 printf("\r> %d recs seen; %d processed", $count, $scount);
545 printf(" (%d/s)", ($count / (time - $start + 1)))
546 if ($count % 500 == 0);
551 Display usage message when things go wrong
557 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
559 --output=<FILE> -o Output filename
560 --exceptions=<FILE> -x Exception report filename
562 --prefix=<PREFIX>> -p Shared prefix for output/exception files. Will
563 produce PREFIX.fp and PREFIX.fp.ex
565 --tag=N -t Which tag to use (default 903)
566 --subfield=X -s Which subfield to use (default 'a')
567 --quiet -q Don't write status messages to STDOUT
569 --fingerprints=LIST Fingerprints to generate, comma separated
570 Default: oclc,isbn,edition,issn,lccn,accomp,authpub
572 --excludelist=FILE Name of fingerprints exclusions file
574 --scores=LIST Scores to calculate, comma separated
575 Default: oclc,dlc,num_650,num_tags,enc_level
576 --newwins New record IDs score higher (default is old wins)
577 --arbitrarily-lose-above
578 --arbitrarily-lose-below
579 --arbitrarily-decrease-score-by
580 Modify fingerprint scoring of records whose EG id is above or below a
581 given value, inclusive (so 5 is <= 5 or >= 5) such that they lose.
583 --marctype=TYPE Defaults to 'XML'