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;
28 use Equinox::Migration::Utils qw/normalize_oclc_number/;
30 my $conf = {}; # configuration hashref
31 my $count = 0; my $scount = 0;
37 open OF, '>', $conf->{output} or die "$0: cannot open output file $conf->{output}: $!\n";
38 open XF, '>', $conf->{exception} or die "$0: cannot open exception file $conf->{exception}: $!\n";
40 for my $file (@ARGV) {
41 print XF "Processing $file\n";
43 my $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 if ($record->field('001') &&
153 $record->field('003') &&
154 $record->field('003')->as_string() =~ /OCo{0,1}LC/ &&
155 defined normalize_oclc_number($record->field('001')->as_string())) {
156 push @{ $marc{oclc} }, normalize_oclc_number($record->field('001')->as_string());
158 for ($record->field('035')) {
159 my $oclc = $_->subfield('a');
161 ($oclc =~ /\(OCoLC\)/ || $oclc =~ /(ocm|ocl7|ocn|on)/) &&
162 defined normalize_oclc_number($oclc)) {
163 push @{ $marc{oclc} }, normalize_oclc_number($oclc);
167 if ($record->field('999')) {
168 my $koha_bib_id = $record->field('999')->subfield('c');
169 $marc{koha_bib_id} = $koha_bib_id if defined $koha_bib_id and $koha_bib_id =~ /^\d+$/;
172 # "Accompanying material" and check for "copy" (300)
173 if ($record->field('300')) {
174 $marc{accomp} = $record->field('300')->subfield('e');
175 $marc{tag300a} = $record->field('300')->subfield('a');
178 # issn, lccn, title, desc, pages, pub, pubyear, edition
179 $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
180 $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
181 $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
182 $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
183 $marc{title} = $record->field('245')->subfield('a')
184 if $record->field('245');
185 $marc{title} .= ' ' . $record->field('245')->subfield('b')
186 if ($record->field('245') and
187 $record->field('245')->subfield('b') and
188 not $conf->{ignoresubtitle});
189 $marc{edition} = $record->field('250')->subfield('a')
190 if $record->field('250');
191 if ($record->field('260')) {
192 $marc{publisher} = $record->field('260')->subfield('b');
193 $marc{pubyear} = $record->field('260')->subfield('c');
195 (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
202 =head2 normalize_marc
204 Gently massages your data.
211 $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
212 if ($marc->{title}) {
213 $marc->{title} = NFD($marc->{title});
214 $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
215 $marc->{title} = lc($marc->{title});
216 $marc->{title} =~ s/\W+$//go;
218 if ($marc->{author}) {
219 $marc->{author} = NFD($marc->{author});
220 $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
221 $marc->{author} = lc($marc->{author});
222 $marc->{author} =~ s/\W+$//go;
223 if ($marc->{author} =~ /^(\w+)/) {
224 $marc->{author} = $1;
227 if ($marc->{publisher}) {
228 $marc->{publisher} = NFD($marc->{publisher});
229 $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
230 $marc->{publisher} = lc($marc->{publisher});
231 $marc->{publisher} =~ s/\W+$//go;
232 if ($marc->{publisher} =~ /^(\w+)/) {
233 $marc->{publisher} = $1;
243 Checks MARC record to see if neccessary fingerprinting data is
250 return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
251 $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
258 Assign a score to the record based on various criteria.
260 Score is constructed by pushing elements onto a list, via a dispatch
261 table. This allows order of fingerprints in the output file to be
267 my ($marc, $record) = @_;
271 #----------------------------------
272 # static criteria scoring
273 #----------------------------------
274 $marc->{misc_score} = 999;
275 $marc->{age_score} = 999999999999;
277 # -1 if 008 has been padded, -2 if it doesn't exist
279 { $marc->{misc_score}-- if ($marc->{tag008} =~ /\|$/) }
281 { $marc->{misc_score} -= 2 }
282 # -1 if date has been pulled from 260
283 $marc->{misc_score}-- if $marc->{fudgedate};
284 # -1 if this is a copy record
285 $marc->{misc_score}--
286 if (defined $marc->{tag300a} and $marc->{tag300a} =~ /copy/i);
288 # subtract record id if we want older records to win
289 #$marc->{age_score} -= $marc->{id} unless ($conf->{newwins});
290 # handle arbitrary adjustments
291 $marc->{age_score} = 1;
292 if ($conf->{'arbitrarily-lose-above'}) {
293 $marc->{age_score} = 0
294 if ($marc->{id} >= $conf->{'arbitrarily-lose-above'});
296 if ($conf->{'arbitrarily-lose-below'}) {
297 $marc->{age_score} = 0
298 if ($marc->{id} <= $conf->{'arbitrarily-lose-below'});
301 #----------------------------------
302 # dynamic calculated scoring
303 #----------------------------------
305 oclc => sub { return $marc->{oclc}[0] ? 1 : 0 },
307 if ($record->field('040') and $record->field('040')->subfield('a'))
308 { return scalar($record->subfield( '040', 'a')) =~ /dlc/io ? 1 : 0 }
312 if ($record->field('650')) {
313 # can't say "scalar $record->field('650')"; MARC::Record
314 # behaves differently in list/scalar contexts
315 my @tags = $record->field('650');
316 return sprintf("%04d", scalar @tags)
317 } else { return '0000' }
319 num_tags=> sub { return sprintf( '%04d', scalar( $record->fields ) ) },
321 my $enc = substr($record->leader, 17, 1) || 'u';
322 my %levels = ( ' ' => 9, 1 => 8, 2 => 7, 3 => 6, 4 => 5, 5 => 4,
323 6 => 3, 7 => 2, 8 => 1, 'u' => 0, 'z' => 0 );
324 return $levels{$enc} || 0;
328 #----------------------------------
329 # assemble and store scores
330 #----------------------------------
331 for ( @{ $conf->{dyn_scores} } ) {
332 push @score, $scores_code{$_}->($marc, $record);
333 $json .= $_ . ':' . $score[-1] . ',';
335 $json .= 'misc:' . $marc->{misc_score} . '}';
337 my $compact = join('', $marc->{age_score}, $marc->{misc_score}, @score);
338 $marc->{score} = "$compact\t$json";
341 =head2 dump_fingerprints
345 sub dump_fingerprints {
348 if ($conf->{fingerprints}{baseline}) {
349 print OF join("\t", $marc->{score}, $marc->{id}, 'baseline',
350 $marc->{item_form}, $marc->{date1}, $marc->{record_type},
351 $marc->{bib_lvl}, $marc->{title}), "\n";
354 if ($conf->{fingerprints}{oclc} and scalar @{$marc->{oclc} }) {
355 for (@{$marc->{oclc} }) {
356 print OF join("\t", $marc->{score}, $marc->{id}, "oclc",
357 $marc->{item_form}, $marc->{date1},
358 $marc->{record_type}, $marc->{bib_lvl},
359 $marc->{title}, $_, "\n");
363 if ($conf->{fingerprints}{koha_bib_id} and exists $marc->{koha_bib_id}) {
364 print OF join("\t", $marc->{score}, $marc->{id}, "z_koha_bib_id",
365 $marc->{item_form}, $marc->{date1},
366 $marc->{record_type},
367 $marc->{bib_lvl}, $marc->{title},
368 $marc->{koha_bib_id}), "\n";
371 if ($conf->{fingerprints}{isbn}) {
372 if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
373 foreach my $isbn ( @{ $marc->{isbns}} ) {
374 print OF join("\t", $marc->{score}, $marc->{id}, "isbn",
375 $marc->{item_form}, $marc->{date1},
376 $marc->{record_type},
377 $marc->{bib_lvl}, $marc->{title},
378 $isbn, $marc->{pages}), "\n";
383 if ($conf->{fingerprints}{edition} and $marc->{edition} and $marc->{author}) {
384 print OF join("\t", $marc->{score}, $marc->{id}, "edition",
385 $marc->{item_form}, $marc->{date1},
386 $marc->{record_type}, $marc->{bib_lvl},
387 $marc->{title}, $marc->{author}, $marc->{edition}), "\n";
390 if ($conf->{fingerprints}{issn} and $marc->{issn}) {
391 print OF join("\t", $marc->{score}, $marc->{id}, "issn",
392 $marc->{item_form}, $marc->{date1},
393 $marc->{record_type}, $marc->{bib_lvl},
394 $marc->{title}, $marc->{issn}), "\n";
397 if ($conf->{fingerprints}{lccn} and $marc->{lccn}) {
398 print OF join("\t", $marc->{score}, $marc->{id}, "lccn",
399 $marc->{item_form}, $marc->{date1},
400 $marc->{record_type}, $marc->{bib_lvl},
401 $marc->{title}, $marc->{lccn}) ,"\n";
404 if ($conf->{fingerprints}{accomp} and $marc->{accomp}) {
405 print OF join("\t", $marc->{score}, $marc->{id}, "accomp",
406 $marc->{item_form}, $marc->{date1},
407 $marc->{record_type}, $marc->{bib_lvl},
408 $marc->{title}, $marc->{accomp}) ,"\n";
411 if ($conf->{fingerprints}{authpub} and $marc->{author} and
412 $marc->{publisher} and $marc->{pubyear} and $marc->{pages}) {
413 print OF join("\t", $marc->{score}, $marc->{id}, "authpub",
414 $marc->{item_form}, $marc->{date1},
415 $marc->{record_type}, $marc->{bib_lvl},
416 $marc->{title}, $marc->{author},
417 $marc->{publisher}, $marc->{pubyear},
418 $marc->{pages}), "\n";
424 =head2 dump_exception
426 Write line of exception report
431 my ($marc, $msg) = @_;
432 unless (defined $marc) {
433 print XF "Undefined record at line $count; likely bad XML\n";
437 print XF "Record ", $marc->{id}, " excluded: ";
443 print XF "missing item_form; " unless ($marc->{item_form});
444 unless (defined $marc->{date1})
445 { print XF "missing date1; " }
447 { print XF "invalid date1: '", $marc->{date1}, "'; "
448 unless ($marc->{date1} =~ /\d{4}/); }
449 print XF "missing record_type; " unless ($marc->{record_type});
450 print XF "missing bib_lvl; " unless ($marc->{bib_lvl});
451 print XF "missing title " unless ($marc->{title});
456 =head2 this_record_is_excluded
458 Returns 1 if the record B<is> and 0 if the record B<is not> excluded,
459 according to the subfield mapping (generated via the C<--excludelist>
464 sub this_record_is_excluded {
465 my ($rec, $marc) = @_;
466 return 0 unless defined $conf->{excludelist};
468 for my $tag (keys %{ $conf->{excludelist}->{tags} }) {
469 for my $sub (keys %{$conf->{excludelist}->{tags}{$tag}}) {
470 my $f = $conf->{excludelist}->field($tag, $sub);
472 # if this record doesn't have the right tag/sub, it can't be
473 return 0 unless ($rec->field($tag) and $rec->field($tag)->subfield($sub));
474 # but it does, so if there are no filters to check...
475 unless ($conf->{excludelist}->filters($f))
476 { dump_exception($marc, "exclusion $tag$sub"); return 1 }
478 my $sub_contents = $rec->field($tag)->subfield($sub);
479 for my $filter (@{ $conf->{excludelist}->filters($f)}) {
480 if ($sub_contents =~ /$filter/i) {
481 # filter matches. no fp.
482 dump_exception($marc, "exclusion $tag$sub '$filter'");
485 # no match, no exclude
494 Performs boring script initialization. Handles argument parsing,
503 # set mode on existing filehandles
504 binmode(STDIN, ':utf8');
506 my $rc = GetOptions( $c,
515 'arbitrarily-lose-above=i',
516 'arbitrarily-lose-below=i',
523 show_help() unless $rc;
524 show_help() if ($c->{help});
526 # check fingerprints list for validity
527 if ($c->{fingerprints}) {
529 my %valid_fps = ( oclc => 1, isbn => 1, issn => 1, lccn => 1,
530 edition => 1, accomp => 1, authpub => 1,
531 baseline => 1, crap => 1,
534 for (split /,/, $c->{fingerprints}) {
535 die "Invalid fingerprint '$_'\n" unless $valid_fps{$_};
538 $c->{fingerprints} = \%fps
540 $c->{fingerprints} = {oclc => 1, isbn => 1, edition => 1, issn => 1,
541 lccn => 1, accomp => 1, authpub => 1};
544 # check scores list for validity
547 my %valid_scores = ( oclc => 1, dlc => 1, num_650 => 1,
548 num_tags => 1, enc_lvl => 1,
550 for (split /,/, $c->{scores}) {
551 die "Invalid score mode '$_'\n" unless $valid_scores{$_};
554 $c->{dyn_scores} = [split /,/, $c->{scores}];
555 $c->{scores} = \%scores;
557 $c->{scores} = {oclc => 1, dlc => 1, num_650 => 1,
558 num_tags => 1, enc_lvl => 1};
559 $c->{dyn_scores} = [ qw/oclc dlc num_650 num_tags enc_lvl/ ];
563 $c->{tag} = 903 unless defined $c->{tag};
564 $c->{subfield} = 'a' unless defined $c->{subfield};
565 $c->{marctype} = 'XML' unless defined $c->{marctype};
567 $c->{output} = join('.',$c->{prefix},'fp');
568 $c->{exception} = join('.',$c->{prefix},'fp','ex');
571 # get SFM object if excludelist was specified
572 if ($c->{excludelist}) {
574 Equinox::Migration::SubfieldMapper->new( file => $c->{excludelist} );
577 my @keys = keys %{$c};
578 show_help() unless (@ARGV and @keys);
579 for my $key ('tag', 'subfield', 'output', 'exception')
580 { push @missing, $key unless $c->{$key} }
582 print "Required option: ", join(', ', @missing), " missing!\n";
588 =head2 progress_ticker
592 sub progress_ticker {
593 return if $conf->{quiet};
594 printf("\r> %d recs seen; %d processed", $count, $scount);
595 printf(" (%d/s)", ($count / (time - $start + 1)))
596 if ($count % 500 == 0);
601 Display usage message when things go wrong
607 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
609 --output=<FILE> -o Output filename
610 --exceptions=<FILE> -x Exception report filename
612 --prefix=<PREFIX>> -p Shared prefix for output/exception files. Will
613 produce PREFIX.fp and PREFIX.fp.ex
615 --tag=N -t Which tag to use (default 903)
616 --subfield=X -s Which subfield to use (default 'a')
617 --quiet -q Don't write status messages to STDOUT
618 --ignoresubtitle -i Ignore 245\$b and construct the title from 245\$a alone.
620 --fingerprints=LIST Fingerprints to generate, comma separated
621 Default: oclc,isbn,edition,issn,lccn,accomp,authpub
622 Others: baseline,koha_bib_id
623 --excludelist=FILE Name of fingerprints exclusions file
625 --scores=LIST Scores to calculate, comma separated
626 Default: oclc,dlc,num_650,num_tags,enc_level
627 --newwins New record IDs score higher (default is old wins)
628 --arbitrarily-lose-above
629 --arbitrarily-lose-below
630 --arbitrarily-decrease-score-by
631 Modify fingerprint scoring of records whose EG id is above or below a
632 given value, inclusive (so 5 is <= 5 or >= 5) such that they lose.
634 --marctype=TYPE Defaults to 'XML'