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 non-alphanumeric
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">\$/;
209 sub stow_record_data {
210 # get tag data if we're looking at it
212 if ($record[$ptr] =~ m/<(?:control|data)field tag="(.{3})"/) {
214 $tag = $recmeta{tag};
215 $record[$ptr] =~ m/ind1="(.)"/;
216 $recmeta{ind1} = $1 || '';
217 $record[$ptr] =~ m/ind2="(.)"/;
218 $recmeta{ind2} = $1 || '';
221 message("Autokill record: no detectable tag");
222 dump_record("No detectable tag") ;
226 # and since we are looking at a tag, see if it's the original id
227 if ($tag == $c->{'original-tag'}) {
231 if ($record[$ptr] =~ m|<controlfield tag="$tag">(.+?)</controlfield>|)
232 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
233 } elsif ($tag >= 10 and $c->{'original-subfield'}) {
235 my $line = $record[$ptr]; my $lptr = $ptr;
236 my $osub = $c->{'original-subfield'};
237 # skim to end of this tag
238 until ($line =~ m|</datafield>|) {
239 if ($line =~ /<subfield code="$osub">(.+?)</)
240 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
242 $line = $record[$lptr];
248 # didn't find the old id!
250 message("Autokill record: no oldid when old2new mapping requested");
251 dump_record("No old id found");
255 # got it; write to old->new map file
256 if ($c->{'renumber-from'} and $c->{'original-subfield'}) {
264 #-----------------------------------------------------------------------------------
266 #-----------------------------------------------------------------------------------
270 Handles the Term::ReadLine loop
277 return if $c->{trash}->has( $recmeta{tag} );
278 if ( $c->{fullauto} )
279 { dump_record($msg); return }
281 $c->{editmsg} = $msg;
284 # stow original problem line
285 $recmeta{origline} = $record[$ptr];
288 my $line = $term->readline('marc-cleanup>');
289 my @chunks = split /\s+/, $line;
291 # lines with single-character first chunks are commands.
292 # make sure they exist.
293 if (length $chunks[0] == 1) {
294 unless (defined $commands{$chunks[0]}) {
295 print $OUT "No such command '", $chunks[0], "'\n";
300 if (defined $commands{$chunks[0]}) {
301 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
304 $recmeta{prevline} = $record[$ptr];
305 $record[$ptr] = "$line\n";
309 # set pointer to top on the way out
315 Constructs record arrays from the incoming MARC file and returns them
323 my $trash = $c->{trash};
325 $l = <MARC> while (defined $l and $l !~ /<record/);
326 return $l unless defined $l;
329 for (keys %recmeta) { $recmeta{$_} = undef }
330 for (0 .. @record) { delete $record[$_] }
333 until ($l =~ m|</record>|) {
334 # clean up tags with spaces in them
335 $l =~ s/tag=" /tag="00/g;
336 $l =~ s/tag=" /tag="0/g;
337 $l =~ s/tag="-/tag="0/g;
338 $l =~ s/tag="(\d\d) /tag="0$1/g;
340 # excise unwanted tags
342 $istrash = 0 if ($l =~ m|</datafield|);
346 if ($l =~ m/<datafield tag="(.{3})"/) {
347 if ($trash->has($1) or ($c->{autoscrub} and $1 =~ /\D/))
348 { $istrash = 1; next }
356 # add 903(?) with new record id
357 if ($c->{'renumber-from'}) {
358 $recmeta{nid} = $c->{'renumber-from'};
359 push @record, join('', ' <datafield tag="', $c->{'renumber-tag'},
360 '" ind1=" " ind2=" "> <subfield code="',
361 $c->{'renumber-subfield'},
364 "</subfield></datafield>\n");
365 $c->{'renumber-from'}++;
378 open $EXMARC, '>:utf8', $c->{exception}
379 or die "Can't open exception file $!\n";
383 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
384 if(defined $recmeta{explanation});
386 # scrub newlines (unless told not to or writing exception record)
387 unless ($c->{nocollapse} or $FH eq $EXMARC)
388 { s/\n// for (@record) }
390 # actually write the record
391 print $FH @record,"\n";
393 # increment output record count (if not exception)
394 $c->{rocount}++ if ($FH eq $EXMARC);
396 # if we were dumping to exception file, nuke the record and set ptr
397 # to terminate processing loop
402 sub print_fullcontext {
403 print $OUT "\r", ' ' x 72, "\n";
404 print $OUT $c->{editmsg},"\n";
405 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
406 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
407 print $OUT " @ ", $c->{ricount}, "/", $c->{totalrecs};
413 my $upper = int($c->{window} / 2) + 1;
414 my $lower = int($c->{window} / 2) - 1;
415 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
416 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
418 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
419 print $OUT '==> |', $record[$ptr];
420 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
427 print $OUT "\r$msg at ",$c->{ricount},"/",$c->{totalrecs}, "\n";
430 #-----------------------------------------------------------------------------------
432 #-----------------------------------------------------------------------------------
437 my $ofrom = shift @chunks;
438 if ($ofrom =~ /^'/) {
439 until ($ofrom =~ /'$/ or !@chunks)
440 { $ofrom .= join(' ','',shift @chunks) }
441 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
443 my $to = shift @chunks;
445 until ($to =~ /'$/ or !@chunks)
446 { $to .= join(' ','',shift @chunks) }
447 $to =~ s/^'//; $to =~ s/'$//;
451 for my $char (split(//,$ofrom)) {
452 $char = "\\" . $char if ($char =~ /\W/);
453 $from = join('', $from, $char);
456 $recmeta{prevline} = $record[$ptr];
457 $record[$ptr] =~ s/$from/$to/;
458 $ofrom = undef; $to = undef; $from = undef;
464 $recmeta{prevline} = $record[$ptr];
465 # remove <subfield stuff; extract (probably wrong) subfield code
466 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
467 # and move to front of line
468 $record[$ptr] = join(' ', $1 , $record[$ptr]);
469 # tear off trailing subfield tag from preceeding line
470 $record[$ptr - 1] =~ s|</subfield>\n||;
471 # join current line onto preceeding line
472 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
474 my @a = @record[0 .. $ptr - 1];
475 my @b = @record[$ptr + 1 .. $#record];
477 # move record pointer to previous line
484 unless ($recmeta{prevline})
485 { print $OUT "No previously edited line to flip\n"; return }
486 my $temp = $record[$ptr];
487 $record[$ptr] = $recmeta{prevline};
488 $recmeta{prevline} = $temp;
495 $recmeta{killline} = $record[$ptr];
496 my @a = @record[0 .. $ptr - 1];
497 my @b = @record[$ptr + 1 .. $#record];
499 @a = undef; @b = undef;
505 unless ($recmeta{killline})
506 { print $OUT "No killed line to yank\n"; return }
507 my @a = @record[0 .. $ptr - 1];
508 my @b = @record[$ptr .. $#record];
509 @record = (@a, $c->{killline}, @b);
510 @a = undef; @b = undef;
515 sub insert_original {
516 $record[$ptr] = $recmeta{origline};
522 print $OUT "\nOrig. edit line :", $recmeta{origline};
523 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
524 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
530 my (@explanation) = @_;
531 $recmeta{explanation} = join(' ', 'DUMPING RECORD: Tag', $recmeta{tag}, @explanation);
532 message( $recmeta{explanation} );
533 write_record($EXMARC);
538 $ptr++ unless ($ptr == $#record);;
544 $ptr-- unless ($ptr == 0);
549 sub commit_edit { return 1 }
552 if ($c->{window} == 15)
553 { print $OUT "Window can't be bigger than 15 lines\n"; return }
559 if ($c->{window} == 5)
560 { print $OUT "Window can't be smaller than 5 lines\n"; return }
567 Type a replacement for the indicated line, or enter a command.
569 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
570 < Expand context window | k Kill current line
571 > Contract context window | y Yank last killed line
572 p Move pointer to prev line | m Merge current line into preceding line
573 n Move pointer to next line | o Insert original line
574 c Print line context | f Flip current line and last edited line
575 d Print current saved lines |
576 -----------------------------+-------------------------------------------
577 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
578 contains spaces, it must be single-quoted
579 t Commit changes and resume automated operations
580 x Dump record to exception file
589 #-----------------------------------------------------------------------
593 Performs boring script initialization. Handles argument parsing,
602 # set mode on existing filehandles
603 binmode(STDIN, ':utf8');
605 my $rc = GetOptions( $c,
613 'renumber-from|rf=i',
615 'renumber-subfield|rs=s',
617 'original-subfield|os=s',
624 show_help() unless $rc;
625 show_help() if ($c->{help});
626 show_trashhelp() if ($c->{trashhelp});
629 my $pfx = defined($c->{prefix}) ? $c->{prefix} : "bibs";
632 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
633 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
636 $c->{output} = join('.',$c->{prefix},'clean','marc','xml')
638 $c->{exception} = join('.',$c->{prefix},'exception','marc','xml')
639 unless $c->{exception};
640 $c->{marcfile} = $c->{prefix} . '.marc.xml'
641 unless $c->{marcfile};
643 show_help() unless ($c->{marcfile} and $c->{output});
645 if ($c->{trashfile}) {
646 $c->{trash} = Equinox::Migration::SimpleTagList->new(file => $c->{trashfile})
648 $c->{trash} = Equinox::Migration::SimpleTagList->new;
650 # autotrash 901, 903 unless no strip-nines
651 unless ($c->{'no-strip9'}) {
652 $c->{trash}->add_tag(901);
653 $c->{trash}->add_tag(903);
655 # remove original id sequence tag from trash hash if we know it
656 $c->{trash}->remove_tag($c->{'original-tag'})
657 if ( $c->{'original-tag'} and $c->{trash}->has($c->{'original-tag'}) );
662 Usage is: marc_cleanup [OPTIONS] <filelist>
664 --output -o Cleaned MARCXML output filename
665 --exception -x Exception (dumped records) MARCXML filename
667 --prefix=<PREFIX> -p Shared prefix for output/exception files. Will produce
668 PREFIX.clean.marc.xml and PREFIX.exception.marc.xml
670 --marcfile -m Input filename. Defaults to PREFIX.marc.xml
672 --renumber-from -rf Begin renumbering id sequence with this number
673 --renumber-tag -rt Tag to use in renumbering (default: 903)
674 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
675 --original-tag -ot Original id tag; will be kept in output even if
676 it appears in the trash file
677 --original-subfield -os Original id subfield code. If this is specified
678 and renumbering is in effect, an old-to-new mapping
679 file (old2new.map) will be generated.
681 --autoscrub -a Automatically remove non-numeric tags in data
682 --nocollapse -n Don't compress records to one line on output
683 --no-strip9 Don't autoremove 901/903 tags in data
684 --trashfile -t File containing trash tag data (see --trashhelp)
686 --fullauto No manual edits. All problematic records dumped to
697 http://intra.lan.hq.esilibrary.com/dokuwiki/doku.php?id=migration:tag_files
699 for tag file syntax information.