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 if ($record->field('999')) {
137 my $koha_bib_id = $record->field('999')->subfield('c');
138 $marc{koha_bib_id} = $koha_bib_id if defined $koha_bib_id and $koha_bib_id =~ /^\d+$/;
141 # "Accompanying material" and check for "copy" (300)
142 if ($record->field('300')) {
143 $marc{accomp} = $record->field('300')->subfield('e');
144 $marc{tag300a} = $record->field('300')->subfield('a');
147 # issn, lccn, title, desc, pages, pub, pubyear, edition
148 $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
149 $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
150 $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
151 $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
152 $marc{title} = $record->field('245')->subfield('a')
153 if $record->field('245');
154 $marc{edition} = $record->field('250')->subfield('a')
155 if $record->field('250');
156 if ($record->field('260')) {
157 $marc{publisher} = $record->field('260')->subfield('b');
158 $marc{pubyear} = $record->field('260')->subfield('c');
160 (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
167 =head2 normalize_marc
169 Gently massages your data.
176 $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
177 if ($marc->{title}) {
178 $marc->{title} = NFD($marc->{title});
179 $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
180 $marc->{title} = lc($marc->{title});
181 $marc->{title} =~ s/\W+$//go;
183 if ($marc->{author}) {
184 $marc->{author} = NFD($marc->{author});
185 $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
186 $marc->{author} = lc($marc->{author});
187 $marc->{author} =~ s/\W+$//go;
188 if ($marc->{author} =~ /^(\w+)/) {
189 $marc->{author} = $1;
192 if ($marc->{publisher}) {
193 $marc->{publisher} = NFD($marc->{publisher});
194 $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
195 $marc->{publisher} = lc($marc->{publisher});
196 $marc->{publisher} =~ s/\W+$//go;
197 if ($marc->{publisher} =~ /^(\w+)/) {
198 $marc->{publisher} = $1;
208 Checks MARC record to see if neccessary fingerprinting data is
215 return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
216 $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
223 Assign a score to the record based on various criteria.
225 Score is constructed by pushing elements onto a list, via a dispatch
226 table. This allows order of fingerprints in the output file to be
232 my ($marc, $record) = @_;
236 #----------------------------------
237 # static criteria scoring
238 #----------------------------------
239 $marc->{misc_score} = 999;
240 $marc->{age_score} = 999999999999;
242 # -1 if 008 has been padded, -2 if it doesn't exist
244 { $marc->{misc_score}-- if ($marc->{tag008} =~ /\|$/) }
246 { $marc->{misc_score} -= 2 }
247 # -1 if date has been pulled from 260
248 $marc->{misc_score}-- if $marc->{fudgedate};
249 # -1 if this is a copy record
250 $marc->{misc_score}--
251 if (defined $marc->{tag300a} and $marc->{tag300a} =~ /copy/i);
253 # subtract record id if we want older records to win
254 #$marc->{age_score} -= $marc->{id} unless ($conf->{newwins});
255 # handle arbitrary adjustments
256 $marc->{age_score} = 1;
257 if ($conf->{'arbitrarily-lose-above'}) {
258 $marc->{age_score} = 0
259 if ($marc->{id} >= $conf->{'arbitrarily-lose-above'});
261 if ($conf->{'arbitrarily-lose-below'}) {
262 $marc->{age_score} = 0
263 if ($marc->{id} <= $conf->{'arbitrarily-lose-below'});
266 #----------------------------------
267 # dynamic calculated scoring
268 #----------------------------------
270 oclc => sub { return $marc->{oclc}[0] ? 1 : 0 },
272 if ($record->field('040') and $record->field('040')->subfield('a'))
273 { return scalar($record->subfield( '040', 'a')) =~ /dlc/io ? 1 : 0 }
277 if ($record->field('650')) {
278 # can't say "scalar $record->field('650')"; MARC::Record
279 # behaves differently in list/scalar contexts
280 my @tags = $record->field('650');
281 return sprintf("%04d", scalar @tags)
282 } else { return '0000' }
284 num_tags=> sub { return sprintf( '%04d', scalar( $record->fields ) ) },
286 my $enc = substr($record->leader, 17, 1) || 'u';
287 my %levels = ( ' ' => 9, 1 => 8, 2 => 7, 3 => 6, 4 => 5, 5 => 4,
288 6 => 3, 7 => 2, 8 => 1, 'u' => 0, 'z' => 0 );
289 return $levels{$enc} || 0;
293 #----------------------------------
294 # assemble and store scores
295 #----------------------------------
296 for ( @{ $conf->{dyn_scores} } ) {
297 push @score, $scores_code{$_}->($marc, $record);
298 $json .= $_ . ':' . $score[-1] . ',';
300 $json .= 'misc:' . $marc->{misc_score} . '}';
302 my $compact = join('', $marc->{age_score}, $marc->{misc_score}, @score);
303 $marc->{score} = "$compact\t$json";
306 =head2 dump_fingerprints
310 sub dump_fingerprints {
313 if ($conf->{fingerprints}{baseline}) {
314 print OF join("\t", $marc->{score}, $marc->{id}, 'baseline',
315 $marc->{item_form}, $marc->{date1}, $marc->{record_type},
316 $marc->{bib_lvl}, $marc->{title}), "\n";
319 if ($conf->{fingerprints}{oclc} and scalar @{$marc->{oclc} }) {
320 for (@{$marc->{oclc} }) {
321 print OF join("\t", $marc->{score}, $marc->{id}, "oclc",
322 $marc->{item_form}, $marc->{date1},
323 $marc->{record_type}, $marc->{bib_lvl},
324 $marc->{title}, $_, "\n");
328 if ($conf->{fingerprints}{koha_bib_id}) {
329 print OF join("\t", $marc->{score}, $marc->{id}, "z_koha_bib_id",
330 $marc->{item_form}, $marc->{date1},
331 $marc->{record_type},
332 $marc->{bib_lvl}, $marc->{title},
333 $marc->{koha_bib_id}), "\n";
336 if ($conf->{fingerprints}{isbn}) {
337 if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
338 foreach my $isbn ( @{ $marc->{isbns}} ) {
339 print OF join("\t", $marc->{score}, $marc->{id}, "isbn",
340 $marc->{item_form}, $marc->{date1},
341 $marc->{record_type},
342 $marc->{bib_lvl}, $marc->{title},
343 $isbn, $marc->{pages}), "\n";
348 if ($conf->{fingerprints}{edition} and $marc->{edition}) {
349 print OF join("\t", $marc->{score}, $marc->{id}, "edition",
350 $marc->{item_form}, $marc->{date1},
351 $marc->{record_type}, $marc->{bib_lvl},
352 $marc->{title}, $marc->{edition}), "\n";
355 if ($conf->{fingerprints}{issn} and $marc->{issn}) {
356 print OF join("\t", $marc->{score}, $marc->{id}, "issn",
357 $marc->{item_form}, $marc->{date1},
358 $marc->{record_type}, $marc->{bib_lvl},
359 $marc->{title}, $marc->{issn}), "\n";
362 if ($conf->{fingerprints}{lccn} and $marc->{lccn}) {
363 print OF join("\t", $marc->{score}, $marc->{id}, "lccn",
364 $marc->{item_form}, $marc->{date1},
365 $marc->{record_type}, $marc->{bib_lvl},
366 $marc->{title}, $marc->{lccn}) ,"\n";
369 if ($conf->{fingerprints}{accomp} and $marc->{accomp}) {
370 print OF join("\t", $marc->{score}, $marc->{id}, "accomp",
371 $marc->{item_form}, $marc->{date1},
372 $marc->{record_type}, $marc->{bib_lvl},
373 $marc->{title}, $marc->{accomp}) ,"\n";
376 if ($conf->{fingerprints}{authpub} and $marc->{author} and
377 $marc->{publisher} and $marc->{pubyear} and $marc->{pages}) {
378 print OF join("\t", $marc->{score}, $marc->{id}, "authpub",
379 $marc->{item_form}, $marc->{date1},
380 $marc->{record_type}, $marc->{bib_lvl},
381 $marc->{title}, $marc->{author},
382 $marc->{publisher}, $marc->{pubyear},
383 $marc->{pages}), "\n";
389 =head2 dump_exception
391 Write line of exception report
396 my ($marc, $msg) = @_;
397 unless (defined $marc) {
398 print XF "Undefined record at line $count; likely bad XML\n";
402 print XF "Record ", $marc->{id}, " excluded: ";
408 print XF "missing item_form; " unless ($marc->{item_form});
409 unless (defined $marc->{date1})
410 { print XF "missing date1; " }
412 { print XF "invalid date1: '", $marc->{date1}, "'; "
413 unless ($marc->{date1} =~ /\d{4}/); }
414 print XF "missing record_type; " unless ($marc->{record_type});
415 print XF "missing bib_lvl; " unless ($marc->{bib_lvl});
416 print XF "missing title " unless ($marc->{title});
421 =head2 this_record_is_excluded
423 Returns 1 if the record B<is> and 0 if the record B<is not> excluded,
424 according to the subfield mapping (generated via the C<--excludelist>
429 sub this_record_is_excluded {
430 my ($rec, $marc) = @_;
431 return 0 unless defined $conf->{excludelist};
433 for my $tag (keys %{ $conf->{excludelist}->{tags} }) {
434 for my $sub (keys %{$conf->{excludelist}->{tags}{$tag}}) {
435 my $f = $conf->{excludelist}->field($tag, $sub);
437 # if this record doesn't have the right tag/sub, it can't be
438 return 0 unless ($rec->field($tag) and $rec->field($tag)->subfield($sub));
439 # but it does, so if there are no filters to check...
440 unless ($conf->{excludelist}->filters($f))
441 { dump_exception($marc, "exclusion $tag$sub"); return 1 }
443 my $sub_contents = $rec->field($tag)->subfield($sub);
444 for my $filter (@{ $conf->{excludelist}->filters($f)}) {
445 if ($sub_contents =~ /$filter/i) {
446 # filter matches. no fp.
447 dump_exception($marc, "exclusion $tag$sub '$filter'");
450 # no match, no exclude
459 Performs boring script initialization. Handles argument parsing,
468 # set mode on existing filehandles
469 binmode(STDIN, ':utf8');
471 my $rc = GetOptions( $c,
480 'arbitrarily-lose-above=i',
481 'arbitrarily-lose-below=i',
487 show_help() unless $rc;
488 show_help() if ($c->{help});
490 # check fingerprints list for validity
491 if ($c->{fingerprints}) {
493 my %valid_fps = ( oclc => 1, isbn => 1, issn => 1, lccn => 1,
494 edition => 1, accomp => 1, authpub => 1,
495 baseline => 1, crap => 1,
498 for (split /,/, $c->{fingerprints}) {
499 die "Invalid fingerprint '$_'\n" unless $valid_fps{$_};
502 $c->{fingerprints} = \%fps
504 $c->{fingerprints} = {oclc => 1, isbn => 1, edition => 1, issn => 1,
505 lccn => 1, accomp => 1, authpub => 1};
508 # check scores list for validity
511 my %valid_scores = ( oclc => 1, dlc => 1, num_650 => 1,
512 num_tags => 1, enc_lvl => 1,
514 for (split /,/, $c->{scores}) {
515 die "Invalid score mode '$_'\n" unless $valid_scores{$_};
518 $c->{dyn_scores} = [split /,/, $c->{scores}];
519 $c->{scores} = \%scores;
521 $c->{scores} = {oclc => 1, dlc => 1, num_650 => 1,
522 num_tags => 1, enc_lvl => 1};
523 $c->{dyn_scores} = [ qw/oclc dlc num_650 num_tags enc_lvl/ ];
527 $c->{tag} = 903 unless defined $c->{tag};
528 $c->{subfield} = 'a' unless defined $c->{subfield};
529 $c->{marctype} = 'XML' unless defined $c->{marctype};
531 $c->{output} = join('.',$c->{prefix},'fp');
532 $c->{exception} = join('.',$c->{prefix},'fp','ex');
535 # get SFM object if excludelist was specified
536 if ($c->{excludelist}) {
538 Equinox::Migration::SubfieldMapper->new( file => $c->{excludelist} );
541 my @keys = keys %{$c};
542 show_help() unless (@ARGV and @keys);
543 for my $key ('tag', 'subfield', 'output', 'exception')
544 { push @missing, $key unless $c->{$key} }
546 print "Required option: ", join(', ', @missing), " missing!\n";
552 =head2 progress_ticker
556 sub progress_ticker {
557 return if $conf->{quiet};
558 printf("\r> %d recs seen; %d processed", $count, $scount);
559 printf(" (%d/s)", ($count / (time - $start + 1)))
560 if ($count % 500 == 0);
565 Display usage message when things go wrong
571 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
573 --output=<FILE> -o Output filename
574 --exceptions=<FILE> -x Exception report filename
576 --prefix=<PREFIX>> -p Shared prefix for output/exception files. Will
577 produce PREFIX.fp and PREFIX.fp.ex
579 --tag=N -t Which tag to use (default 903)
580 --subfield=X -s Which subfield to use (default 'a')
581 --quiet -q Don't write status messages to STDOUT
583 --fingerprints=LIST Fingerprints to generate, comma separated
584 Default: oclc,isbn,edition,issn,lccn,accomp,authpub
585 Others: baseline,koha_bib_id
586 --excludelist=FILE Name of fingerprints exclusions file
588 --scores=LIST Scores to calculate, comma separated
589 Default: oclc,dlc,num_650,num_tags,enc_level
590 --newwins New record IDs score higher (default is old wins)
591 --arbitrarily-lose-above
592 --arbitrarily-lose-below
593 --arbitrarily-decrease-score-by
594 Modify fingerprint scoring of records whose EG id is above or below a
595 given value, inclusive (so 5 is <= 5 or >= 5) such that they lose.
597 --marctype=TYPE Defaults to 'XML'