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.
26 use Equinox::Migration::SimpleTagList;
28 my $term = new Term::ReadLine 'yaz-cleanup';
29 my $OUT = $term->OUT || \*STDOUT;
30 binmode STDOUT, ":utf8";
31 binmode $OUT, ":utf8";
35 # initialization and setup
39 # set up files, since everything appears to be in order
40 open MARC, '<:utf8', $c->{marcfile}
41 or die "Can't open input file $!\n";
42 open my $NUMARC, '>:utf8', $c->{output}
43 or die "Can't open output file $!\n";
44 open my $OLD2NEW, '>', 'old2new.map'
45 if ($c->{'renumber-from'} and $c->{'original-tag'});
47 print $NUMARC "<collection xmlns=\"http://www.loc.gov/MARC21/slim\">\n";
49 $c->{totalrecs} = `grep -c '<record' $c->{marcfile}`;
50 chomp $c->{totalrecs};
53 my @record; # current record storage
54 my %recmeta; # metadata about current record
55 my $ptr = 0; # record index pointer
57 # this is the dispatch table which drives command selection in
59 my %commands = ( c => \&print_fullcontext,
62 '<' => \&widen_window,
63 '>' => \&narrow_window,
65 o => \&insert_original,
79 my @spinner = qw(- \\ | /);
82 while ( buildrecord() ) {
83 unless ($c->{ricount} % 50) {
84 $c->{percent} = int(($c->{ricount} / $c->{totalrecs}) * 100);
85 print "\rWorking (",$c->{percent},"%) ", $spinner[$sidx];
86 $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
89 my $rc = do_automated_cleanups();
93 until ($ptr == $#record) {
94 # get datafield/tag data if we have it
95 $rc = stow_record_data() if ($c->{'renumber-from'} and $c->{'original-tag'});
99 if ($record[$ptr] =~ /&/ && $record[$ptr] !~ /&\w+?;/)
100 { edit("Naked ampersand"); $ptr= 0; next }
102 if ($record[$ptr] =~ /<datafield tag="(.+?)"/) {
104 # tags must be numeric
105 if ($match =~ /\D/) {
106 edit("Non-numerics in tag") unless $c->{autoscrub};
111 # subfields can't be non-alphanumeric
112 if ($record[$ptr] =~ /<subfield code="(.*?)"/) {
113 if ($1 =~ /\P{IsAlnum}/ or $1 eq '') {
114 edit("Junk in subfield code/Null subfield code");
118 # subfields can't be larger than 1 char (technically you could make the MARC format accomodate that:)
119 if ($record[$ptr] =~ /<subfield code="(\w{2,})"/) {
120 edit("Subfield code larger than 1 char");
126 write_record($NUMARC);
128 print $NUMARC "</collection>\n";
129 print $OUT "\nDone. ",$c->{ricount}," in; ",$c->{rocount}," dumped \n";
132 #-----------------------------------------------------------------------------------
134 #-----------------------------------------------------------------------------------
136 sub do_automated_cleanups {
138 until ($ptr == $#record) {
140 # catch empty datafield elements
141 if ($record[$ptr] =~ m/<datafield tag="..."/) {
142 if ($record[$ptr + 1] =~ m|</datafield>|) {
143 my @a = @record[0 .. $ptr - 1];
144 my @b = @record[$ptr + 2 .. $#record];
146 @a = undef; @b = undef;
147 message("Empty datafield scrubbed");
152 # and quasi-empty subfields
153 if ($record[$ptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
154 my $code = $1; my $content = $2;
155 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
156 my @a = @record[0 .. $ptr - 1];
157 my @b = @record[$ptr + 1 .. $#record];
159 @a = undef; @b = undef;
160 message("Empty subfield scrubbed");
169 for $ptr (0 .. $#record) {
171 if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
173 if (length $leader < 24) {
174 $leader .= ' ' x (20 - length($leader));
176 $record[$ptr] = "<leader>$leader</leader>\n";
177 message("Short leader padded");
180 if ($c->{'force-utf8'}) {
181 if ($record[$ptr] =~ m|<leader>(.........).(.+)</leader>|) {
182 $record[$ptr] = "<leader>$1a$2</leader>\n";
185 if ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
188 if (length $content < 40) {
189 $content .= ' ' x (40 - length($content));
190 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
191 message("Short 008 padded");
195 # clean misplaced dollarsigns
196 if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
197 $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
198 message("Dollar sign corrected");
201 # excessive trailing whitespace in subfield contents
202 if ($record[$ptr] =~ m|\s{10,}</subfield>|) {
203 $record[$ptr] =~ s|\s{10,}</subfield>|</subfield>|;
204 message("Trailing whitespace trimmed from subfield contents");
207 # automatable subfield maladies
208 $record[$ptr] =~ s/code=" ">c/code="c">/;
209 $record[$ptr] =~ s/code=" ">\$/code="c">\$/;
211 if ($c->{'fix-subfield'}) {
212 $record[$ptr] =~ s/code="&">/code="$c->{'fix-subfield'}">/;
213 $record[$ptr] =~ s/code="\P{IsAlnum}">/code="$c->{'fix-subfield'}">/;
214 $record[$ptr] =~ s/code="">/code="$c->{'fix-subfield'}">/;
220 sub stow_record_data {
221 # get tag data if we're looking at it
223 if ($record[$ptr] =~ m/<(?:control|data)field tag="(.{3})"/) {
225 $tag = $recmeta{tag};
226 $record[$ptr] =~ m/ind1="(.)"/;
227 $recmeta{ind1} = $1 || '';
228 $record[$ptr] =~ m/ind2="(.)"/;
229 $recmeta{ind2} = $1 || '';
232 message("Autokill record: no detectable tag");
233 dump_record("No detectable tag") ;
237 # and since we are looking at a tag, see if it's the original id
238 if ($tag == $c->{'original-tag'}) {
242 if ($record[$ptr] =~ m|<controlfield tag="$tag">(.+?)</controlfield>|)
243 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
244 } elsif ($tag >= 10 and $c->{'original-subfield'}) {
246 my $line = $record[$ptr]; my $lptr = $ptr;
247 my $osub = $c->{'original-subfield'};
248 # skim to end of this tag
249 until ($line =~ m|</datafield>|) {
250 if ($line =~ /<subfield code="$osub">(.+?)</)
251 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
253 $line = $record[$lptr];
259 # didn't find the old id!
261 message("Autokill record: no oldid when old2new mapping requested");
262 dump_record("No old id found");
266 # got it; write to old->new map file
267 if ($c->{'renumber-from'} and $c->{'original-subfield'}) {
275 #-----------------------------------------------------------------------------------
277 #-----------------------------------------------------------------------------------
281 Handles the Term::ReadLine loop
288 return if $c->{trash}->has( $recmeta{tag} );
289 if ( $c->{fullauto} )
290 { dump_record($msg); return }
292 $c->{editmsg} = $msg;
295 # stow original problem line
296 $recmeta{origline} = $record[$ptr];
299 my $line = $term->readline('marc-cleanup>');
300 my @chunks = split /\s+/, $line;
302 # lines with single-character first chunks are commands.
303 # make sure they exist.
304 if (length $chunks[0] == 1) {
305 unless (defined $commands{$chunks[0]}) {
306 print $OUT "No such command '", $chunks[0], "'\n";
311 if (defined $commands{$chunks[0]}) {
312 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
315 $recmeta{prevline} = $record[$ptr];
316 $record[$ptr] = "$line\n";
320 # set pointer to top on the way out
326 Constructs record arrays from the incoming MARC file and returns them
334 my $trash = $c->{trash};
336 $l = <MARC> while (defined $l and $l !~ /<record/);
337 return $l unless defined $l;
340 for (keys %recmeta) { $recmeta{$_} = undef }
341 for (0 .. @record) { delete $record[$_] }
344 until ($l =~ m|</record>|) {
345 # clean up tags with spaces in them
346 $l =~ s/tag=" /tag="00/g;
347 $l =~ s/tag=" /tag="0/g;
348 $l =~ s/tag="-/tag="0/g;
349 $l =~ s/tag="(\d\d) /tag="0$1/g;
351 # excise unwanted tags
353 $istrash = 0 if ($l =~ m|</datafield|);
357 if ($l =~ m/<datafield tag="(.{3})"/) {
358 if ($trash->has($1) or ($c->{autoscrub} and $1 =~ /\D/))
359 { $istrash = 1; next }
367 # add 903(?) with new record id
368 if ($c->{'renumber-from'}) {
369 $recmeta{nid} = $c->{'renumber-from'};
370 push @record, join('', ' <datafield tag="', $c->{'renumber-tag'},
371 '" ind1=" " ind2=" "> <subfield code="',
372 $c->{'renumber-subfield'},
375 "</subfield></datafield>\n");
376 $c->{'renumber-from'}++;
389 open $EXMARC, '>:utf8', $c->{exception}
390 or die "Can't open exception file $!\n";
394 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
395 if(defined $recmeta{explanation});
397 # scrub newlines (unless told not to or writing exception record)
398 unless ($c->{nocollapse} or $FH eq $EXMARC)
399 { s/\n// for (@record) }
401 # actually write the record
402 print $FH @record,"\n";
404 # increment output record count (if not exception)
405 $c->{rocount}++ if ($FH eq $EXMARC);
407 # if we were dumping to exception file, nuke the record and set ptr
408 # to terminate processing loop
413 sub print_fullcontext {
414 print $OUT "\r", ' ' x 72, "\n";
415 print $OUT $c->{editmsg},"\n";
416 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
417 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
418 print $OUT " @ ", $c->{ricount}, "/", $c->{totalrecs};
424 my $upper = int($c->{window} / 2) + 1;
425 my $lower = int($c->{window} / 2) - 1;
426 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
427 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
429 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
430 print $OUT '==> |', $record[$ptr];
431 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
438 print $OUT "\r$msg at ",$c->{ricount},"/",$c->{totalrecs}, "\n";
441 #-----------------------------------------------------------------------------------
443 #-----------------------------------------------------------------------------------
448 my $ofrom = shift @chunks;
449 if ($ofrom =~ /^'/) {
450 until ($ofrom =~ /'$/ or !@chunks)
451 { $ofrom .= join(' ','',shift @chunks) }
452 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
454 my $to = shift @chunks;
456 until ($to =~ /'$/ or !@chunks)
457 { $to .= join(' ','',shift @chunks) }
458 $to =~ s/^'//; $to =~ s/'$//;
462 for my $char (split(//,$ofrom)) {
463 $char = "\\" . $char if ($char =~ /\W/);
464 $from = join('', $from, $char);
467 $recmeta{prevline} = $record[$ptr];
468 $record[$ptr] =~ s/$from/$to/;
469 $ofrom = undef; $to = undef; $from = undef;
475 $recmeta{prevline} = $record[$ptr];
476 # remove <subfield stuff; extract (probably wrong) subfield code
477 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
478 # and move to front of line
479 $record[$ptr] = join(' ', $1 , $record[$ptr]);
480 # tear off trailing subfield tag from preceeding line
481 $record[$ptr - 1] =~ s|</subfield>\n||;
482 # join current line onto preceeding line
483 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
485 my @a = @record[0 .. $ptr - 1];
486 my @b = @record[$ptr + 1 .. $#record];
488 # move record pointer to previous line
495 unless ($recmeta{prevline})
496 { print $OUT "No previously edited line to flip\n"; return }
497 my $temp = $record[$ptr];
498 $record[$ptr] = $recmeta{prevline};
499 $recmeta{prevline} = $temp;
506 $recmeta{killline} = $record[$ptr];
507 my @a = @record[0 .. $ptr - 1];
508 my @b = @record[$ptr + 1 .. $#record];
510 @a = undef; @b = undef;
516 unless ($recmeta{killline})
517 { print $OUT "No killed line to yank\n"; return }
518 my @a = @record[0 .. $ptr - 1];
519 my @b = @record[$ptr .. $#record];
520 @record = (@a, $c->{killline}, @b);
521 @a = undef; @b = undef;
526 sub insert_original {
527 $record[$ptr] = $recmeta{origline};
533 print $OUT "\nOrig. edit line :", $recmeta{origline};
534 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
535 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
541 my (@explanation) = @_;
542 $recmeta{explanation} = join(' ', 'DUMPING RECORD: Tag', $recmeta{tag}, @explanation);
543 message( $recmeta{explanation} );
544 write_record($EXMARC);
549 $ptr++ unless ($ptr == $#record);;
555 $ptr-- unless ($ptr == 0);
560 sub commit_edit { return 1 }
563 if ($c->{window} == 15)
564 { print $OUT "Window can't be bigger than 15 lines\n"; return }
570 if ($c->{window} == 5)
571 { print $OUT "Window can't be smaller than 5 lines\n"; return }
578 Type a replacement for the indicated line, or enter a command.
580 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
581 < Expand context window | k Kill current line
582 > Contract context window | y Yank last killed line
583 p Move pointer to prev line | m Merge current line into preceding line
584 n Move pointer to next line | o Insert original line
585 c Print line context | f Flip current line and last edited line
586 d Print current saved lines |
587 -----------------------------+-------------------------------------------
588 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
589 contains spaces, it must be single-quoted
590 t Commit changes and resume automated operations
591 x Dump record to exception file
600 #-----------------------------------------------------------------------
604 Performs boring script initialization. Handles argument parsing,
613 # set mode on existing filehandles
614 binmode(STDIN, ':utf8');
616 my $rc = GetOptions( $c,
624 'renumber-from|rf=i',
626 'renumber-subfield|rs=s',
628 'original-subfield|os=s',
637 show_help() unless $rc;
638 show_help() if ($c->{help});
639 show_trashhelp() if ($c->{trashhelp});
642 my $pfx = defined($c->{prefix}) ? $c->{prefix} : "bibs";
645 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
646 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
649 $c->{output} = join('.',$c->{prefix},'clean','marc','xml')
651 $c->{exception} = join('.',$c->{prefix},'exception','marc','xml')
652 unless $c->{exception};
653 $c->{marcfile} = $c->{prefix} . '.marc.xml'
654 unless $c->{marcfile};
656 show_help() unless ($c->{marcfile} and $c->{output});
658 if ($c->{trashfile}) {
659 $c->{trash} = Equinox::Migration::SimpleTagList->new(file => $c->{trashfile})
661 $c->{trash} = Equinox::Migration::SimpleTagList->new;
663 # autotrash 901, 903 unless no strip-nines
664 unless ($c->{'no-strip9'}) {
665 $c->{trash}->add_tag(901);
666 $c->{trash}->add_tag(903);
668 # remove original id sequence tag from trash hash if we know it
669 $c->{trash}->remove_tag($c->{'original-tag'})
670 if ( $c->{'original-tag'} and $c->{trash}->has($c->{'original-tag'}) );
675 Usage is: marc_cleanup [OPTIONS] <filelist>
677 --output -o Cleaned MARCXML output filename
678 --exception -x Exception (dumped records) MARCXML filename
680 --prefix=<PREFIX> -p Shared prefix for output/exception files. Will produce
681 PREFIX.clean.marc.xml and PREFIX.exception.marc.xml
683 --marcfile -m Input filename. Defaults to PREFIX.marc.xml
685 --renumber-from -rf Begin renumbering id sequence with this number
686 --renumber-tag -rt Tag to use in renumbering (default: 903)
687 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
688 --original-tag -ot Original id tag; will be kept in output even if
689 it appears in the trash file
690 --original-subfield -os Original id subfield code. If this is specified
691 and renumbering is in effect, an old-to-new mapping
692 file (old2new.map) will be generated.
694 --force-utf8 Rewrite each record so that they describe themselves as
696 --autoscrub -a Automatically remove non-numeric tags in data
697 --fix-subfield -fs Subfield code to use in place of non-alphanumeric
698 or empty subfield codes
699 --nocollapse -n Don't compress records to one line on output
700 --no-strip9 Don't autoremove 901/903 tags in data
701 --trashfile -t File containing trash tag data (see --trashhelp)
703 --fullauto No manual edits. All problematic records dumped to
714 http://intra.lan.hq.esilibrary.com/dokuwiki/doku.php?id=migration:tag_files
716 for tag file syntax information.