3 # Copyright 2009-2012, Equinox Software, Inc.
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 use Unicode::Normalize;
26 use MARC::File::XML ( BinaryEncoding => 'utf-8' );
27 use Equinox::Migration::SubfieldMapper;
29 my $conf = {}; # configuration hashref
30 my $count = 0; my $scount = 0;
36 open OF, '>', $conf->{output} or die "$0: cannot open output file $conf->{output}: $!\n";
37 open XF, '>', $conf->{exception} or die "$0: cannot open exception file $conf->{output}: $!\n";
39 for my $file (@ARGV) {
40 print XF "Processing $file\n";
41 my $batch = undef; my $record = undef;
43 $batch = MARC::Batch->new($conf->{marctype}, $file);
45 $batch->warnings_off();
49 eval { $record = $batch->next; };
51 import MARC::File::XML;
52 print "skipping bad record: $@\n";
56 $count++; progress_ticker();
58 unless ( defined $record )
59 { dump_exception($marc); next; }
61 my $id = $record->field($conf->{tag});
63 print XF "ERROR: Record $count in $file is missing a ",
64 $conf->{tag}, " field.\n", $record->as_formatted(), "\n=====\n";
68 # populate and normalize marc
69 $marc = populate_marc($record, $id);
70 # check for manual exclusion
71 next if this_record_is_excluded($record, $marc);
72 normalize_marc($marc);
73 unless (marc_isvalid($marc))
74 { dump_exception($marc); next; }
76 # if everything looks good, score it and dump fingerprints
77 score_marc($marc, $record);
78 dump_fingerprints($marc);
79 $scount++; progress_ticker();
83 print "\nSuccessfully processed:\t$count\n" unless $conf->{quiet};
87 Constructs a hash containing the relevant MARC data for a record and
88 returns a reference to it.
93 my ($record, $id) = @_;
94 my %marc = (); $marc{isbns} = [];
97 $marc{id} = $id->as_string($conf->{subfield});
99 # record_type, bib_lvl
100 $marc{record_type} = substr($record->leader, 6, 1);
101 $marc{bib_lvl} = substr($record->leader, 7, 1);
104 my $my_008 = $record->field('008');
105 $marc{tag008} = $my_008->as_string() if ($my_008);
106 if (defined $marc{tag008}) {
107 unless (length $marc{tag008} == 40) {
108 $marc{tag008} = $marc{tag008} . ('|' x (40 - length($marc{tag008})));
109 print XF ">> Short 008 padded to ",length($marc{tag008})," at rec $count\n";
111 $marc{date1} = substr($marc{tag008},7,4) if ($marc{tag008});
112 $marc{date2} = substr($marc{tag008},11,4) if ($marc{tag008}); # UNUSED
114 unless ($marc{date1} and $marc{date1} =~ /\d{4}/) {
115 my $my_260 = $record->field('260');
116 if ($my_260 and $my_260->subfield('c')) {
117 my $date1 = $my_260->subfield('c');
119 if (defined $date1 and $date1 =~ /\d{4}/) {
120 $marc{date1} = $date1;
121 $marc{fudgedate} = 1;
122 print XF ">> using 260c as date1 at rec $count\n";
128 if ( $marc{record_type} =~ /[gkroef]/ ) { # MAP, VIS
129 $marc{item_form} = substr($marc{tag008},29,1) if ($marc{tag008});
131 $marc{item_form} = substr($marc{tag008},23,1) if ($marc{tag008});
135 my @isbns = $record->field('020') if $record->field('020');
136 push @isbns, $record->field('024') if $record->field('024');
137 for my $f ( @isbns ) {
138 push @{ $marc{isbns} }, $1 if ( defined $f->subfield('a') and
139 $f->subfield('a')=~/(\S+)/ );
143 for my $rec_field (100, 110, 111) {
144 if ($record->field($rec_field)) {
145 $marc{author} = $record->field($rec_field)->subfield('a');
152 push @{ $marc{oclc} }, $record->field('001')->as_string()
153 if ($record->field('001') and $record->field('003') and
154 $record->field('003')->as_string() =~ /OCo{0,1}LC/);
155 for ($record->field('035')) {
156 my $oclc = $_->subfield('a');
157 push @{ $marc{oclc} }, $oclc
158 if (defined $oclc and $oclc =~ /\(OCoLC\)/ and $oclc =~/([0-9]+)/);
161 if ($record->field('999')) {
162 my $koha_bib_id = $record->field('999')->subfield('c');
163 $marc{koha_bib_id} = $koha_bib_id if defined $koha_bib_id and $koha_bib_id =~ /^\d+$/;
166 # "Accompanying material" and check for "copy" (300)
167 if ($record->field('300')) {
168 $marc{accomp} = $record->field('300')->subfield('e');
169 $marc{tag300a} = $record->field('300')->subfield('a');
172 # issn, lccn, title, desc, pages, pub, pubyear, edition
173 $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
174 $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
175 $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
176 $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
177 $marc{title} = $record->field('245')->subfield('a')
178 if $record->field('245');
179 $marc{title} .= ' ' . $record->field('245')->subfield('b')
180 if ($record->field('245') and
181 $record->field('245')->subfield('b') and
182 not $conf->{ignoresubtitle});
183 $marc{edition} = $record->field('250')->subfield('a')
184 if $record->field('250');
185 if ($record->field('260')) {
186 $marc{publisher} = $record->field('260')->subfield('b');
187 $marc{pubyear} = $record->field('260')->subfield('c');
189 (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
196 =head2 normalize_marc
198 Gently massages your data.
205 $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
206 if ($marc->{title}) {
207 $marc->{title} = NFD($marc->{title});
208 $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
209 $marc->{title} = lc($marc->{title});
210 $marc->{title} =~ s/\W+$//go;
212 if ($marc->{author}) {
213 $marc->{author} = NFD($marc->{author});
214 $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
215 $marc->{author} = lc($marc->{author});
216 $marc->{author} =~ s/\W+$//go;
217 if ($marc->{author} =~ /^(\w+)/) {
218 $marc->{author} = $1;
221 if ($marc->{publisher}) {
222 $marc->{publisher} = NFD($marc->{publisher});
223 $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
224 $marc->{publisher} = lc($marc->{publisher});
225 $marc->{publisher} =~ s/\W+$//go;
226 if ($marc->{publisher} =~ /^(\w+)/) {
227 $marc->{publisher} = $1;
237 Checks MARC record to see if neccessary fingerprinting data is
244 return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
245 $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
252 Assign a score to the record based on various criteria.
254 Score is constructed by pushing elements onto a list, via a dispatch
255 table. This allows order of fingerprints in the output file to be
261 my ($marc, $record) = @_;
265 #----------------------------------
266 # static criteria scoring
267 #----------------------------------
268 $marc->{misc_score} = 999;
269 $marc->{age_score} = 999999999999;
271 # -1 if 008 has been padded, -2 if it doesn't exist
273 { $marc->{misc_score}-- if ($marc->{tag008} =~ /\|$/) }
275 { $marc->{misc_score} -= 2 }
276 # -1 if date has been pulled from 260
277 $marc->{misc_score}-- if $marc->{fudgedate};
278 # -1 if this is a copy record
279 $marc->{misc_score}--
280 if (defined $marc->{tag300a} and $marc->{tag300a} =~ /copy/i);
282 # subtract record id if we want older records to win
283 #$marc->{age_score} -= $marc->{id} unless ($conf->{newwins});
284 # handle arbitrary adjustments
285 $marc->{age_score} = 1;
286 if ($conf->{'arbitrarily-lose-above'}) {
287 $marc->{age_score} = 0
288 if ($marc->{id} >= $conf->{'arbitrarily-lose-above'});
290 if ($conf->{'arbitrarily-lose-below'}) {
291 $marc->{age_score} = 0
292 if ($marc->{id} <= $conf->{'arbitrarily-lose-below'});
295 #----------------------------------
296 # dynamic calculated scoring
297 #----------------------------------
299 oclc => sub { return $marc->{oclc}[0] ? 1 : 0 },
301 if ($record->field('040') and $record->field('040')->subfield('a'))
302 { return scalar($record->subfield( '040', 'a')) =~ /dlc/io ? 1 : 0 }
306 if ($record->field('650')) {
307 # can't say "scalar $record->field('650')"; MARC::Record
308 # behaves differently in list/scalar contexts
309 my @tags = $record->field('650');
310 return sprintf("%04d", scalar @tags)
311 } else { return '0000' }
313 num_tags=> sub { return sprintf( '%04d', scalar( $record->fields ) ) },
315 my $enc = substr($record->leader, 17, 1) || 'u';
316 my %levels = ( ' ' => 9, 1 => 8, 2 => 7, 3 => 6, 4 => 5, 5 => 4,
317 6 => 3, 7 => 2, 8 => 1, 'u' => 0, 'z' => 0 );
318 return $levels{$enc} || 0;
322 #----------------------------------
323 # assemble and store scores
324 #----------------------------------
325 for ( @{ $conf->{dyn_scores} } ) {
326 push @score, $scores_code{$_}->($marc, $record);
327 $json .= $_ . ':' . $score[-1] . ',';
329 $json .= 'misc:' . $marc->{misc_score} . '}';
331 my $compact = join('', $marc->{age_score}, $marc->{misc_score}, @score);
332 $marc->{score} = "$compact\t$json";
335 =head2 dump_fingerprints
339 sub dump_fingerprints {
342 if ($conf->{fingerprints}{baseline}) {
343 print OF join("\t", $marc->{score}, $marc->{id}, 'baseline',
344 $marc->{item_form}, $marc->{date1}, $marc->{record_type},
345 $marc->{bib_lvl}, $marc->{title}), "\n";
348 if ($conf->{fingerprints}{oclc} and scalar @{$marc->{oclc} }) {
349 for (@{$marc->{oclc} }) {
350 print OF join("\t", $marc->{score}, $marc->{id}, "oclc",
351 $marc->{item_form}, $marc->{date1},
352 $marc->{record_type}, $marc->{bib_lvl},
353 $marc->{title}, $_, "\n");
357 if ($conf->{fingerprints}{koha_bib_id} and exists $marc->{koha_bib_id}) {
358 print OF join("\t", $marc->{score}, $marc->{id}, "z_koha_bib_id",
359 $marc->{item_form}, $marc->{date1},
360 $marc->{record_type},
361 $marc->{bib_lvl}, $marc->{title},
362 $marc->{koha_bib_id}), "\n";
365 if ($conf->{fingerprints}{isbn}) {
366 if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
367 foreach my $isbn ( @{ $marc->{isbns}} ) {
368 print OF join("\t", $marc->{score}, $marc->{id}, "isbn",
369 $marc->{item_form}, $marc->{date1},
370 $marc->{record_type},
371 $marc->{bib_lvl}, $marc->{title},
372 $isbn, $marc->{pages}), "\n";
377 if ($conf->{fingerprints}{edition} and $marc->{edition}) {
378 print OF join("\t", $marc->{score}, $marc->{id}, "edition",
379 $marc->{item_form}, $marc->{date1},
380 $marc->{record_type}, $marc->{bib_lvl},
381 $marc->{title}, $marc->{edition}), "\n";
384 if ($conf->{fingerprints}{issn} and $marc->{issn}) {
385 print OF join("\t", $marc->{score}, $marc->{id}, "issn",
386 $marc->{item_form}, $marc->{date1},
387 $marc->{record_type}, $marc->{bib_lvl},
388 $marc->{title}, $marc->{issn}), "\n";
391 if ($conf->{fingerprints}{lccn} and $marc->{lccn}) {
392 print OF join("\t", $marc->{score}, $marc->{id}, "lccn",
393 $marc->{item_form}, $marc->{date1},
394 $marc->{record_type}, $marc->{bib_lvl},
395 $marc->{title}, $marc->{lccn}) ,"\n";
398 if ($conf->{fingerprints}{accomp} and $marc->{accomp}) {
399 print OF join("\t", $marc->{score}, $marc->{id}, "accomp",
400 $marc->{item_form}, $marc->{date1},
401 $marc->{record_type}, $marc->{bib_lvl},
402 $marc->{title}, $marc->{accomp}) ,"\n";
405 if ($conf->{fingerprints}{authpub} and $marc->{author} and
406 $marc->{publisher} and $marc->{pubyear} and $marc->{pages}) {
407 print OF join("\t", $marc->{score}, $marc->{id}, "authpub",
408 $marc->{item_form}, $marc->{date1},
409 $marc->{record_type}, $marc->{bib_lvl},
410 $marc->{title}, $marc->{author},
411 $marc->{publisher}, $marc->{pubyear},
412 $marc->{pages}), "\n";
418 =head2 dump_exception
420 Write line of exception report
425 my ($marc, $msg) = @_;
426 unless (defined $marc) {
427 print XF "Undefined record at line $count; likely bad XML\n";
431 print XF "Record ", $marc->{id}, " excluded: ";
437 print XF "missing item_form; " unless ($marc->{item_form});
438 unless (defined $marc->{date1})
439 { print XF "missing date1; " }
441 { print XF "invalid date1: '", $marc->{date1}, "'; "
442 unless ($marc->{date1} =~ /\d{4}/); }
443 print XF "missing record_type; " unless ($marc->{record_type});
444 print XF "missing bib_lvl; " unless ($marc->{bib_lvl});
445 print XF "missing title " unless ($marc->{title});
450 =head2 this_record_is_excluded
452 Returns 1 if the record B<is> and 0 if the record B<is not> excluded,
453 according to the subfield mapping (generated via the C<--excludelist>
458 sub this_record_is_excluded {
459 my ($rec, $marc) = @_;
460 return 0 unless defined $conf->{excludelist};
462 for my $tag (keys %{ $conf->{excludelist}->{tags} }) {
463 for my $sub (keys %{$conf->{excludelist}->{tags}{$tag}}) {
464 my $f = $conf->{excludelist}->field($tag, $sub);
466 # if this record doesn't have the right tag/sub, it can't be
467 return 0 unless ($rec->field($tag) and $rec->field($tag)->subfield($sub));
468 # but it does, so if there are no filters to check...
469 unless ($conf->{excludelist}->filters($f))
470 { dump_exception($marc, "exclusion $tag$sub"); return 1 }
472 my $sub_contents = $rec->field($tag)->subfield($sub);
473 for my $filter (@{ $conf->{excludelist}->filters($f)}) {
474 if ($sub_contents =~ /$filter/i) {
475 # filter matches. no fp.
476 dump_exception($marc, "exclusion $tag$sub '$filter'");
479 # no match, no exclude
488 Performs boring script initialization. Handles argument parsing,
497 # set mode on existing filehandles
498 binmode(STDIN, ':utf8');
500 my $rc = GetOptions( $c,
509 'arbitrarily-lose-above=i',
510 'arbitrarily-lose-below=i',
517 show_help() unless $rc;
518 show_help() if ($c->{help});
520 # check fingerprints list for validity
521 if ($c->{fingerprints}) {
523 my %valid_fps = ( oclc => 1, isbn => 1, issn => 1, lccn => 1,
524 edition => 1, accomp => 1, authpub => 1,
525 baseline => 1, crap => 1,
528 for (split /,/, $c->{fingerprints}) {
529 die "Invalid fingerprint '$_'\n" unless $valid_fps{$_};
532 $c->{fingerprints} = \%fps
534 $c->{fingerprints} = {oclc => 1, isbn => 1, edition => 1, issn => 1,
535 lccn => 1, accomp => 1, authpub => 1};
538 # check scores list for validity
541 my %valid_scores = ( oclc => 1, dlc => 1, num_650 => 1,
542 num_tags => 1, enc_lvl => 1,
544 for (split /,/, $c->{scores}) {
545 die "Invalid score mode '$_'\n" unless $valid_scores{$_};
548 $c->{dyn_scores} = [split /,/, $c->{scores}];
549 $c->{scores} = \%scores;
551 $c->{scores} = {oclc => 1, dlc => 1, num_650 => 1,
552 num_tags => 1, enc_lvl => 1};
553 $c->{dyn_scores} = [ qw/oclc dlc num_650 num_tags enc_lvl/ ];
557 $c->{tag} = 903 unless defined $c->{tag};
558 $c->{subfield} = 'a' unless defined $c->{subfield};
559 $c->{marctype} = 'XML' unless defined $c->{marctype};
561 $c->{output} = join('.',$c->{prefix},'fp');
562 $c->{exception} = join('.',$c->{prefix},'fp','ex');
565 # get SFM object if excludelist was specified
566 if ($c->{excludelist}) {
568 Equinox::Migration::SubfieldMapper->new( file => $c->{excludelist} );
571 my @keys = keys %{$c};
572 show_help() unless (@ARGV and @keys);
573 for my $key ('tag', 'subfield', 'output', 'exception')
574 { push @missing, $key unless $c->{$key} }
576 print "Required option: ", join(', ', @missing), " missing!\n";
582 =head2 progress_ticker
586 sub progress_ticker {
587 return if $conf->{quiet};
588 printf("\r> %d recs seen; %d processed", $count, $scount);
589 printf(" (%d/s)", ($count / (time - $start + 1)))
590 if ($count % 500 == 0);
595 Display usage message when things go wrong
601 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
603 --output=<FILE> -o Output filename
604 --exceptions=<FILE> -x Exception report filename
606 --prefix=<PREFIX>> -p Shared prefix for output/exception files. Will
607 produce PREFIX.fp and PREFIX.fp.ex
609 --tag=N -t Which tag to use (default 903)
610 --subfield=X -s Which subfield to use (default 'a')
611 --quiet -q Don't write status messages to STDOUT
612 --ignoresubtitle -i Ignore 245$b and construct the title from 245$a alone.
614 --fingerprints=LIST Fingerprints to generate, comma separated
615 Default: oclc,isbn,edition,issn,lccn,accomp,authpub
616 Others: baseline,koha_bib_id
617 --excludelist=FILE Name of fingerprints exclusions file
619 --scores=LIST Scores to calculate, comma separated
620 Default: oclc,dlc,num_650,num_tags,enc_level
621 --newwins New record IDs score higher (default is old wins)
622 --arbitrarily-lose-above
623 --arbitrarily-lose-below
624 --arbitrarily-decrease-score-by
625 Modify fingerprint scoring of records whose EG id is above or below a
626 given value, inclusive (so 5 is <= 5 or >= 5) such that they lose.
628 --marctype=TYPE Defaults to 'XML'