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 ($1)");
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 if ($record[$ptr] =~ /code=" ">c/) {
209 message('Fixing probable subfield c, scenario 1');
210 $record[$ptr] =~ s/code=" ">c/code="c">/;
212 if ($record[$ptr] =~ /code=" ">\$/) {
213 message('Fixing probable subfield c, scenario 2');
214 $record[$ptr] =~ s/code=" ">\$/code="c">\$/;
217 if ($c->{'fix-subfield'}) {
218 if ($record[$ptr] =~ /code="&">/) {
219 message('Fixing & for subfield code');
220 $record[$ptr] =~ s/code="&">/code="$c->{'fix-subfield'}">/;
222 if ($record[$ptr] =~ /code="(.*?\P{IsAlnum}.*?)">/) {
223 message("Fixing non-alphanumeric subfield code: $1 -> " . $c->{'fix-subfield'});
224 $record[$ptr] =~ s/code=".*?\P{IsAlnum}.*?">/code="$c->{'fix-subfield'}">/;
226 if ($record[$ptr] =~ /code="">/) {
227 message('Fixing null subfield code');
228 $record[$ptr] =~ s/code="">/code="$c->{'fix-subfield'}">/;
235 sub stow_record_data {
236 # get tag data if we're looking at it
238 if ($record[$ptr] =~ m/<(?:control|data)field tag="(.{3})"/) {
240 $tag = $recmeta{tag};
241 $record[$ptr] =~ m/ind1="(.)"/;
242 $recmeta{ind1} = $1 || '';
243 $record[$ptr] =~ m/ind2="(.)"/;
244 $recmeta{ind2} = $1 || '';
247 message("Autokill record: no detectable tag");
248 dump_record("No detectable tag") ;
252 # and since we are looking at a tag, see if it's the original id
253 if ($tag == $c->{'original-tag'}) {
257 if ($record[$ptr] =~ m|<controlfield tag="$tag">(.+?)</controlfield>|)
258 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
259 } elsif ($tag >= 10 and $c->{'original-subfield'}) {
261 my $line = $record[$ptr]; my $lptr = $ptr;
262 my $osub = $c->{'original-subfield'};
263 # skim to end of this tag
264 until ($line =~ m|</datafield>|) {
265 if ($line =~ /<subfield code="$osub">(.+?)</)
266 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
268 $line = $record[$lptr];
274 # didn't find the old id!
276 message("Autokill record: no oldid when old2new mapping requested");
277 dump_record("No old id found");
281 # got it; write to old->new map file
282 if ($c->{'renumber-from'} and $c->{'original-subfield'}) {
290 #-----------------------------------------------------------------------------------
292 #-----------------------------------------------------------------------------------
296 Handles the Term::ReadLine loop
303 return if $c->{trash}->has( $recmeta{tag} );
304 if ( $c->{fullauto} )
305 { dump_record($msg); return }
307 $c->{editmsg} = $msg;
310 # stow original problem line
311 $recmeta{origline} = $record[$ptr];
314 my $line = $term->readline('marc-cleanup>');
315 my @chunks = split /\s+/, $line;
317 # lines with single-character first chunks are commands.
318 # make sure they exist.
319 if (length $chunks[0] == 1) {
320 unless (defined $commands{$chunks[0]}) {
321 print $OUT "No such command '", $chunks[0], "'\n";
326 if (defined $commands{$chunks[0]}) {
327 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
330 $recmeta{prevline} = $record[$ptr];
331 $record[$ptr] = "$line\n";
335 # set pointer to top on the way out
341 Constructs record arrays from the incoming MARC file and returns them
349 my $trash = $c->{trash};
351 $l = <MARC> while (defined $l and $l !~ /<record/);
352 return $l unless defined $l;
355 for (keys %recmeta) { $recmeta{$_} = undef }
356 for (0 .. @record) { delete $record[$_] }
359 until ($l =~ m|</record>|) {
360 # clean up tags with spaces in them
361 $l =~ s/tag=" /tag="00/g;
362 $l =~ s/tag=" /tag="0/g;
363 $l =~ s/tag="-/tag="0/g;
364 $l =~ s/tag="(\d\d) /tag="0$1/g;
366 # excise unwanted tags
368 $istrash = 0 if ($l =~ m|</datafield|);
372 if ($l =~ m/<datafield tag="(.{3})"/) {
373 if ($trash->has($1) or ($c->{autoscrub} and $1 =~ /\D/))
374 { $istrash = 1; next }
382 # add 903(?) with new record id
383 if ($c->{'renumber-from'}) {
384 $recmeta{nid} = $c->{'renumber-from'};
385 push @record, join('', ' <datafield tag="', $c->{'renumber-tag'},
386 '" ind1=" " ind2=" "> <subfield code="',
387 $c->{'renumber-subfield'},
390 "</subfield></datafield>\n");
391 $c->{'renumber-from'}++;
404 open $EXMARC, '>:utf8', $c->{exception}
405 or die "Can't open exception file $!\n";
409 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
410 if(defined $recmeta{explanation});
412 # scrub newlines (unless told not to or writing exception record)
413 unless ($c->{nocollapse} or $FH eq $EXMARC)
414 { s/\n// for (@record) }
416 # actually write the record
417 print $FH @record,"\n";
419 # increment output record count (if not exception)
420 $c->{rocount}++ if ($FH eq $EXMARC);
422 # if we were dumping to exception file, nuke the record and set ptr
423 # to terminate processing loop
428 sub print_fullcontext {
429 print $OUT "\r", ' ' x 72, "\n";
430 print $OUT $c->{editmsg},"\n";
431 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
432 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
433 print $OUT " @ ", $c->{ricount}, "/", $c->{totalrecs};
439 my $upper = int($c->{window} / 2) + 1;
440 my $lower = int($c->{window} / 2) - 1;
441 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
442 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
444 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
445 print $OUT '==> |', $record[$ptr];
446 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
453 print $OUT "\r$msg at ",$c->{ricount},"/",$c->{totalrecs}, "\n";
456 #-----------------------------------------------------------------------------------
458 #-----------------------------------------------------------------------------------
463 my $ofrom = shift @chunks;
464 if ($ofrom =~ /^'/) {
465 until ($ofrom =~ /'$/ or !@chunks)
466 { $ofrom .= join(' ','',shift @chunks) }
467 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
469 my $to = shift @chunks;
471 until ($to =~ /'$/ or !@chunks)
472 { $to .= join(' ','',shift @chunks) }
473 $to =~ s/^'//; $to =~ s/'$//;
477 for my $char (split(//,$ofrom)) {
478 $char = "\\" . $char if ($char =~ /\W/);
479 $from = join('', $from, $char);
482 $recmeta{prevline} = $record[$ptr];
483 $record[$ptr] =~ s/$from/$to/;
484 $ofrom = undef; $to = undef; $from = undef;
490 $recmeta{prevline} = $record[$ptr];
491 # remove <subfield stuff; extract (probably wrong) subfield code
492 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
493 # and move to front of line
494 $record[$ptr] = join(' ', $1 , $record[$ptr]);
495 # tear off trailing subfield tag from preceeding line
496 $record[$ptr - 1] =~ s|</subfield>\n||;
497 # join current line onto preceeding line
498 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
500 my @a = @record[0 .. $ptr - 1];
501 my @b = @record[$ptr + 1 .. $#record];
503 # move record pointer to previous line
510 unless ($recmeta{prevline})
511 { print $OUT "No previously edited line to flip\n"; return }
512 my $temp = $record[$ptr];
513 $record[$ptr] = $recmeta{prevline};
514 $recmeta{prevline} = $temp;
521 $recmeta{killline} = $record[$ptr];
522 my @a = @record[0 .. $ptr - 1];
523 my @b = @record[$ptr + 1 .. $#record];
525 @a = undef; @b = undef;
531 unless ($recmeta{killline})
532 { print $OUT "No killed line to yank\n"; return }
533 my @a = @record[0 .. $ptr - 1];
534 my @b = @record[$ptr .. $#record];
535 @record = (@a, $c->{killline}, @b);
536 @a = undef; @b = undef;
541 sub insert_original {
542 $record[$ptr] = $recmeta{origline};
548 print $OUT "\nOrig. edit line :", $recmeta{origline};
549 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
550 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
556 my (@explanation) = @_;
557 $recmeta{explanation} = join(' ', 'DUMPING RECORD: Tag', $recmeta{tag}, @explanation);
558 message( $recmeta{explanation} );
559 write_record($EXMARC);
564 $ptr++ unless ($ptr == $#record);;
570 $ptr-- unless ($ptr == 0);
575 sub commit_edit { return 1 }
578 if ($c->{window} == 15)
579 { print $OUT "Window can't be bigger than 15 lines\n"; return }
585 if ($c->{window} == 5)
586 { print $OUT "Window can't be smaller than 5 lines\n"; return }
593 Type a replacement for the indicated line, or enter a command.
595 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
596 < Expand context window | k Kill current line
597 > Contract context window | y Yank last killed line
598 p Move pointer to prev line | m Merge current line into preceding line
599 n Move pointer to next line | o Insert original line
600 c Print line context | f Flip current line and last edited line
601 d Print current saved lines |
602 -----------------------------+-------------------------------------------
603 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
604 contains spaces, it must be single-quoted
605 t Commit changes and resume automated operations
606 x Dump record to exception file
615 #-----------------------------------------------------------------------
619 Performs boring script initialization. Handles argument parsing,
628 # set mode on existing filehandles
629 binmode(STDIN, ':utf8');
631 my $rc = GetOptions( $c,
639 'renumber-from|rf=i',
641 'renumber-subfield|rs=s',
643 'original-subfield|os=s',
652 show_help() unless $rc;
653 show_help() if ($c->{help});
654 show_trashhelp() if ($c->{trashhelp});
657 my $pfx = defined($c->{prefix}) ? $c->{prefix} : "bibs";
660 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
661 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
663 if ($c->{marcfile} and $c->{prefix}) { abort('You can not declare a marc file and prefix.'); }
664 if ($c->{marcfile}) {
665 $c->{output} = join('.',$c->{marcfile},'clean')
667 $c->{exception} = join('.',$c->{marcfile},'exception')
668 unless $c->{exception};
671 $c->{output} = join('.',$c->{prefix},'clean','marc','xml')
673 $c->{exception} = join('.',$c->{prefix},'exception','marc','xml')
674 unless $c->{exception};
675 $c->{marcfile} = $c->{prefix} . '.marc.xml'
676 unless $c->{marcfile};
678 show_help() unless ($c->{marcfile} and $c->{output});
680 if ($c->{trashfile}) {
681 $c->{trash} = Equinox::Migration::SimpleTagList->new(file => $c->{trashfile})
683 $c->{trash} = Equinox::Migration::SimpleTagList->new;
685 # autotrash 901, 903 unless no strip-nines
686 unless ($c->{'no-strip9'}) {
687 $c->{trash}->add_tag(901);
688 $c->{trash}->add_tag(903);
690 # remove original id sequence tag from trash hash if we know it
691 $c->{trash}->remove_tag($c->{'original-tag'})
692 if ( $c->{'original-tag'} and $c->{trash}->has($c->{'original-tag'}) );
697 print STDERR "$0: $msg", "\n";
703 Usage is: marc_cleanup [OPTIONS] <filelist>
705 --output -o Cleaned MARCXML output filename
706 --exception -x Exception (dumped records) MARCXML filename
708 --prefix=<PREFIX> -p Shared prefix for output/exception files. Will produce
709 PREFIX.clean.marc.xml and PREFIX.exception.marc.xml
711 --marcfile -m Input filename. Defaults to PREFIX.marc.xml
713 --renumber-from -rf Begin renumbering id sequence with this number
714 --renumber-tag -rt Tag to use in renumbering (default: 903)
715 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
716 --original-tag -ot Original id tag; will be kept in output even if
717 it appears in the trash file
718 --original-subfield -os Original id subfield code. If this is specified
719 and renumbering is in effect, an old-to-new mapping
720 file (old2new.map) will be generated.
722 --force-utf8 Rewrite each record so that they describe themselves as
724 --autoscrub -a Automatically remove non-numeric tags in data
725 --fix-subfield -fs Subfield code to use in place of non-alphanumeric
726 or empty subfield codes
727 --nocollapse -n Don't compress records to one line on output
728 --no-strip9 Don't autoremove 901/903 tags in data
729 --trashfile -t File containing trash tag data (see --trashhelp)
731 --fullauto No manual edits. All problematic records dumped to
742 http://intra.lan.hq.esilibrary.com/dokuwiki/doku.php?id=migration:tag_files
744 for tag file syntax information.