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 ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
183 if (length $content < 40) {
184 $content .= ' ' x (40 - length($content));
185 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
186 message("Short 008 padded");
190 # clean misplaced dollarsigns
191 if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
192 $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
193 message("Dollar sign corrected");
196 # excessive trailing whitespace in subfield contents
197 if ($record[$ptr] =~ m|\s{10,}</subfield>|) {
198 $record[$ptr] =~ s|\s{10,}</subfield>|</subfield>|;
199 message("Trailing whitespace trimmed from subfield contents");
202 # automatable subfield maladies
203 $record[$ptr] =~ s/code=" ">c/code="c">/;
204 $record[$ptr] =~ s/code=" ">\$/code="c">\$/;
206 if ($c->{'fix-subfield'}) {
207 $record[$ptr] =~ s/code="&">/code="$c->{'fix-subfield'}">/;
208 $record[$ptr] =~ s/code="\P{IsAlnum}">/code="$c->{'fix-subfield'}">/;
209 $record[$ptr] =~ s/code="">/code="$c->{'fix-subfield'}">/;
215 sub stow_record_data {
216 # get tag data if we're looking at it
218 if ($record[$ptr] =~ m/<(?:control|data)field tag="(.{3})"/) {
220 $tag = $recmeta{tag};
221 $record[$ptr] =~ m/ind1="(.)"/;
222 $recmeta{ind1} = $1 || '';
223 $record[$ptr] =~ m/ind2="(.)"/;
224 $recmeta{ind2} = $1 || '';
227 message("Autokill record: no detectable tag");
228 dump_record("No detectable tag") ;
232 # and since we are looking at a tag, see if it's the original id
233 if ($tag == $c->{'original-tag'}) {
237 if ($record[$ptr] =~ m|<controlfield tag="$tag">(.+?)</controlfield>|)
238 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
239 } elsif ($tag >= 10 and $c->{'original-subfield'}) {
241 my $line = $record[$ptr]; my $lptr = $ptr;
242 my $osub = $c->{'original-subfield'};
243 # skim to end of this tag
244 until ($line =~ m|</datafield>|) {
245 if ($line =~ /<subfield code="$osub">(.+?)</)
246 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
248 $line = $record[$lptr];
254 # didn't find the old id!
256 message("Autokill record: no oldid when old2new mapping requested");
257 dump_record("No old id found");
261 # got it; write to old->new map file
262 if ($c->{'renumber-from'} and $c->{'original-subfield'}) {
270 #-----------------------------------------------------------------------------------
272 #-----------------------------------------------------------------------------------
276 Handles the Term::ReadLine loop
283 return if $c->{trash}->has( $recmeta{tag} );
284 if ( $c->{fullauto} )
285 { dump_record($msg); return }
287 $c->{editmsg} = $msg;
290 # stow original problem line
291 $recmeta{origline} = $record[$ptr];
294 my $line = $term->readline('marc-cleanup>');
295 my @chunks = split /\s+/, $line;
297 # lines with single-character first chunks are commands.
298 # make sure they exist.
299 if (length $chunks[0] == 1) {
300 unless (defined $commands{$chunks[0]}) {
301 print $OUT "No such command '", $chunks[0], "'\n";
306 if (defined $commands{$chunks[0]}) {
307 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
310 $recmeta{prevline} = $record[$ptr];
311 $record[$ptr] = "$line\n";
315 # set pointer to top on the way out
321 Constructs record arrays from the incoming MARC file and returns them
329 my $trash = $c->{trash};
331 $l = <MARC> while (defined $l and $l !~ /<record/);
332 return $l unless defined $l;
335 for (keys %recmeta) { $recmeta{$_} = undef }
336 for (0 .. @record) { delete $record[$_] }
339 until ($l =~ m|</record>|) {
340 # clean up tags with spaces in them
341 $l =~ s/tag=" /tag="00/g;
342 $l =~ s/tag=" /tag="0/g;
343 $l =~ s/tag="-/tag="0/g;
344 $l =~ s/tag="(\d\d) /tag="0$1/g;
346 # excise unwanted tags
348 $istrash = 0 if ($l =~ m|</datafield|);
352 if ($l =~ m/<datafield tag="(.{3})"/) {
353 if ($trash->has($1) or ($c->{autoscrub} and $1 =~ /\D/))
354 { $istrash = 1; next }
362 # add 903(?) with new record id
363 if ($c->{'renumber-from'}) {
364 $recmeta{nid} = $c->{'renumber-from'};
365 push @record, join('', ' <datafield tag="', $c->{'renumber-tag'},
366 '" ind1=" " ind2=" "> <subfield code="',
367 $c->{'renumber-subfield'},
370 "</subfield></datafield>\n");
371 $c->{'renumber-from'}++;
384 open $EXMARC, '>:utf8', $c->{exception}
385 or die "Can't open exception file $!\n";
389 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
390 if(defined $recmeta{explanation});
392 # scrub newlines (unless told not to or writing exception record)
393 unless ($c->{nocollapse} or $FH eq $EXMARC)
394 { s/\n// for (@record) }
396 # actually write the record
397 print $FH @record,"\n";
399 # increment output record count (if not exception)
400 $c->{rocount}++ if ($FH eq $EXMARC);
402 # if we were dumping to exception file, nuke the record and set ptr
403 # to terminate processing loop
408 sub print_fullcontext {
409 print $OUT "\r", ' ' x 72, "\n";
410 print $OUT $c->{editmsg},"\n";
411 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
412 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
413 print $OUT " @ ", $c->{ricount}, "/", $c->{totalrecs};
419 my $upper = int($c->{window} / 2) + 1;
420 my $lower = int($c->{window} / 2) - 1;
421 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
422 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
424 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
425 print $OUT '==> |', $record[$ptr];
426 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
433 print $OUT "\r$msg at ",$c->{ricount},"/",$c->{totalrecs}, "\n";
436 #-----------------------------------------------------------------------------------
438 #-----------------------------------------------------------------------------------
443 my $ofrom = shift @chunks;
444 if ($ofrom =~ /^'/) {
445 until ($ofrom =~ /'$/ or !@chunks)
446 { $ofrom .= join(' ','',shift @chunks) }
447 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
449 my $to = shift @chunks;
451 until ($to =~ /'$/ or !@chunks)
452 { $to .= join(' ','',shift @chunks) }
453 $to =~ s/^'//; $to =~ s/'$//;
457 for my $char (split(//,$ofrom)) {
458 $char = "\\" . $char if ($char =~ /\W/);
459 $from = join('', $from, $char);
462 $recmeta{prevline} = $record[$ptr];
463 $record[$ptr] =~ s/$from/$to/;
464 $ofrom = undef; $to = undef; $from = undef;
470 $recmeta{prevline} = $record[$ptr];
471 # remove <subfield stuff; extract (probably wrong) subfield code
472 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
473 # and move to front of line
474 $record[$ptr] = join(' ', $1 , $record[$ptr]);
475 # tear off trailing subfield tag from preceeding line
476 $record[$ptr - 1] =~ s|</subfield>\n||;
477 # join current line onto preceeding line
478 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
480 my @a = @record[0 .. $ptr - 1];
481 my @b = @record[$ptr + 1 .. $#record];
483 # move record pointer to previous line
490 unless ($recmeta{prevline})
491 { print $OUT "No previously edited line to flip\n"; return }
492 my $temp = $record[$ptr];
493 $record[$ptr] = $recmeta{prevline};
494 $recmeta{prevline} = $temp;
501 $recmeta{killline} = $record[$ptr];
502 my @a = @record[0 .. $ptr - 1];
503 my @b = @record[$ptr + 1 .. $#record];
505 @a = undef; @b = undef;
511 unless ($recmeta{killline})
512 { print $OUT "No killed line to yank\n"; return }
513 my @a = @record[0 .. $ptr - 1];
514 my @b = @record[$ptr .. $#record];
515 @record = (@a, $c->{killline}, @b);
516 @a = undef; @b = undef;
521 sub insert_original {
522 $record[$ptr] = $recmeta{origline};
528 print $OUT "\nOrig. edit line :", $recmeta{origline};
529 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
530 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
536 my (@explanation) = @_;
537 $recmeta{explanation} = join(' ', 'DUMPING RECORD: Tag', $recmeta{tag}, @explanation);
538 message( $recmeta{explanation} );
539 write_record($EXMARC);
544 $ptr++ unless ($ptr == $#record);;
550 $ptr-- unless ($ptr == 0);
555 sub commit_edit { return 1 }
558 if ($c->{window} == 15)
559 { print $OUT "Window can't be bigger than 15 lines\n"; return }
565 if ($c->{window} == 5)
566 { print $OUT "Window can't be smaller than 5 lines\n"; return }
573 Type a replacement for the indicated line, or enter a command.
575 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
576 < Expand context window | k Kill current line
577 > Contract context window | y Yank last killed line
578 p Move pointer to prev line | m Merge current line into preceding line
579 n Move pointer to next line | o Insert original line
580 c Print line context | f Flip current line and last edited line
581 d Print current saved lines |
582 -----------------------------+-------------------------------------------
583 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
584 contains spaces, it must be single-quoted
585 t Commit changes and resume automated operations
586 x Dump record to exception file
595 #-----------------------------------------------------------------------
599 Performs boring script initialization. Handles argument parsing,
608 # set mode on existing filehandles
609 binmode(STDIN, ':utf8');
611 my $rc = GetOptions( $c,
619 'renumber-from|rf=i',
621 'renumber-subfield|rs=s',
623 'original-subfield|os=s',
631 show_help() unless $rc;
632 show_help() if ($c->{help});
633 show_trashhelp() if ($c->{trashhelp});
636 my $pfx = defined($c->{prefix}) ? $c->{prefix} : "bibs";
639 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
640 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
643 $c->{output} = join('.',$c->{prefix},'clean','marc','xml')
645 $c->{exception} = join('.',$c->{prefix},'exception','marc','xml')
646 unless $c->{exception};
647 $c->{marcfile} = $c->{prefix} . '.marc.xml'
648 unless $c->{marcfile};
650 show_help() unless ($c->{marcfile} and $c->{output});
652 if ($c->{trashfile}) {
653 $c->{trash} = Equinox::Migration::SimpleTagList->new(file => $c->{trashfile})
655 $c->{trash} = Equinox::Migration::SimpleTagList->new;
657 # autotrash 901, 903 unless no strip-nines
658 unless ($c->{'no-strip9'}) {
659 $c->{trash}->add_tag(901);
660 $c->{trash}->add_tag(903);
662 # remove original id sequence tag from trash hash if we know it
663 $c->{trash}->remove_tag($c->{'original-tag'})
664 if ( $c->{'original-tag'} and $c->{trash}->has($c->{'original-tag'}) );
669 Usage is: marc_cleanup [OPTIONS] <filelist>
671 --output -o Cleaned MARCXML output filename
672 --exception -x Exception (dumped records) MARCXML filename
674 --prefix=<PREFIX> -p Shared prefix for output/exception files. Will produce
675 PREFIX.clean.marc.xml and PREFIX.exception.marc.xml
677 --marcfile -m Input filename. Defaults to PREFIX.marc.xml
679 --renumber-from -rf Begin renumbering id sequence with this number
680 --renumber-tag -rt Tag to use in renumbering (default: 903)
681 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
682 --original-tag -ot Original id tag; will be kept in output even if
683 it appears in the trash file
684 --original-subfield -os Original id subfield code. If this is specified
685 and renumbering is in effect, an old-to-new mapping
686 file (old2new.map) will be generated.
688 --autoscrub -a Automatically remove non-numeric tags in data
689 --fix-subfield -fs Subfield code to use in place of non-alphanumeric
690 or empty subfield codes
691 --nocollapse -n Don't compress records to one line on output
692 --no-strip9 Don't autoremove 901/903 tags in data
693 --trashfile -t File containing trash tag data (see --trashhelp)
695 --fullauto No manual edits. All problematic records dumped to
706 http://intra.lan.hq.esilibrary.com/dokuwiki/doku.php?id=migration:tag_files
708 for tag file syntax information.