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} or die "$0: cannot open output file $conf->{output}: $!\n";
20 open XF, '>', $conf->{exception} or die "$0: cannot open exception file $conf->{output}: $!\n";
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();
32 eval { $record = $batch->next; };
34 import MARC::File::XML;
35 print "skipping bad record: $@\n";
39 $count++; progress_ticker();
41 unless ( defined $record )
42 { dump_exception($marc); next; }
44 my $id = $record->field($conf->{tag});
46 print XF "ERROR: Record $count in $file is missing a ",
47 $conf->{tag}, " field.\n", $record->as_formatted(), "\n=====\n";
51 # populate and normalize marc
52 $marc = populate_marc($record, $id);
53 # check for manual exclusion
54 next if this_record_is_excluded($record, $marc);
55 normalize_marc($marc);
56 unless (marc_isvalid($marc))
57 { dump_exception($marc); next; }
59 # if everything looks good, score it and dump fingerprints
60 score_marc($marc, $record);
61 dump_fingerprints($marc);
62 $scount++; progress_ticker();
66 print "\nSuccessfully processed:\t$count\n" unless $conf->{quiet};
70 Constructs a hash containing the relevant MARC data for a record and
71 returns a reference to it.
76 my ($record, $id) = @_;
77 my %marc = (); $marc{isbns} = [];
80 $marc{id} = $id->as_string($conf->{subfield});
82 # record_type, bib_lvl
83 $marc{record_type} = substr($record->leader, 6, 1);
84 $marc{bib_lvl} = substr($record->leader, 7, 1);
87 my $my_008 = $record->field('008');
88 $marc{tag008} = $my_008->as_string() if ($my_008);
89 if (defined $marc{tag008}) {
90 unless (length $marc{tag008} == 40) {
91 $marc{tag008} = $marc{tag008} . ('|' x (40 - length($marc{tag008})));
92 print XF ">> Short 008 padded to ",length($marc{tag008})," at rec $count\n";
94 $marc{date1} = substr($marc{tag008},7,4) if ($marc{tag008});
95 $marc{date2} = substr($marc{tag008},11,4) if ($marc{tag008}); # UNUSED
97 unless ($marc{date1} and $marc{date1} =~ /\d{4}/) {
98 my $my_260 = $record->field('260');
99 if ($my_260 and $my_260->subfield('c')) {
100 my $date1 = $my_260->subfield('c');
102 if (defined $date1 and $date1 =~ /\d{4}/) {
103 $marc{date1} = $date1;
104 $marc{fudgedate} = 1;
105 print XF ">> using 260c as date1 at rec $count\n";
111 if ( $marc{record_type} =~ /[gkroef]/ ) { # MAP, VIS
112 $marc{item_form} = substr($marc{tag008},29,1) if ($marc{tag008});
114 $marc{item_form} = substr($marc{tag008},23,1) if ($marc{tag008});
118 my @isbns = $record->field('020') if $record->field('020');
119 push @isbns, $record->field('024') if $record->field('024');
120 for my $f ( @isbns ) {
121 push @{ $marc{isbns} }, $1 if ( defined $f->subfield('a') and
122 $f->subfield('a')=~/(\S+)/ );
126 for my $rec_field (100, 110, 111) {
127 if ($record->field($rec_field)) {
128 $marc{author} = $record->field($rec_field)->subfield('a');
135 push @{ $marc{oclc} }, $record->field('001')->as_string()
136 if ($record->field('001') and $record->field('003') and
137 $record->field('003')->as_string() =~ /OCo{0,1}LC/);
138 for ($record->field('035')) {
139 my $oclc = $_->subfield('a');
140 push @{ $marc{oclc} }, $oclc
141 if (defined $oclc and $oclc =~ /\(OCoLC\)/ and $oclc =~/([0-9]+)/);
144 if ($record->field('999')) {
145 my $koha_bib_id = $record->field('999')->subfield('c');
146 $marc{koha_bib_id} = $koha_bib_id if defined $koha_bib_id and $koha_bib_id =~ /^\d+$/;
149 # "Accompanying material" and check for "copy" (300)
150 if ($record->field('300')) {
151 $marc{accomp} = $record->field('300')->subfield('e');
152 $marc{tag300a} = $record->field('300')->subfield('a');
155 # issn, lccn, title, desc, pages, pub, pubyear, edition
156 $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
157 $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
158 $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
159 $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
160 $marc{title} = $record->field('245')->subfield('a')
161 if $record->field('245');
162 $marc{title} .= ' ' . $record->field('245')->subfield('b')
163 if ($record->field('245') and
164 $record->field('245')->subfield('b') and
165 not $conf->{ignoresubtitle});
166 $marc{edition} = $record->field('250')->subfield('a')
167 if $record->field('250');
168 if ($record->field('260')) {
169 $marc{publisher} = $record->field('260')->subfield('b');
170 $marc{pubyear} = $record->field('260')->subfield('c');
172 (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
179 =head2 normalize_marc
181 Gently massages your data.
188 $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
189 if ($marc->{title}) {
190 $marc->{title} = NFD($marc->{title});
191 $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
192 $marc->{title} = lc($marc->{title});
193 $marc->{title} =~ s/\W+$//go;
195 if ($marc->{author}) {
196 $marc->{author} = NFD($marc->{author});
197 $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
198 $marc->{author} = lc($marc->{author});
199 $marc->{author} =~ s/\W+$//go;
200 if ($marc->{author} =~ /^(\w+)/) {
201 $marc->{author} = $1;
204 if ($marc->{publisher}) {
205 $marc->{publisher} = NFD($marc->{publisher});
206 $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
207 $marc->{publisher} = lc($marc->{publisher});
208 $marc->{publisher} =~ s/\W+$//go;
209 if ($marc->{publisher} =~ /^(\w+)/) {
210 $marc->{publisher} = $1;
220 Checks MARC record to see if neccessary fingerprinting data is
227 return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
228 $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
235 Assign a score to the record based on various criteria.
237 Score is constructed by pushing elements onto a list, via a dispatch
238 table. This allows order of fingerprints in the output file to be
244 my ($marc, $record) = @_;
248 #----------------------------------
249 # static criteria scoring
250 #----------------------------------
251 $marc->{misc_score} = 999;
252 $marc->{age_score} = 999999999999;
254 # -1 if 008 has been padded, -2 if it doesn't exist
256 { $marc->{misc_score}-- if ($marc->{tag008} =~ /\|$/) }
258 { $marc->{misc_score} -= 2 }
259 # -1 if date has been pulled from 260
260 $marc->{misc_score}-- if $marc->{fudgedate};
261 # -1 if this is a copy record
262 $marc->{misc_score}--
263 if (defined $marc->{tag300a} and $marc->{tag300a} =~ /copy/i);
265 # subtract record id if we want older records to win
266 #$marc->{age_score} -= $marc->{id} unless ($conf->{newwins});
267 # handle arbitrary adjustments
268 $marc->{age_score} = 1;
269 if ($conf->{'arbitrarily-lose-above'}) {
270 $marc->{age_score} = 0
271 if ($marc->{id} >= $conf->{'arbitrarily-lose-above'});
273 if ($conf->{'arbitrarily-lose-below'}) {
274 $marc->{age_score} = 0
275 if ($marc->{id} <= $conf->{'arbitrarily-lose-below'});
278 #----------------------------------
279 # dynamic calculated scoring
280 #----------------------------------
282 oclc => sub { return $marc->{oclc}[0] ? 1 : 0 },
284 if ($record->field('040') and $record->field('040')->subfield('a'))
285 { return scalar($record->subfield( '040', 'a')) =~ /dlc/io ? 1 : 0 }
289 if ($record->field('650')) {
290 # can't say "scalar $record->field('650')"; MARC::Record
291 # behaves differently in list/scalar contexts
292 my @tags = $record->field('650');
293 return sprintf("%04d", scalar @tags)
294 } else { return '0000' }
296 num_tags=> sub { return sprintf( '%04d', scalar( $record->fields ) ) },
298 my $enc = substr($record->leader, 17, 1) || 'u';
299 my %levels = ( ' ' => 9, 1 => 8, 2 => 7, 3 => 6, 4 => 5, 5 => 4,
300 6 => 3, 7 => 2, 8 => 1, 'u' => 0, 'z' => 0 );
301 return $levels{$enc} || 0;
305 #----------------------------------
306 # assemble and store scores
307 #----------------------------------
308 for ( @{ $conf->{dyn_scores} } ) {
309 push @score, $scores_code{$_}->($marc, $record);
310 $json .= $_ . ':' . $score[-1] . ',';
312 $json .= 'misc:' . $marc->{misc_score} . '}';
314 my $compact = join('', $marc->{age_score}, $marc->{misc_score}, @score);
315 $marc->{score} = "$compact\t$json";
318 =head2 dump_fingerprints
322 sub dump_fingerprints {
325 if ($conf->{fingerprints}{baseline}) {
326 print OF join("\t", $marc->{score}, $marc->{id}, 'baseline',
327 $marc->{item_form}, $marc->{date1}, $marc->{record_type},
328 $marc->{bib_lvl}, $marc->{title}), "\n";
331 if ($conf->{fingerprints}{oclc} and scalar @{$marc->{oclc} }) {
332 for (@{$marc->{oclc} }) {
333 print OF join("\t", $marc->{score}, $marc->{id}, "oclc",
334 $marc->{item_form}, $marc->{date1},
335 $marc->{record_type}, $marc->{bib_lvl},
336 $marc->{title}, $_, "\n");
340 if ($conf->{fingerprints}{koha_bib_id} and exists $marc->{koha_bib_id}) {
341 print OF join("\t", $marc->{score}, $marc->{id}, "z_koha_bib_id",
342 $marc->{item_form}, $marc->{date1},
343 $marc->{record_type},
344 $marc->{bib_lvl}, $marc->{title},
345 $marc->{koha_bib_id}), "\n";
348 if ($conf->{fingerprints}{isbn}) {
349 if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
350 foreach my $isbn ( @{ $marc->{isbns}} ) {
351 print OF join("\t", $marc->{score}, $marc->{id}, "isbn",
352 $marc->{item_form}, $marc->{date1},
353 $marc->{record_type},
354 $marc->{bib_lvl}, $marc->{title},
355 $isbn, $marc->{pages}), "\n";
360 if ($conf->{fingerprints}{edition} and $marc->{edition}) {
361 print OF join("\t", $marc->{score}, $marc->{id}, "edition",
362 $marc->{item_form}, $marc->{date1},
363 $marc->{record_type}, $marc->{bib_lvl},
364 $marc->{title}, $marc->{edition}), "\n";
367 if ($conf->{fingerprints}{issn} and $marc->{issn}) {
368 print OF join("\t", $marc->{score}, $marc->{id}, "issn",
369 $marc->{item_form}, $marc->{date1},
370 $marc->{record_type}, $marc->{bib_lvl},
371 $marc->{title}, $marc->{issn}), "\n";
374 if ($conf->{fingerprints}{lccn} and $marc->{lccn}) {
375 print OF join("\t", $marc->{score}, $marc->{id}, "lccn",
376 $marc->{item_form}, $marc->{date1},
377 $marc->{record_type}, $marc->{bib_lvl},
378 $marc->{title}, $marc->{lccn}) ,"\n";
381 if ($conf->{fingerprints}{accomp} and $marc->{accomp}) {
382 print OF join("\t", $marc->{score}, $marc->{id}, "accomp",
383 $marc->{item_form}, $marc->{date1},
384 $marc->{record_type}, $marc->{bib_lvl},
385 $marc->{title}, $marc->{accomp}) ,"\n";
388 if ($conf->{fingerprints}{authpub} and $marc->{author} and
389 $marc->{publisher} and $marc->{pubyear} and $marc->{pages}) {
390 print OF join("\t", $marc->{score}, $marc->{id}, "authpub",
391 $marc->{item_form}, $marc->{date1},
392 $marc->{record_type}, $marc->{bib_lvl},
393 $marc->{title}, $marc->{author},
394 $marc->{publisher}, $marc->{pubyear},
395 $marc->{pages}), "\n";
401 =head2 dump_exception
403 Write line of exception report
408 my ($marc, $msg) = @_;
409 unless (defined $marc) {
410 print XF "Undefined record at line $count; likely bad XML\n";
414 print XF "Record ", $marc->{id}, " excluded: ";
420 print XF "missing item_form; " unless ($marc->{item_form});
421 unless (defined $marc->{date1})
422 { print XF "missing date1; " }
424 { print XF "invalid date1: '", $marc->{date1}, "'; "
425 unless ($marc->{date1} =~ /\d{4}/); }
426 print XF "missing record_type; " unless ($marc->{record_type});
427 print XF "missing bib_lvl; " unless ($marc->{bib_lvl});
428 print XF "missing title " unless ($marc->{title});
433 =head2 this_record_is_excluded
435 Returns 1 if the record B<is> and 0 if the record B<is not> excluded,
436 according to the subfield mapping (generated via the C<--excludelist>
441 sub this_record_is_excluded {
442 my ($rec, $marc) = @_;
443 return 0 unless defined $conf->{excludelist};
445 for my $tag (keys %{ $conf->{excludelist}->{tags} }) {
446 for my $sub (keys %{$conf->{excludelist}->{tags}{$tag}}) {
447 my $f = $conf->{excludelist}->field($tag, $sub);
449 # if this record doesn't have the right tag/sub, it can't be
450 return 0 unless ($rec->field($tag) and $rec->field($tag)->subfield($sub));
451 # but it does, so if there are no filters to check...
452 unless ($conf->{excludelist}->filters($f))
453 { dump_exception($marc, "exclusion $tag$sub"); return 1 }
455 my $sub_contents = $rec->field($tag)->subfield($sub);
456 for my $filter (@{ $conf->{excludelist}->filters($f)}) {
457 if ($sub_contents =~ /$filter/i) {
458 # filter matches. no fp.
459 dump_exception($marc, "exclusion $tag$sub '$filter'");
462 # no match, no exclude
471 Performs boring script initialization. Handles argument parsing,
480 # set mode on existing filehandles
481 binmode(STDIN, ':utf8');
483 my $rc = GetOptions( $c,
492 'arbitrarily-lose-above=i',
493 'arbitrarily-lose-below=i',
500 show_help() unless $rc;
501 show_help() if ($c->{help});
503 # check fingerprints list for validity
504 if ($c->{fingerprints}) {
506 my %valid_fps = ( oclc => 1, isbn => 1, issn => 1, lccn => 1,
507 edition => 1, accomp => 1, authpub => 1,
508 baseline => 1, crap => 1,
511 for (split /,/, $c->{fingerprints}) {
512 die "Invalid fingerprint '$_'\n" unless $valid_fps{$_};
515 $c->{fingerprints} = \%fps
517 $c->{fingerprints} = {oclc => 1, isbn => 1, edition => 1, issn => 1,
518 lccn => 1, accomp => 1, authpub => 1};
521 # check scores list for validity
524 my %valid_scores = ( oclc => 1, dlc => 1, num_650 => 1,
525 num_tags => 1, enc_lvl => 1,
527 for (split /,/, $c->{scores}) {
528 die "Invalid score mode '$_'\n" unless $valid_scores{$_};
531 $c->{dyn_scores} = [split /,/, $c->{scores}];
532 $c->{scores} = \%scores;
534 $c->{scores} = {oclc => 1, dlc => 1, num_650 => 1,
535 num_tags => 1, enc_lvl => 1};
536 $c->{dyn_scores} = [ qw/oclc dlc num_650 num_tags enc_lvl/ ];
540 $c->{tag} = 903 unless defined $c->{tag};
541 $c->{subfield} = 'a' unless defined $c->{subfield};
542 $c->{marctype} = 'XML' unless defined $c->{marctype};
544 $c->{output} = join('.',$c->{prefix},'fp');
545 $c->{exception} = join('.',$c->{prefix},'fp','ex');
548 # get SFM object if excludelist was specified
549 if ($c->{excludelist}) {
551 Equinox::Migration::SubfieldMapper->new( file => $c->{excludelist} );
554 my @keys = keys %{$c};
555 show_help() unless (@ARGV and @keys);
556 for my $key ('tag', 'subfield', 'output', 'exception')
557 { push @missing, $key unless $c->{$key} }
559 print "Required option: ", join(', ', @missing), " missing!\n";
565 =head2 progress_ticker
569 sub progress_ticker {
570 return if $conf->{quiet};
571 printf("\r> %d recs seen; %d processed", $count, $scount);
572 printf(" (%d/s)", ($count / (time - $start + 1)))
573 if ($count % 500 == 0);
578 Display usage message when things go wrong
584 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
586 --output=<FILE> -o Output filename
587 --exceptions=<FILE> -x Exception report filename
589 --prefix=<PREFIX>> -p Shared prefix for output/exception files. Will
590 produce PREFIX.fp and PREFIX.fp.ex
592 --tag=N -t Which tag to use (default 903)
593 --subfield=X -s Which subfield to use (default 'a')
594 --quiet -q Don't write status messages to STDOUT
595 --ignoresubtitle -i Ignore 245$b and construct the title from 245$a alone.
597 --fingerprints=LIST Fingerprints to generate, comma separated
598 Default: oclc,isbn,edition,issn,lccn,accomp,authpub
599 Others: baseline,koha_bib_id
600 --excludelist=FILE Name of fingerprints exclusions file
602 --scores=LIST Scores to calculate, comma separated
603 Default: oclc,dlc,num_650,num_tags,enc_level
604 --newwins New record IDs score higher (default is old wins)
605 --arbitrarily-lose-above
606 --arbitrarily-lose-below
607 --arbitrarily-decrease-score-by
608 Modify fingerprint scoring of records whose EG id is above or below a
609 given value, inclusive (so 5 is <= 5 or >= 5) such that they lose.
611 --marctype=TYPE Defaults to 'XML'