9 my $term = new Term::ReadLine 'yaz-cleanup';
10 my $OUT = $term->OUT || \*STDOUT;
14 # initialization and setup
17 populate_trash() if ($conf->{trashfile});
19 # set up files, since everything appears to be in order
20 open MARC, '<:utf8', (shift || 'incoming.marc.xml')
21 or die "Can't open input file $!\n";
22 open my $NUMARC, '>:utf8', $conf->{output}
23 or die "Can't open output file $!\n";
24 open my $OLD2NEW, '>', 'old2new.map'
25 if ($conf->{'renumber-from'} and $conf->{'original-subfield'});
29 my @record = (); # current record storage
30 my %recmeta = (); # metadata about current record
31 my $ptr = 0; # record index pointer
33 # this is the dispatch table which drives command selection in
35 my %commands = ( c => \&print_fullcontext,
38 '<' => \&widen_window,
39 '>' => \&narrow_window,
41 o => \&insert_original,
55 my @spinner = qw(- / | \\);
58 while ( buildrecord() ) {
59 unless ($conf->{ricount} % 100) {
60 print "\rWorking... ", $spinner[$sidx];
61 $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
64 do_automated_cleanups();
67 until ($ptr == $#record) {
69 if ($record[$ptr] =~ /&/ && $record[$ptr] !~ /&\w+?;/)
70 { edit("Naked ampersand"); $ptr= 0; next }
72 if ($record[$ptr] =~ /<datafield tag="(.+?)"/) {
74 # tags must be numeric
76 edit("Non-numerics in tag") unless $conf->{autoscrub};
79 # test for existing 901/903 unless we're autocleaning them
80 unless ($conf->{'strip-nines'}) {
81 if ($match == 901 or $match == 903) {
82 edit("Incoming 901/903 found in data");
88 # subfields can't be non-alphanumeric
89 if ($record[$ptr] =~ /<subfield code="(.*?)"/) {
91 if ($match =~ /\P{IsAlnum}/ or $match eq '') {
92 edit("Junk in subfield code/Null subfield code");
99 write_record($NUMARC);
101 #print $NUMARC "</collection>\n";
102 print $OUT "\nDone. \n";
105 #-----------------------------------------------------------------------------------
107 #-----------------------------------------------------------------------------------
109 sub do_automated_cleanups {
111 until ($ptr == $#record) {
112 # get datafield/tag data if we have it
115 # catch empty datafield elements
116 if ($record[$ptr] =~ m/<datafield tag="..."/) {
117 if ($record[$ptr + 1] =~ m|</datafield>|) {
118 my @a = @record[0 .. $ptr - 1];
119 my @b = @record[$ptr + 2 .. $#record];
121 message("Empty datafield scrubbed");
126 # and quasi-empty subfields
127 if ($record[$ptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
128 my $code = $1; my $content = $2;
129 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
130 my @a = @record[0 .. $ptr - 1];
131 my @b = @record[$ptr + 1 .. $#record];
133 message("Empty subfield scrubbed");
142 for $ptr (0 .. $#record) {
144 if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
146 if (length $leader < 24) {
147 $leader .= ' ' x (20 - length($leader));
149 $record[$ptr] = "<leader>$leader</leader>\n";
150 message("Short leader padded");
153 if ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
156 if (length $content < 40) {
157 $content .= ' ' x (40 - length($content));
158 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
159 message("Short 008 padded");
163 # clean misplaced dollarsigns
164 if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
165 $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
166 message("Dollar sign corrected");
169 # clean up tags with spaces in them
170 $record[$ptr] =~ s/tag=" /tag="00/g;
171 $record[$ptr] =~ s/tag=" /tag="0/g;
172 $record[$ptr] =~ s/tag="-/tag="0/g;
173 $record[$ptr] =~ s/tag="(\d\d) /tag="0$1/g;
175 # automatable subfield maladies
176 $record[$ptr] =~ s/code=" ">c/code="c">/;
177 $record[$ptr] =~ s/code=" ">\$/code="c"$>/;
181 sub stow_record_data {
182 # get tag data if we're looking at it
183 if ($record[$ptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)"/) {
185 $recmeta{ind1} = $2 || '';
186 $recmeta{ind2} = $3 || '';
188 unless (defined $recmeta{tag}) {
189 message("Autokill record: no detectable tag");
190 dump_record("No detectable tag") ;
193 # and since we are looking at a tag, see if it's the original id
194 if ($conf->{'original-subfield'} and $1 == $conf->{'original-tag'}) {
195 my $line = $record[$ptr]; my $lptr = $ptr;
196 my $osub = $conf->{'original-subfield'};
197 $recmeta{oid} = 'NONE';
199 until ($line =~ m|</record>|) {
201 $line = $record[$lptr];
203 if ($line =~ /<subfield code="$osub">(.+?)</);
209 #-----------------------------------------------------------------------------------
211 #-----------------------------------------------------------------------------------
215 Handles the Term::ReadLine loop
222 return if $conf->{trash}{ $recmeta{tag} };
223 $conf->{editmsg} = $msg;
226 # stow original problem line
227 $recmeta{origline} = $record[$ptr];
230 my $line = $term->readline('marc-cleanup>');
231 my @chunks = split /\s+/, $line;
233 # lines with single-character first chunks are commands.
234 # make sure they exist.
235 if (length $chunks[0] == 1) {
236 unless (defined $commands{$chunks[0]}) {
237 print $OUT "No such command '", $chunks[0], "'\n";
242 if (defined $commands{$chunks[0]}) {
243 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
246 $recmeta{prevline} = $record[$ptr];
247 $record[$ptr] = "$line\n";
251 # set pointer to top on the way out
257 Constructs record arrays from the incoming MARC file and returns them
264 $l = <MARC> while (defined $l and $l !~ /<record>/);
265 return $l unless defined $l;
270 until ($l =~ m|</record>|)
271 { push @record, $l; $l = <MARC>; }
278 my $trash = $conf->{trash};
282 open $EXMARC, '>:utf8', $conf->{exception}
283 or die "Can't open exception file $!\n";
287 $conf->{rocount}++ if ($FH eq $NUMARC);
288 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
289 if(defined $recmeta{explanation});
291 # excise unwanted tags
292 if (keys %{$trash} or $conf->{autoscrub}) {
295 for my $line (@record) {
297 $istrash = 0 if $line =~ m|</datafield|;
300 if ($line =~ m/<datafield tag="(.{3})"/) {
302 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
307 push @trimmed, $line;
312 # add 903(?) with new record id
314 if ($conf->{'renumber-from'}) {
315 $recmeta{nid} = $conf->{'renumber-from'};
316 $renumber = join('', ' <datafield tag="', $conf->{'renumber-tag'},
317 '" ind1=" " ind2=" "> <subfield code="',
318 $conf->{'renumber-subfield'},
319 '">', $recmeta{nid}, "</subfield></datafield>\n");
320 my @tmp = @record[0 .. $#record - 1];
321 my $last = $record[$#record];
322 @record = (@tmp, $renumber, $last);
323 $conf->{'renumber-from'}++;
326 # scrub newlines (unless told not to or writing exception record)
327 unless ($conf->{nocollapse} or $FH eq $EXMARC)
328 { s/\n// for (@record) }
330 # write to old->new map file if needed
331 if ($conf->{'renumber-from'} and $conf->{'original-subfield'}) {
332 unless (defined $recmeta{oid}) {
333 my $msg = join(' ', "No old id num found");
336 print $OLD2NEW $recmeta{oid}, "\t", $recmeta{nid}, "\n"
340 # actually write the record
341 print $FH @record,"\n";
343 # if we were dumping to exception file, nuke the record and set ptr
344 # to terminate processing loop
349 sub print_fullcontext {
350 print $OUT "\r", ' ' x 72, "\n";
351 print $OUT $conf->{editmsg},"\n";
352 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
353 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
354 print $OUT " @ ", $conf->{ricount}, "/", $conf->{rocount} + 1,"\n";
360 my $upper = int($conf->{window} / 2) + 1;
361 my $lower = int($conf->{window} / 2) - 1;
362 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
363 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
365 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
366 print $OUT '==> |', $record[$ptr];
367 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
374 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
377 #-----------------------------------------------------------------------------------
379 #-----------------------------------------------------------------------------------
384 my $ofrom = shift @chunks;
385 if ($ofrom =~ /^'/) {
386 until ($ofrom =~ /'$/ or !@chunks)
387 { $ofrom .= join(' ','',shift @chunks) }
388 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
390 my $to = shift @chunks;
392 until ($to =~ /'$/ or !@chunks)
393 { $to .= join(' ','',shift @chunks) }
394 $to =~ s/^'//; $to =~ s/'$//;
398 for my $char (split(//,$ofrom)) {
399 $char = "\\" . $char if ($char =~ /\W/);
400 $from = join('', $from, $char);
403 $recmeta{prevline} = $record[$ptr];
404 $record[$ptr] =~ s/$from/$to/;
410 $recmeta{prevline} = $record[$ptr];
411 # remove <subfield stuff; extract (probably wrong) subfield code
412 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
413 # and move to front of line
414 $record[$ptr] = join(' ', $1 , $record[$ptr]);
415 # tear off trailing subfield tag from preceeding line
416 $record[$ptr - 1] =~ s|</subfield>\n||;
417 # join current line onto preceeding line
418 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
420 my @a = @record[0 .. $ptr - 1];
421 my @b = @record[$ptr + 1 .. $#record];
423 # move record pointer to previous line
430 unless ($recmeta{prevline})
431 { print $OUT "No previously edited line to flip\n"; return }
432 my $temp = $record[$ptr];
433 $record[$ptr] = $recmeta{prevline};
434 $recmeta{prevline} = $temp;
440 $recmeta{killline} = $record[$ptr];
441 my @a = @record[0 .. $ptr - 1];
442 my @b = @record[$ptr + 1 .. $#record];
449 unless ($recmeta{killline})
450 { print $OUT "No killed line to yank\n"; return }
451 my @a = @record[0 .. $ptr - 1];
452 my @b = @record[$ptr .. $#record];
453 @record = (@a, $conf->{killline}, @b);
458 sub insert_original {
459 $record[$ptr] = $recmeta{origline};
465 print $OUT "\nOrig. edit line :", $recmeta{origline};
466 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
467 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
473 my (@explanation) = @_;
474 print $OUT @explanation;
475 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
476 write_record($EXMARC);
481 $ptr++ unless ($ptr == $#record);;
487 $ptr-- unless ($ptr == 0);
492 sub commit_edit { return 1 }
495 if ($conf->{window} == 15)
496 { print $OUT "Window can't be bigger than 15 lines\n"; return }
497 $conf->{window} += 2;
502 if ($conf->{window} == 5)
503 { print $OUT "Window can't be smaller than 5 lines\n"; return }
504 $conf->{window} -= 2;
510 Type a replacement for the indicated line, or enter a command.
512 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
513 < Expand context window | k Kill current line
514 > Contract context window | y Yank last killed line
515 p Move pointer to prev line | m Merge current line into preceding line
516 n Move pointer to next line | o Insert original line
517 c Print line context | f Flip current line and last edited line
518 d Print current saved lines |
519 -----------------------------+-------------------------------------------
520 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
521 contains spaces, it must be single-quoted
522 t Commit changes and resume automated operations
523 x Dump record to exception file
532 #-----------------------------------------------------------------------------------
534 #-----------------------------------------------------------------------------------
535 # defined a domain-specific language for specifying MARC tags to be dropped from
536 # records during processing. it is line oriented, and is specified as follows:
538 # each line may specify any number of tags to be included, either singly (\d{1,3})
539 # or as a range (\d{1,3}\.\.\d{1,3}
541 # if a single number is given, it must be between '000' and '999', inclusive.
543 # ranges obey the previous rule, and also the first number of the range must be less
544 # than the second number
546 # finally, any single range in a line may be followed by the keyword 'except'. every
547 # number or range after 'except' is excluded from the range specified. all these
548 # numbers must actually be within the range.
550 # specifying a tag twice is an error, to help prevent typos
553 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
554 open TRASH, '<', $conf->{trashfile}
555 or die "Can't open trash tags file!\n";
557 my $lastwasrange = 0;
558 my %lastrange = ( high => 0, low => 0);
561 my @chunks = split /\s+/;
562 while (my $chunk = shift @chunks) {
565 if ($chunk =~ /^\d{1,3}$/) {
566 trash_add($chunk, $except);
572 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
573 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
575 %lastrange = (low => $low, high => $high)
581 if ($chunk eq 'except') {
582 die "Keyword 'except' can only follow a range (line $.)\n"
583 unless $lastwasrange;
584 die "Keyword 'except' may only occur once per line (line $.)\n"
590 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
594 # remove original id sequence tag from trash hash if we know it
595 trash_add($conf->{'original-tag'}, 1)
596 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
599 sub trash_add_range {
600 my ($chunk, $except, $range) = @_;
601 my ($low,$high) = split /\.\./, $chunk;
602 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
605 die "Exception ranges must be within last addition range (line $.)\n"
606 if ($low < $range->{low} or $high > $range->{high});
608 for my $tag ($low..$high) {
609 trash_add($tag, $except)
615 my ($tag, $except) = @_;
616 my $trash = $conf->{trash};
618 die "Trash values must be valid tags (000-999)\n"
619 unless ($tag >= 0 and $tag <= 999);
622 delete $trash->{$tag};
624 die "Trash tag '$tag' specified twice (line $.)\n"
630 #-----------------------------------------------------------------------
634 Performs boring script initialization. Handles argument parsing,
643 # set mode on existing filehandles
644 binmode(STDIN, ':utf8');
646 my $rc = GetOptions( $c,
652 'renumber-from|rf=i',
654 'renumber-subfield|rs=s',
656 'original-subfield|os=s',
663 show_help() unless $rc;
664 show_help() if ($c->{help});
665 show_trashhelp() if ($c->{trashhelp});
669 $c->{output} = join('.',$c->{prefix},'marc','xml');
670 $c->{exception} = join('.',$c->{prefix},'ex','xml');
672 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
673 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
676 # autotrash 901, 903 if strip-nines
677 if ($c->{'strip-nines'}) {
678 $c->{trash}{901} = 1;
679 $c->{trash}{903} = 1;
682 my @keys = keys %{$c};
683 show_help() unless (@ARGV and @keys);
688 Usage is: marc-cleanup [OPTIONS] <filelist>
690 --output -o Cleaned MARCXML output filename
691 --exception -x Exception (dumped records) MARCXML filename
693 --prefix=<PREFIX>> -p Shared prefix for output/exception files. Will
694 produce PREFIX.marc.xml and PREFIX.ex.xml
696 --trashfile -t File containing trash tag data (see --trashhelp)
698 --renumber-from -rf Begin renumbering id sequence with this number
699 --renumber-tag -rt Tag to use in renumbering (default: 903)
700 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
701 --original-tag -ot Original id tag; will be kept in output even if
702 it appears in the trash file
703 --original-subfield -os Original id subfield code. If this is specified
704 and renumbering is in effect, an old-to-new mapping
705 file (old2new.map) will be generated.
707 --nocollapse -n Don't compress records to one line on output
708 --autoscrub -a Automatically remove non-numeric tags in data
709 --strip-nines Automatically remove any existing 901/903 tags in data
711 --script Store human-initiated ops in scriptfile (.mcscript)
719 The marc-cleanup trash tags file is a simple plaintext file. It is a
720 line oriented format. There are three basic tokens:
724 * The "except" clause
726 Any number of tags and/or tag ranges can appear on a single line. A
727 tag cannot appear twice in the file, either alone or as part of a
728 range. This is to prevent errors in the trash tag listing. Items do
729 not have to be sorted within a line. These following lines are valid:
731 850 852 870..879 886 890 896..899
734 Ranges must be ordered internally. That is, "870..879" is valid while
737 Finally, there can be only one "except" clause on a line. It is
738 composed of the word "except" followed by one or more tags or
739 ranges. Except clauses must follow a range, and all tags within the
740 clause must be within the range which the clause follows.
742 900..997 except 935 950..959 987 994