9 use Equinox::Migration::SimpleTagList;
11 my $term = new Term::ReadLine 'yaz-cleanup';
12 my $OUT = $term->OUT || \*STDOUT;
13 binmode STDOUT, ":utf8";
14 binmode $OUT, ":utf8";
18 # initialization and setup
22 # set up files, since everything appears to be in order
23 open MARC, '<:utf8', $c->{marcfile}
24 or die "Can't open input file $!\n";
25 open my $NUMARC, '>:utf8', $c->{output}
26 or die "Can't open output file $!\n";
27 open my $OLD2NEW, '>', 'old2new.map'
28 if ($c->{'renumber-from'} and $c->{'original-tag'});
30 print $NUMARC "<collection xmlns=\"http://www.loc.gov/MARC21/slim\">\n";
32 $c->{totalrecs} = `grep -c '<record' $c->{marcfile}`;
33 chomp $c->{totalrecs};
36 my @record; # current record storage
37 my %recmeta; # metadata about current record
38 my $ptr = 0; # record index pointer
40 # this is the dispatch table which drives command selection in
42 my %commands = ( c => \&print_fullcontext,
45 '<' => \&widen_window,
46 '>' => \&narrow_window,
48 o => \&insert_original,
62 my @spinner = qw(- \\ | /);
65 while ( buildrecord() ) {
66 unless ($c->{ricount} % 50) {
67 $c->{percent} = int(($c->{ricount} / $c->{totalrecs}) * 100);
68 print "\rWorking (",$c->{percent},"%) ", $spinner[$sidx];
69 $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
72 my $rc = do_automated_cleanups();
76 until ($ptr == $#record) {
77 # get datafield/tag data if we have it
78 $rc = stow_record_data() if ($c->{'renumber-from'} and $c->{'original-tag'});
82 if ($record[$ptr] =~ /&/ && $record[$ptr] !~ /&\w+?;/)
83 { edit("Naked ampersand"); $ptr= 0; next }
85 if ($record[$ptr] =~ /<datafield tag="(.+?)"/) {
87 # tags must be numeric
89 edit("Non-numerics in tag") unless $c->{autoscrub};
94 # subfields can't be non-alphanumeric
95 if ($record[$ptr] =~ /<subfield code="(.*?)"/) {
96 if ($1 =~ /\P{IsAlnum}/ or $1 eq '') {
97 edit("Junk in subfield code/Null subfield code");
101 # subfields can't be non-alphanumeric
102 if ($record[$ptr] =~ /<subfield code="(\w{2,})"/) {
103 edit("Subfield code larger than 1 char");
109 write_record($NUMARC);
111 print $NUMARC "</collection>\n";
112 print $OUT "\nDone. ",$c->{ricount}," in; ",$c->{rocount}," dumped \n";
115 #-----------------------------------------------------------------------------------
117 #-----------------------------------------------------------------------------------
119 sub do_automated_cleanups {
121 until ($ptr == $#record) {
123 # catch empty datafield elements
124 if ($record[$ptr] =~ m/<datafield tag="..."/) {
125 if ($record[$ptr + 1] =~ m|</datafield>|) {
126 my @a = @record[0 .. $ptr - 1];
127 my @b = @record[$ptr + 2 .. $#record];
129 @a = undef; @b = undef;
130 message("Empty datafield scrubbed");
135 # and quasi-empty subfields
136 if ($record[$ptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
137 my $code = $1; my $content = $2;
138 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
139 my @a = @record[0 .. $ptr - 1];
140 my @b = @record[$ptr + 1 .. $#record];
142 @a = undef; @b = undef;
143 message("Empty subfield scrubbed");
152 for $ptr (0 .. $#record) {
154 if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
156 if (length $leader < 24) {
157 $leader .= ' ' x (20 - length($leader));
159 $record[$ptr] = "<leader>$leader</leader>\n";
160 message("Short leader padded");
163 if ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
166 if (length $content < 40) {
167 $content .= ' ' x (40 - length($content));
168 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
169 message("Short 008 padded");
173 # clean misplaced dollarsigns
174 if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
175 $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
176 message("Dollar sign corrected");
179 # automatable subfield maladies
180 $record[$ptr] =~ s/code=" ">c/code="c">/;
181 $record[$ptr] =~ s/code=" ">\$/code="c">\$/;
186 sub stow_record_data {
187 # get tag data if we're looking at it
189 if ($record[$ptr] =~ m/<(control|data)field tag="(.{3})"/) {
191 $tag = $recmeta{tag};
192 $record[$ptr] =~ m/ind1="(.)"/;
193 $recmeta{ind1} = $1 || '';
194 $record[$ptr] =~ m/ind2="(.)"/;
195 $recmeta{ind2} = $1 || '';
198 message("Autokill record: no detectable tag");
199 dump_record("No detectable tag") ;
203 # and since we are looking at a tag, see if it's the original id
204 if ($tag == $c->{'original-tag'}) {
208 if ($record[$ptr] =~ m|<controlfield tag="$tag">(.+?)</controlfield>|)
209 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
210 } elsif ($tag >= 10 and $c->{'original-subfield'}) {
212 my $line = $record[$ptr]; my $lptr = $ptr;
213 my $osub = $c->{'original-subfield'};
214 # skim to end of this tag
215 until ($line =~ m|</datafield>|) {
216 if ($line =~ /<subfield code="$osub">(.+?)</)
217 { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
219 $line = $record[$lptr];
225 # didn't find the old id!
227 message("Autokill record: no oldid when old2new mapping requested");
228 dump_record("No old id found");
232 # got it; write to old->new map file
233 if ($c->{'renumber-from'} and $c->{'original-subfield'}) {
241 #-----------------------------------------------------------------------------------
243 #-----------------------------------------------------------------------------------
247 Handles the Term::ReadLine loop
254 return if $c->{trash}->has( $recmeta{tag} );
255 if ( $c->{fullauto} )
256 { dump_record($msg); return }
258 $c->{editmsg} = $msg;
261 # stow original problem line
262 $recmeta{origline} = $record[$ptr];
265 my $line = $term->readline('marc-cleanup>');
266 my @chunks = split /\s+/, $line;
268 # lines with single-character first chunks are commands.
269 # make sure they exist.
270 if (length $chunks[0] == 1) {
271 unless (defined $commands{$chunks[0]}) {
272 print $OUT "No such command '", $chunks[0], "'\n";
277 if (defined $commands{$chunks[0]}) {
278 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
281 $recmeta{prevline} = $record[$ptr];
282 $record[$ptr] = "$line\n";
286 # set pointer to top on the way out
292 Constructs record arrays from the incoming MARC file and returns them
300 my $trash = $c->{trash};
302 $l = <MARC> while (defined $l and $l !~ /<record>/);
303 return $l unless defined $l;
306 for (keys %recmeta) { $recmeta{$_} = undef }
307 for (0 .. @record) { delete $record[$_] }
310 until ($l =~ m|</record>|) {
311 # clean up tags with spaces in them
312 $l =~ s/tag=" /tag="00/g;
313 $l =~ s/tag=" /tag="0/g;
314 $l =~ s/tag="-/tag="0/g;
315 $l =~ s/tag="(\d\d) /tag="0$1/g;
317 # excise unwanted tags
319 $istrash = 0 if ($l =~ m|</datafield|);
323 if ($l =~ m/<datafield tag="(.{3})"/) {
324 if ($trash->has($1) or ($c->{autoscrub} and $1 =~ /\D/))
325 { $istrash = 1; next }
333 # add 903(?) with new record id
334 if ($c->{'renumber-from'}) {
335 $recmeta{nid} = $c->{'renumber-from'};
336 push @record, join('', ' <datafield tag="', $c->{'renumber-tag'},
337 '" ind1=" " ind2=" "> <subfield code="',
338 $c->{'renumber-subfield'},
341 "</subfield></datafield>\n");
342 $c->{'renumber-from'}++;
355 open $EXMARC, '>:utf8', $c->{exception}
356 or die "Can't open exception file $!\n";
360 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
361 if(defined $recmeta{explanation});
363 # scrub newlines (unless told not to or writing exception record)
364 unless ($c->{nocollapse} or $FH eq $EXMARC)
365 { s/\n// for (@record) }
367 # actually write the record
368 print $FH @record,"\n";
370 # increment output record count (if not exception)
371 $c->{rocount}++ if ($FH eq $EXMARC);
373 # if we were dumping to exception file, nuke the record and set ptr
374 # to terminate processing loop
379 sub print_fullcontext {
380 print $OUT "\r", ' ' x 72, "\n";
381 print $OUT $c->{editmsg},"\n";
382 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
383 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
384 print $OUT " @ ", $c->{ricount}, "/", $c->{totalrecs};
390 my $upper = int($c->{window} / 2) + 1;
391 my $lower = int($c->{window} / 2) - 1;
392 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
393 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
395 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
396 print $OUT '==> |', $record[$ptr];
397 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
404 print $OUT "\r$msg at ",$c->{ricount},"/",$c->{totalrecs}, "\n";
407 #-----------------------------------------------------------------------------------
409 #-----------------------------------------------------------------------------------
414 my $ofrom = shift @chunks;
415 if ($ofrom =~ /^'/) {
416 until ($ofrom =~ /'$/ or !@chunks)
417 { $ofrom .= join(' ','',shift @chunks) }
418 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
420 my $to = shift @chunks;
422 until ($to =~ /'$/ or !@chunks)
423 { $to .= join(' ','',shift @chunks) }
424 $to =~ s/^'//; $to =~ s/'$//;
428 for my $char (split(//,$ofrom)) {
429 $char = "\\" . $char if ($char =~ /\W/);
430 $from = join('', $from, $char);
433 $recmeta{prevline} = $record[$ptr];
434 $record[$ptr] =~ s/$from/$to/;
435 $ofrom = undef; $to = undef; $from = undef;
441 $recmeta{prevline} = $record[$ptr];
442 # remove <subfield stuff; extract (probably wrong) subfield code
443 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
444 # and move to front of line
445 $record[$ptr] = join(' ', $1 , $record[$ptr]);
446 # tear off trailing subfield tag from preceeding line
447 $record[$ptr - 1] =~ s|</subfield>\n||;
448 # join current line onto preceeding line
449 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
451 my @a = @record[0 .. $ptr - 1];
452 my @b = @record[$ptr + 1 .. $#record];
454 # move record pointer to previous line
461 unless ($recmeta{prevline})
462 { print $OUT "No previously edited line to flip\n"; return }
463 my $temp = $record[$ptr];
464 $record[$ptr] = $recmeta{prevline};
465 $recmeta{prevline} = $temp;
472 $recmeta{killline} = $record[$ptr];
473 my @a = @record[0 .. $ptr - 1];
474 my @b = @record[$ptr + 1 .. $#record];
476 @a = undef; @b = undef;
482 unless ($recmeta{killline})
483 { print $OUT "No killed line to yank\n"; return }
484 my @a = @record[0 .. $ptr - 1];
485 my @b = @record[$ptr .. $#record];
486 @record = (@a, $c->{killline}, @b);
487 @a = undef; @b = undef;
492 sub insert_original {
493 $record[$ptr] = $recmeta{origline};
499 print $OUT "\nOrig. edit line :", $recmeta{origline};
500 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
501 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
507 my (@explanation) = @_;
508 $recmeta{explanation} = join(' ', 'DUMPING RECORD: Tag', $recmeta{tag}, @explanation);
509 message( $recmeta{explanation} );
510 write_record($EXMARC);
515 $ptr++ unless ($ptr == $#record);;
521 $ptr-- unless ($ptr == 0);
526 sub commit_edit { return 1 }
529 if ($c->{window} == 15)
530 { print $OUT "Window can't be bigger than 15 lines\n"; return }
536 if ($c->{window} == 5)
537 { print $OUT "Window can't be smaller than 5 lines\n"; return }
544 Type a replacement for the indicated line, or enter a command.
546 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
547 < Expand context window | k Kill current line
548 > Contract context window | y Yank last killed line
549 p Move pointer to prev line | m Merge current line into preceding line
550 n Move pointer to next line | o Insert original line
551 c Print line context | f Flip current line and last edited line
552 d Print current saved lines |
553 -----------------------------+-------------------------------------------
554 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
555 contains spaces, it must be single-quoted
556 t Commit changes and resume automated operations
557 x Dump record to exception file
566 #-----------------------------------------------------------------------
570 Performs boring script initialization. Handles argument parsing,
579 # set mode on existing filehandles
580 binmode(STDIN, ':utf8');
582 my $rc = GetOptions( $c,
590 'renumber-from|rf=i',
592 'renumber-subfield|rs=s',
594 'original-subfield|os=s',
601 show_help() unless $rc;
602 show_help() if ($c->{help});
603 show_trashhelp() if ($c->{trashhelp});
606 my $pfx = defined($c->{prefix}) ? $c->{prefix} : "bibs";
609 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
610 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
613 $c->{output} = join('.',$c->{prefix},'clean','marc','xml')
615 $c->{exception} = join('.',$c->{prefix},'exception','marc','xml')
616 unless $c->{exception};
617 $c->{marcfile} = $c->{prefix} . '.marc.xml'
618 unless $c->{marcfile};
620 show_help() unless ($c->{marcfile} and $c->{output});
622 if ($c->{trashfile}) {
623 $c->{trash} = Equinox::Migration::SimpleTagList->new(file => $c->{trashfile})
625 $c->{trash} = Equinox::Migration::SimpleTagList->new;
627 # autotrash 901, 903 unless no strip-nines
628 unless ($c->{'no-strip9'}) {
629 $c->{trash}->add_tag(901);
630 $c->{trash}->add_tag(903);
632 # remove original id sequence tag from trash hash if we know it
633 $c->{trash}->remove_tag($c->{'original-tag'})
634 if ( $c->{'original-tag'} and $c->{trash}->has($c->{'original-tag'}) );
639 Usage is: marc_cleanup [OPTIONS] <filelist>
641 --output -o Cleaned MARCXML output filename
642 --exception -x Exception (dumped records) MARCXML filename
644 --prefix=<PREFIX> -p Shared prefix for output/exception files. Will produce
645 PREFIX.clean.marc.xml and PREFIX.exception.marc.xml
647 --marcfile -m Input filename. Defaults to PREFIX.marc.xml
649 --renumber-from -rf Begin renumbering id sequence with this number
650 --renumber-tag -rt Tag to use in renumbering (default: 903)
651 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
652 --original-tag -ot Original id tag; will be kept in output even if
653 it appears in the trash file
654 --original-subfield -os Original id subfield code. If this is specified
655 and renumbering is in effect, an old-to-new mapping
656 file (old2new.map) will be generated.
658 --autoscrub -a Automatically remove non-numeric tags in data
659 --nocollapse -n Don't compress records to one line on output
660 --no-strip9 Don't autoremove 901/903 tags in data
661 --trashfile -t File containing trash tag data (see --trashhelp)
663 --fullauto No manual edits. All problematic records dumped to
674 http://intra.lan.hq.esilibrary.com/dokuwiki/doku.php?id=migration:tag_files
676 for tag file syntax information.