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 # automatable subfield maladies
197 $record[$ptr] =~ s/code=" ">c/code="c">/;
198 $record[$ptr] =~ s/code=" ">\$/code="c">\$/;
203 sub stow_record_data {
204 # get tag data if we're looking at it
206 if ($record[$ptr] =~ m/<(?:control|data)field tag="(.{3})"/) {
208 $tag = $recmeta{tag};
209 $record[$ptr] =~ m/ind1="(.)"/;
210 $recmeta{ind1} = $1 || '';
211 $record[$ptr] =~ m/ind2="(.)"/;
212 $recmeta{ind2} = $1 || '';
215 message("Autokill record: no detectable tag");
216 dump_record("No detectable tag") ;
220 # and since we are looking at a tag, see if it's the original id
221 if ($tag == $c->{'original-tag'}) {
225 if ($record[$ptr] =~ m|<controlfield tag="$tag">(.+?)</controlfield>|)
226 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
227 } elsif ($tag >= 10 and $c->{'original-subfield'}) {
229 my $line = $record[$ptr]; my $lptr = $ptr;
230 my $osub = $c->{'original-subfield'};
231 # skim to end of this tag
232 until ($line =~ m|</datafield>|) {
233 if ($line =~ /<subfield code="$osub">(.+?)</)
234 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
236 $line = $record[$lptr];
242 # didn't find the old id!
244 message("Autokill record: no oldid when old2new mapping requested");
245 dump_record("No old id found");
249 # got it; write to old->new map file
250 if ($c->{'renumber-from'} and $c->{'original-subfield'}) {
258 #-----------------------------------------------------------------------------------
260 #-----------------------------------------------------------------------------------
264 Handles the Term::ReadLine loop
271 return if $c->{trash}->has( $recmeta{tag} );
272 if ( $c->{fullauto} )
273 { dump_record($msg); return }
275 $c->{editmsg} = $msg;
278 # stow original problem line
279 $recmeta{origline} = $record[$ptr];
282 my $line = $term->readline('marc-cleanup>');
283 my @chunks = split /\s+/, $line;
285 # lines with single-character first chunks are commands.
286 # make sure they exist.
287 if (length $chunks[0] == 1) {
288 unless (defined $commands{$chunks[0]}) {
289 print $OUT "No such command '", $chunks[0], "'\n";
294 if (defined $commands{$chunks[0]}) {
295 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
298 $recmeta{prevline} = $record[$ptr];
299 $record[$ptr] = "$line\n";
303 # set pointer to top on the way out
309 Constructs record arrays from the incoming MARC file and returns them
317 my $trash = $c->{trash};
319 $l = <MARC> while (defined $l and $l !~ /<record>/);
320 return $l unless defined $l;
323 for (keys %recmeta) { $recmeta{$_} = undef }
324 for (0 .. @record) { delete $record[$_] }
327 until ($l =~ m|</record>|) {
328 # clean up tags with spaces in them
329 $l =~ s/tag=" /tag="00/g;
330 $l =~ s/tag=" /tag="0/g;
331 $l =~ s/tag="-/tag="0/g;
332 $l =~ s/tag="(\d\d) /tag="0$1/g;
334 # excise unwanted tags
336 $istrash = 0 if ($l =~ m|</datafield|);
340 if ($l =~ m/<datafield tag="(.{3})"/) {
341 if ($trash->has($1) or ($c->{autoscrub} and $1 =~ /\D/))
342 { $istrash = 1; next }
350 # add 903(?) with new record id
351 if ($c->{'renumber-from'}) {
352 $recmeta{nid} = $c->{'renumber-from'};
353 push @record, join('', ' <datafield tag="', $c->{'renumber-tag'},
354 '" ind1=" " ind2=" "> <subfield code="',
355 $c->{'renumber-subfield'},
358 "</subfield></datafield>\n");
359 $c->{'renumber-from'}++;
372 open $EXMARC, '>:utf8', $c->{exception}
373 or die "Can't open exception file $!\n";
377 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
378 if(defined $recmeta{explanation});
380 # scrub newlines (unless told not to or writing exception record)
381 unless ($c->{nocollapse} or $FH eq $EXMARC)
382 { s/\n// for (@record) }
384 # actually write the record
385 print $FH @record,"\n";
387 # increment output record count (if not exception)
388 $c->{rocount}++ if ($FH eq $EXMARC);
390 # if we were dumping to exception file, nuke the record and set ptr
391 # to terminate processing loop
396 sub print_fullcontext {
397 print $OUT "\r", ' ' x 72, "\n";
398 print $OUT $c->{editmsg},"\n";
399 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
400 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
401 print $OUT " @ ", $c->{ricount}, "/", $c->{totalrecs};
407 my $upper = int($c->{window} / 2) + 1;
408 my $lower = int($c->{window} / 2) - 1;
409 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
410 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
412 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
413 print $OUT '==> |', $record[$ptr];
414 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
421 print $OUT "\r$msg at ",$c->{ricount},"/",$c->{totalrecs}, "\n";
424 #-----------------------------------------------------------------------------------
426 #-----------------------------------------------------------------------------------
431 my $ofrom = shift @chunks;
432 if ($ofrom =~ /^'/) {
433 until ($ofrom =~ /'$/ or !@chunks)
434 { $ofrom .= join(' ','',shift @chunks) }
435 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
437 my $to = shift @chunks;
439 until ($to =~ /'$/ or !@chunks)
440 { $to .= join(' ','',shift @chunks) }
441 $to =~ s/^'//; $to =~ s/'$//;
445 for my $char (split(//,$ofrom)) {
446 $char = "\\" . $char if ($char =~ /\W/);
447 $from = join('', $from, $char);
450 $recmeta{prevline} = $record[$ptr];
451 $record[$ptr] =~ s/$from/$to/;
452 $ofrom = undef; $to = undef; $from = undef;
458 $recmeta{prevline} = $record[$ptr];
459 # remove <subfield stuff; extract (probably wrong) subfield code
460 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
461 # and move to front of line
462 $record[$ptr] = join(' ', $1 , $record[$ptr]);
463 # tear off trailing subfield tag from preceeding line
464 $record[$ptr - 1] =~ s|</subfield>\n||;
465 # join current line onto preceeding line
466 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
468 my @a = @record[0 .. $ptr - 1];
469 my @b = @record[$ptr + 1 .. $#record];
471 # move record pointer to previous line
478 unless ($recmeta{prevline})
479 { print $OUT "No previously edited line to flip\n"; return }
480 my $temp = $record[$ptr];
481 $record[$ptr] = $recmeta{prevline};
482 $recmeta{prevline} = $temp;
489 $recmeta{killline} = $record[$ptr];
490 my @a = @record[0 .. $ptr - 1];
491 my @b = @record[$ptr + 1 .. $#record];
493 @a = undef; @b = undef;
499 unless ($recmeta{killline})
500 { print $OUT "No killed line to yank\n"; return }
501 my @a = @record[0 .. $ptr - 1];
502 my @b = @record[$ptr .. $#record];
503 @record = (@a, $c->{killline}, @b);
504 @a = undef; @b = undef;
509 sub insert_original {
510 $record[$ptr] = $recmeta{origline};
516 print $OUT "\nOrig. edit line :", $recmeta{origline};
517 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
518 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
524 my (@explanation) = @_;
525 $recmeta{explanation} = join(' ', 'DUMPING RECORD: Tag', $recmeta{tag}, @explanation);
526 message( $recmeta{explanation} );
527 write_record($EXMARC);
532 $ptr++ unless ($ptr == $#record);;
538 $ptr-- unless ($ptr == 0);
543 sub commit_edit { return 1 }
546 if ($c->{window} == 15)
547 { print $OUT "Window can't be bigger than 15 lines\n"; return }
553 if ($c->{window} == 5)
554 { print $OUT "Window can't be smaller than 5 lines\n"; return }
561 Type a replacement for the indicated line, or enter a command.
563 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
564 < Expand context window | k Kill current line
565 > Contract context window | y Yank last killed line
566 p Move pointer to prev line | m Merge current line into preceding line
567 n Move pointer to next line | o Insert original line
568 c Print line context | f Flip current line and last edited line
569 d Print current saved lines |
570 -----------------------------+-------------------------------------------
571 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
572 contains spaces, it must be single-quoted
573 t Commit changes and resume automated operations
574 x Dump record to exception file
583 #-----------------------------------------------------------------------
587 Performs boring script initialization. Handles argument parsing,
596 # set mode on existing filehandles
597 binmode(STDIN, ':utf8');
599 my $rc = GetOptions( $c,
607 'renumber-from|rf=i',
609 'renumber-subfield|rs=s',
611 'original-subfield|os=s',
618 show_help() unless $rc;
619 show_help() if ($c->{help});
620 show_trashhelp() if ($c->{trashhelp});
623 my $pfx = defined($c->{prefix}) ? $c->{prefix} : "bibs";
626 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
627 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
630 $c->{output} = join('.',$c->{prefix},'clean','marc','xml')
632 $c->{exception} = join('.',$c->{prefix},'exception','marc','xml')
633 unless $c->{exception};
634 $c->{marcfile} = $c->{prefix} . '.marc.xml'
635 unless $c->{marcfile};
637 show_help() unless ($c->{marcfile} and $c->{output});
639 if ($c->{trashfile}) {
640 $c->{trash} = Equinox::Migration::SimpleTagList->new(file => $c->{trashfile})
642 $c->{trash} = Equinox::Migration::SimpleTagList->new;
644 # autotrash 901, 903 unless no strip-nines
645 unless ($c->{'no-strip9'}) {
646 $c->{trash}->add_tag(901);
647 $c->{trash}->add_tag(903);
649 # remove original id sequence tag from trash hash if we know it
650 $c->{trash}->remove_tag($c->{'original-tag'})
651 if ( $c->{'original-tag'} and $c->{trash}->has($c->{'original-tag'}) );
656 Usage is: marc_cleanup [OPTIONS] <filelist>
658 --output -o Cleaned MARCXML output filename
659 --exception -x Exception (dumped records) MARCXML filename
661 --prefix=<PREFIX> -p Shared prefix for output/exception files. Will produce
662 PREFIX.clean.marc.xml and PREFIX.exception.marc.xml
664 --marcfile -m Input filename. Defaults to PREFIX.marc.xml
666 --renumber-from -rf Begin renumbering id sequence with this number
667 --renumber-tag -rt Tag to use in renumbering (default: 903)
668 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
669 --original-tag -ot Original id tag; will be kept in output even if
670 it appears in the trash file
671 --original-subfield -os Original id subfield code. If this is specified
672 and renumbering is in effect, an old-to-new mapping
673 file (old2new.map) will be generated.
675 --autoscrub -a Automatically remove non-numeric tags in data
676 --nocollapse -n Don't compress records to one line on output
677 --no-strip9 Don't autoremove 901/903 tags in data
678 --trashfile -t File containing trash tag data (see --trashhelp)
680 --fullauto No manual edits. All problematic records dumped to
691 http://intra.lan.hq.esilibrary.com/dokuwiki/doku.php?id=migration:tag_files
693 for tag file syntax information.