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->{exception}: $!\n";
39 for my $file (@ARGV) {
40 print XF "Processing $file\n";
42 my $batch = MARC::Batch->new($conf->{marctype}, $file);
44 $batch->warnings_off();
48 eval { $record = $batch->next; };
50 import MARC::File::XML;
51 print "skipping bad record: $@\n";
55 $count++; progress_ticker();
57 unless ( defined $record )
58 { dump_exception($marc); next; }
60 my $id = $record->field($conf->{tag});
62 print XF "ERROR: Record $count in $file is missing a ",
63 $conf->{tag}, " field.\n", $record->as_formatted(), "\n=====\n";
67 # populate and normalize marc
68 $marc = populate_marc($record, $id);
69 # check for manual exclusion
70 next if this_record_is_excluded($record, $marc);
71 normalize_marc($marc);
72 unless (marc_isvalid($marc))
73 { dump_exception($marc); next; }
75 # if everything looks good, score it and dump fingerprints
76 score_marc($marc, $record);
77 dump_fingerprints($marc);
78 $scount++; progress_ticker();
82 print "\nSuccessfully processed:\t$count\n" unless $conf->{quiet};
86 Constructs a hash containing the relevant MARC data for a record and
87 returns a reference to it.
92 my ($record, $id) = @_;
93 my %marc = (); $marc{isbns} = [];
96 $marc{id} = $id->as_string($conf->{subfield});
98 # record_type, bib_lvl
99 $marc{record_type} = substr($record->leader, 6, 1);
100 $marc{bib_lvl} = substr($record->leader, 7, 1);
103 my $my_008 = $record->field('008');
104 $marc{tag008} = $my_008->as_string() if ($my_008);
105 if (defined $marc{tag008}) {
106 unless (length $marc{tag008} == 40) {
107 $marc{tag008} = $marc{tag008} . ('|' x (40 - length($marc{tag008})));
108 print XF ">> Short 008 padded to ",length($marc{tag008})," at rec $count\n";
110 $marc{date1} = substr($marc{tag008},7,4) if ($marc{tag008});
111 $marc{date2} = substr($marc{tag008},11,4) if ($marc{tag008}); # UNUSED
113 unless ($marc{date1} and $marc{date1} =~ /\d{4}/) {
114 my $my_260 = $record->field('260');
115 if ($my_260 and $my_260->subfield('c')) {
116 my $date1 = $my_260->subfield('c');
118 if (defined $date1 and $date1 =~ /\d{4}/) {
119 $marc{date1} = $date1;
120 $marc{fudgedate} = 1;
121 print XF ">> using 260c as date1 at rec $count\n";
127 if ( $marc{record_type} =~ /[gkroef]/ ) { # MAP, VIS
128 $marc{item_form} = substr($marc{tag008},29,1) if ($marc{tag008});
130 $marc{item_form} = substr($marc{tag008},23,1) if ($marc{tag008});
134 my @isbns = $record->field('020') if $record->field('020');
135 push @isbns, $record->field('024') if $record->field('024');
136 for my $f ( @isbns ) {
137 push @{ $marc{isbns} }, $1 if ( defined $f->subfield('a') and
138 $f->subfield('a')=~/(\S+)/ );
142 for my $rec_field (100, 110, 111) {
143 if ($record->field($rec_field)) {
144 $marc{author} = $record->field($rec_field)->subfield('a');
151 push @{ $marc{oclc} }, $record->field('001')->as_string()
152 if ($record->field('001') and $record->field('003') and
153 $record->field('003')->as_string() =~ /OCo{0,1}LC/);
154 for ($record->field('035')) {
155 my $oclc = $_->subfield('a');
156 push @{ $marc{oclc} }, $oclc
157 if (defined $oclc and $oclc =~ /\(OCoLC\)/ and $oclc =~/([0-9]+)/);
160 if ($record->field('999')) {
161 my $koha_bib_id = $record->field('999')->subfield('c');
162 $marc{koha_bib_id} = $koha_bib_id if defined $koha_bib_id and $koha_bib_id =~ /^\d+$/;
165 # "Accompanying material" and check for "copy" (300)
166 if ($record->field('300')) {
167 $marc{accomp} = $record->field('300')->subfield('e');
168 $marc{tag300a} = $record->field('300')->subfield('a');
171 # issn, lccn, title, desc, pages, pub, pubyear, edition
172 $marc{lccn} = $record->field('010')->subfield('a') if $record->field('010');
173 $marc{issn} = $record->field('022')->subfield('a') if $record->field('022');
174 $marc{desc} = $record->field('300')->subfield('a') if $record->field('300');
175 $marc{pages} = $1 if (defined $marc{desc} and $marc{desc} =~ /(\d+)/);
176 $marc{title} = $record->field('245')->subfield('a')
177 if $record->field('245');
178 $marc{title} .= ' ' . $record->field('245')->subfield('b')
179 if ($record->field('245') and
180 $record->field('245')->subfield('b') and
181 not $conf->{ignoresubtitle});
182 $marc{edition} = $record->field('250')->subfield('a')
183 if $record->field('250');
184 if ($record->field('260')) {
185 $marc{publisher} = $record->field('260')->subfield('b');
186 $marc{pubyear} = $record->field('260')->subfield('c');
188 (defined $marc{pubyear} and $marc{pubyear} =~ /(\d{4})/) ? $1 : '';
195 =head2 normalize_marc
197 Gently massages your data.
204 $marc->{record_type }= 'a' if ($marc->{record_type} eq ' ');
205 if ($marc->{title}) {
206 $marc->{title} = NFD($marc->{title});
207 $marc->{title} =~ s/[\x{80}-\x{ffff}]//go;
208 $marc->{title} = lc($marc->{title});
209 $marc->{title} =~ s/\W+$//go;
211 if ($marc->{author}) {
212 $marc->{author} = NFD($marc->{author});
213 $marc->{author} =~ s/[\x{80}-\x{ffff}]//go;
214 $marc->{author} = lc($marc->{author});
215 $marc->{author} =~ s/\W+$//go;
216 if ($marc->{author} =~ /^(\w+)/) {
217 $marc->{author} = $1;
220 if ($marc->{publisher}) {
221 $marc->{publisher} = NFD($marc->{publisher});
222 $marc->{publisher} =~ s/[\x{80}-\x{ffff}]//go;
223 $marc->{publisher} = lc($marc->{publisher});
224 $marc->{publisher} =~ s/\W+$//go;
225 if ($marc->{publisher} =~ /^(\w+)/) {
226 $marc->{publisher} = $1;
236 Checks MARC record to see if neccessary fingerprinting data is
243 return 1 if ($marc->{item_form} and ($marc->{date1} =~ /\d{4}/) and
244 $marc->{record_type} and $marc->{bib_lvl} and $marc->{title});
251 Assign a score to the record based on various criteria.
253 Score is constructed by pushing elements onto a list, via a dispatch
254 table. This allows order of fingerprints in the output file to be
260 my ($marc, $record) = @_;
264 #----------------------------------
265 # static criteria scoring
266 #----------------------------------
267 $marc->{misc_score} = 999;
268 $marc->{age_score} = 999999999999;
270 # -1 if 008 has been padded, -2 if it doesn't exist
272 { $marc->{misc_score}-- if ($marc->{tag008} =~ /\|$/) }
274 { $marc->{misc_score} -= 2 }
275 # -1 if date has been pulled from 260
276 $marc->{misc_score}-- if $marc->{fudgedate};
277 # -1 if this is a copy record
278 $marc->{misc_score}--
279 if (defined $marc->{tag300a} and $marc->{tag300a} =~ /copy/i);
281 # subtract record id if we want older records to win
282 #$marc->{age_score} -= $marc->{id} unless ($conf->{newwins});
283 # handle arbitrary adjustments
284 $marc->{age_score} = 1;
285 if ($conf->{'arbitrarily-lose-above'}) {
286 $marc->{age_score} = 0
287 if ($marc->{id} >= $conf->{'arbitrarily-lose-above'});
289 if ($conf->{'arbitrarily-lose-below'}) {
290 $marc->{age_score} = 0
291 if ($marc->{id} <= $conf->{'arbitrarily-lose-below'});
294 #----------------------------------
295 # dynamic calculated scoring
296 #----------------------------------
298 oclc => sub { return $marc->{oclc}[0] ? 1 : 0 },
300 if ($record->field('040') and $record->field('040')->subfield('a'))
301 { return scalar($record->subfield( '040', 'a')) =~ /dlc/io ? 1 : 0 }
305 if ($record->field('650')) {
306 # can't say "scalar $record->field('650')"; MARC::Record
307 # behaves differently in list/scalar contexts
308 my @tags = $record->field('650');
309 return sprintf("%04d", scalar @tags)
310 } else { return '0000' }
312 num_tags=> sub { return sprintf( '%04d', scalar( $record->fields ) ) },
314 my $enc = substr($record->leader, 17, 1) || 'u';
315 my %levels = ( ' ' => 9, 1 => 8, 2 => 7, 3 => 6, 4 => 5, 5 => 4,
316 6 => 3, 7 => 2, 8 => 1, 'u' => 0, 'z' => 0 );
317 return $levels{$enc} || 0;
321 #----------------------------------
322 # assemble and store scores
323 #----------------------------------
324 for ( @{ $conf->{dyn_scores} } ) {
325 push @score, $scores_code{$_}->($marc, $record);
326 $json .= $_ . ':' . $score[-1] . ',';
328 $json .= 'misc:' . $marc->{misc_score} . '}';
330 my $compact = join('', $marc->{age_score}, $marc->{misc_score}, @score);
331 $marc->{score} = "$compact\t$json";
334 =head2 dump_fingerprints
338 sub dump_fingerprints {
341 if ($conf->{fingerprints}{baseline}) {
342 print OF join("\t", $marc->{score}, $marc->{id}, 'baseline',
343 $marc->{item_form}, $marc->{date1}, $marc->{record_type},
344 $marc->{bib_lvl}, $marc->{title}), "\n";
347 if ($conf->{fingerprints}{oclc} and scalar @{$marc->{oclc} }) {
348 for (@{$marc->{oclc} }) {
349 print OF join("\t", $marc->{score}, $marc->{id}, "oclc",
350 $marc->{item_form}, $marc->{date1},
351 $marc->{record_type}, $marc->{bib_lvl},
352 $marc->{title}, $_, "\n");
356 if ($conf->{fingerprints}{koha_bib_id} and exists $marc->{koha_bib_id}) {
357 print OF join("\t", $marc->{score}, $marc->{id}, "z_koha_bib_id",
358 $marc->{item_form}, $marc->{date1},
359 $marc->{record_type},
360 $marc->{bib_lvl}, $marc->{title},
361 $marc->{koha_bib_id}), "\n";
364 if ($conf->{fingerprints}{isbn}) {
365 if ((scalar @{ $marc->{isbns} } > 0) and $marc->{pages}) {
366 foreach my $isbn ( @{ $marc->{isbns}} ) {
367 print OF join("\t", $marc->{score}, $marc->{id}, "isbn",
368 $marc->{item_form}, $marc->{date1},
369 $marc->{record_type},
370 $marc->{bib_lvl}, $marc->{title},
371 $isbn, $marc->{pages}), "\n";
376 if ($conf->{fingerprints}{edition} and $marc->{edition} and $marc->{author}) {
377 print OF join("\t", $marc->{score}, $marc->{id}, "edition",
378 $marc->{item_form}, $marc->{date1},
379 $marc->{record_type}, $marc->{bib_lvl},
380 $marc->{title}, $marc->{author}, $marc->{edition}), "\n";
383 if ($conf->{fingerprints}{issn} and $marc->{issn}) {
384 print OF join("\t", $marc->{score}, $marc->{id}, "issn",
385 $marc->{item_form}, $marc->{date1},
386 $marc->{record_type}, $marc->{bib_lvl},
387 $marc->{title}, $marc->{issn}), "\n";
390 if ($conf->{fingerprints}{lccn} and $marc->{lccn}) {
391 print OF join("\t", $marc->{score}, $marc->{id}, "lccn",
392 $marc->{item_form}, $marc->{date1},
393 $marc->{record_type}, $marc->{bib_lvl},
394 $marc->{title}, $marc->{lccn}) ,"\n";
397 if ($conf->{fingerprints}{accomp} and $marc->{accomp}) {
398 print OF join("\t", $marc->{score}, $marc->{id}, "accomp",
399 $marc->{item_form}, $marc->{date1},
400 $marc->{record_type}, $marc->{bib_lvl},
401 $marc->{title}, $marc->{accomp}) ,"\n";
404 if ($conf->{fingerprints}{authpub} and $marc->{author} and
405 $marc->{publisher} and $marc->{pubyear} and $marc->{pages}) {
406 print OF join("\t", $marc->{score}, $marc->{id}, "authpub",
407 $marc->{item_form}, $marc->{date1},
408 $marc->{record_type}, $marc->{bib_lvl},
409 $marc->{title}, $marc->{author},
410 $marc->{publisher}, $marc->{pubyear},
411 $marc->{pages}), "\n";
417 =head2 dump_exception
419 Write line of exception report
424 my ($marc, $msg) = @_;
425 unless (defined $marc) {
426 print XF "Undefined record at line $count; likely bad XML\n";
430 print XF "Record ", $marc->{id}, " excluded: ";
436 print XF "missing item_form; " unless ($marc->{item_form});
437 unless (defined $marc->{date1})
438 { print XF "missing date1; " }
440 { print XF "invalid date1: '", $marc->{date1}, "'; "
441 unless ($marc->{date1} =~ /\d{4}/); }
442 print XF "missing record_type; " unless ($marc->{record_type});
443 print XF "missing bib_lvl; " unless ($marc->{bib_lvl});
444 print XF "missing title " unless ($marc->{title});
449 =head2 this_record_is_excluded
451 Returns 1 if the record B<is> and 0 if the record B<is not> excluded,
452 according to the subfield mapping (generated via the C<--excludelist>
457 sub this_record_is_excluded {
458 my ($rec, $marc) = @_;
459 return 0 unless defined $conf->{excludelist};
461 for my $tag (keys %{ $conf->{excludelist}->{tags} }) {
462 for my $sub (keys %{$conf->{excludelist}->{tags}{$tag}}) {
463 my $f = $conf->{excludelist}->field($tag, $sub);
465 # if this record doesn't have the right tag/sub, it can't be
466 return 0 unless ($rec->field($tag) and $rec->field($tag)->subfield($sub));
467 # but it does, so if there are no filters to check...
468 unless ($conf->{excludelist}->filters($f))
469 { dump_exception($marc, "exclusion $tag$sub"); return 1 }
471 my $sub_contents = $rec->field($tag)->subfield($sub);
472 for my $filter (@{ $conf->{excludelist}->filters($f)}) {
473 if ($sub_contents =~ /$filter/i) {
474 # filter matches. no fp.
475 dump_exception($marc, "exclusion $tag$sub '$filter'");
478 # no match, no exclude
487 Performs boring script initialization. Handles argument parsing,
496 # set mode on existing filehandles
497 binmode(STDIN, ':utf8');
499 my $rc = GetOptions( $c,
508 'arbitrarily-lose-above=i',
509 'arbitrarily-lose-below=i',
516 show_help() unless $rc;
517 show_help() if ($c->{help});
519 # check fingerprints list for validity
520 if ($c->{fingerprints}) {
522 my %valid_fps = ( oclc => 1, isbn => 1, issn => 1, lccn => 1,
523 edition => 1, accomp => 1, authpub => 1,
524 baseline => 1, crap => 1,
527 for (split /,/, $c->{fingerprints}) {
528 die "Invalid fingerprint '$_'\n" unless $valid_fps{$_};
531 $c->{fingerprints} = \%fps
533 $c->{fingerprints} = {oclc => 1, isbn => 1, edition => 1, issn => 1,
534 lccn => 1, accomp => 1, authpub => 1};
537 # check scores list for validity
540 my %valid_scores = ( oclc => 1, dlc => 1, num_650 => 1,
541 num_tags => 1, enc_lvl => 1,
543 for (split /,/, $c->{scores}) {
544 die "Invalid score mode '$_'\n" unless $valid_scores{$_};
547 $c->{dyn_scores} = [split /,/, $c->{scores}];
548 $c->{scores} = \%scores;
550 $c->{scores} = {oclc => 1, dlc => 1, num_650 => 1,
551 num_tags => 1, enc_lvl => 1};
552 $c->{dyn_scores} = [ qw/oclc dlc num_650 num_tags enc_lvl/ ];
556 $c->{tag} = 903 unless defined $c->{tag};
557 $c->{subfield} = 'a' unless defined $c->{subfield};
558 $c->{marctype} = 'XML' unless defined $c->{marctype};
560 $c->{output} = join('.',$c->{prefix},'fp');
561 $c->{exception} = join('.',$c->{prefix},'fp','ex');
564 # get SFM object if excludelist was specified
565 if ($c->{excludelist}) {
567 Equinox::Migration::SubfieldMapper->new( file => $c->{excludelist} );
570 my @keys = keys %{$c};
571 show_help() unless (@ARGV and @keys);
572 for my $key ('tag', 'subfield', 'output', 'exception')
573 { push @missing, $key unless $c->{$key} }
575 print "Required option: ", join(', ', @missing), " missing!\n";
581 =head2 progress_ticker
585 sub progress_ticker {
586 return if $conf->{quiet};
587 printf("\r> %d recs seen; %d processed", $count, $scount);
588 printf(" (%d/s)", ($count / (time - $start + 1)))
589 if ($count % 500 == 0);
594 Display usage message when things go wrong
600 Usage is: $0 [REQUIRED ARGS] [OPTIONS] <filelist>
602 --output=<FILE> -o Output filename
603 --exceptions=<FILE> -x Exception report filename
605 --prefix=<PREFIX>> -p Shared prefix for output/exception files. Will
606 produce PREFIX.fp and PREFIX.fp.ex
608 --tag=N -t Which tag to use (default 903)
609 --subfield=X -s Which subfield to use (default 'a')
610 --quiet -q Don't write status messages to STDOUT
611 --ignoresubtitle -i Ignore 245\$b and construct the title from 245\$a alone.
613 --fingerprints=LIST Fingerprints to generate, comma separated
614 Default: oclc,isbn,edition,issn,lccn,accomp,authpub
615 Others: baseline,koha_bib_id
616 --excludelist=FILE Name of fingerprints exclusions file
618 --scores=LIST Scores to calculate, comma separated
619 Default: oclc,dlc,num_650,num_tags,enc_level
620 --newwins New record IDs score higher (default is old wins)
621 --arbitrarily-lose-above
622 --arbitrarily-lose-below
623 --arbitrarily-decrease-score-by
624 Modify fingerprint scoring of records whose EG id is above or below a
625 given value, inclusive (so 5 is <= 5 or >= 5) such that they lose.
627 --marctype=TYPE Defaults to 'XML'