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
21 open MARC, '<:utf8', (shift || 'incoming.marc.xml');
22 open my $NUMARC, '>:utf8', $conf->{output};
23 open my $OLD2NEW, '>', 'old2new.map'
24 if ($conf->{'renumber-from'} and $conf->{'original-subfield'});
25 print $NUMARC '<?xml version="1.0" encoding="UTF-8"?>',"\n";
26 print $NUMARC '<collection xmlns="http://www.loc.gov/MARC21/slim">',"\n";
28 my @record = (); # current record storage
29 my %recmeta = (); # metadata about current record
30 my $ptr = 0; # record index pointer
32 # this is the dispatch table which drives command selection in
34 my %commands = ( c => \&print_fullcontext,
37 '<' => \&widen_window,
38 '>' => \&narrow_window,
40 o => \&insert_original,
54 my @spinner = qw(- / | \\);
57 while ( buildrecord() ) {
58 unless ($conf->{ricount} % 100) {
59 print "\rWorking... ", $spinner[$sidx];
60 $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
63 do_automated_cleanups();
66 until ($ptr == $#record) {
68 if ($record[$ptr] =~ /&/ && $record[$ptr] !~ /&\w+?;/)
69 { edit("Naked ampersand"); $ptr= 0; next }
71 if ($record[$ptr] =~ /<datafield tag="(.+?)"/) {
73 # tags must be numeric
75 edit("Non-numerics in tag") unless $conf->{autoscrub};
78 # test for existing 901/903 unless we're autocleaning them
79 unless ($conf->{'strip-nines'}) {
80 if ($match == 901 or $match == 903) {
81 edit("Incoming 901/903 found in data");
87 # subfields can't be non-alphanumeric
88 if ($record[$ptr] =~ /<subfield code="(.*?)"/) {
90 if ($match =~ /\P{IsAlnum}/ or $match eq '') {
91 edit("Junk in subfield code/Null subfield code");
98 write_record($NUMARC);
100 print $NUMARC "</collection>\n";
101 print $OUT "\nDone. \n";
104 #-----------------------------------------------------------------------------------
106 #-----------------------------------------------------------------------------------
108 sub do_automated_cleanups {
110 until ($ptr == $#record) {
111 # get datafield/tag data if we have it
114 # catch empty datafield elements
115 if ($record[$ptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
116 if ($record[$ptr + 1] =~ m|</datafield>|) {
117 my @a = @record[0 .. $ptr - 1];
118 my @b = @record[$ptr + 2 .. $#record];
120 message("Empty datafield scrubbed");
125 # and quasi-empty subfields
126 if ($record[$ptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
127 my $code = $1; my $content = $2;
128 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
129 my @a = @record[0 .. $ptr - 1];
130 my @b = @record[$ptr + 1 .. $#record];
132 message("Empty subfield scrubbed");
141 for $ptr (0 .. $#record) {
143 if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
145 if (length $leader < 24) {
146 $leader .= ' ' x (20 - length($leader));
148 $record[$ptr] = "<leader>$leader</leader>\n";
149 message("Short leader padded");
152 if ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
155 if (length $content < 40) {
156 $content .= ' ' x (40 - length($content));
157 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
158 message("Short 008 padded");
162 # clean misplaced dollarsigns
163 if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
164 $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
165 message("Dollar sign corrected");
168 # clean up tags with spaces in them
169 $record[$ptr] =~ s/tag=" /tag="00/g;
170 $record[$ptr] =~ s/tag=" /tag="0/g;
171 $record[$ptr] =~ s/tag="-/tag="0/g;
172 $record[$ptr] =~ s/tag="(\d\d) /tag="0$1/g;
174 # automatable subfield maladies
175 $record[$ptr] =~ s/code=" ">c/code="c">/;
176 $record[$ptr] =~ s/code=" ">\$/code="c"$>/;
180 sub stow_record_data {
181 # get tag data if we're looking at it
182 if ($record[$ptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
187 # and since we are looking at a tag, see if it's the original id
188 if ($conf->{'original-subfield'} and $1 == $conf->{'original-tag'}) {
189 my $line = $record[$ptr]; my $lptr = $ptr;
190 my $osub = $conf->{'original-subfield'};
191 $recmeta{oid} = 'NONE';
193 until ($line =~ m|</record>|) {
195 $line = $record[$lptr];
197 if ($line =~ /<subfield code="$osub">(.+?)</);
203 #-----------------------------------------------------------------------------------
205 #-----------------------------------------------------------------------------------
209 Handles the Term::ReadLine loop
216 return if $conf->{trash}{ $recmeta{tag} };
217 $conf->{editmsg} = $msg;
220 # stow original problem line
221 $recmeta{origline} = $record[$ptr];
224 my $line = $term->readline('marc-cleanup>');
225 my @chunks = split /\s+/, $line;
227 # lines with single-character first chunks are commands.
228 # make sure they exist.
229 if (length $chunks[0] == 1) {
230 unless (defined $commands{$chunks[0]}) {
231 print $OUT "No such command '", $chunks[0], "'\n";
236 if (defined $commands{$chunks[0]}) {
237 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
240 $recmeta{prevline} = $record[$ptr];
241 $record[$ptr] = "$line\n";
245 # set pointer to top on the way out
251 Constructs record arrays from the incoming MARC file and returns them
258 $l = <MARC> while (defined $l and $l !~ /<record>/);
259 return $l unless defined $l;
264 until ($l =~ m|</record>|)
265 { push @record, $l; $l = <MARC>; }
272 my $trash = $conf->{trash};
274 # uninitialized $EXMARC
276 open $EXMARC, '>:utf8', $conf->{exception};
280 $conf->{rocount}++ if ($FH eq $NUMARC);
281 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
282 if(defined $recmeta{explanation});
284 # excise unwanted tags
285 if (keys %{$trash} or $conf->{autoscrub}) {
288 for my $line (@record) {
290 $istrash = 0 if $line =~ m|</datafield|;
293 if ($line =~ m/<datafield tag="(.{3})"/) {
295 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
300 push @trimmed, $line;
305 # add 903(?) with new record id
307 if ($conf->{'renumber-from'}) {
308 $recmeta{nid} = $conf->{'renumber-from'};
309 $renumber = join('', ' <datafield tag="', $conf->{'renumber-tag'},
310 '" ind1=" " ind2=" "> <subfield code="',
311 $conf->{'renumber-subfield'},
312 '">', $recmeta{nid}, "</subfield></datafield>\n");
313 my @tmp = @record[0 .. $#record - 1];
314 my $last = $record[$#record];
315 @record = (@tmp, $renumber, $last);
316 $conf->{'renumber-from'}++;
320 unless ($conf->{nocollapse})
321 { s/\n// for (@record) }
323 # write to old->new map file if needed
324 if ($conf->{'renumber-from'} and $conf->{'original-subfield'}) {
325 unless (defined $recmeta{oid}) {
326 my $msg = join(' ', "No old id num found");
329 print $OLD2NEW $recmeta{oid}, "\t", $recmeta{nid}, "\n"
333 # and finally, actually write the record
334 print $FH @record,"\n";
337 sub print_fullcontext {
338 print $OUT "\r", ' ' x 72, "\n";
339 print $OUT $conf->{editmsg},"\n";
340 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
341 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
342 print $OUT " @ ", $conf->{ricount}, "/", $conf->{rocount} + 1,"\n";
348 my $upper = int($conf->{window} / 2) + 1;
349 my $lower = int($conf->{window} / 2) - 1;
350 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
351 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
353 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
354 print $OUT '==> |', $record[$ptr];
355 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
362 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
365 #-----------------------------------------------------------------------------------
367 #-----------------------------------------------------------------------------------
372 my $ofrom = shift @chunks;
373 if ($ofrom =~ /^'/) {
374 until ($ofrom =~ /'$/ or !@chunks)
375 { $ofrom .= join(' ','',shift @chunks) }
376 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
378 my $to = shift @chunks;
380 until ($to =~ /'$/ or !@chunks)
381 { $to .= join(' ','',shift @chunks) }
382 $to =~ s/^'//; $to =~ s/'$//;
386 for my $char (split(//,$ofrom)) {
387 $char = "\\" . $char if ($char =~ /\W/);
388 $from = join('', $from, $char);
391 $recmeta{prevline} = $record[$ptr];
392 $record[$ptr] =~ s/$from/$to/;
398 $recmeta{prevline} = $record[$ptr];
399 # remove <subfield stuff; extract (probably wrong) subfield code
400 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
401 # and move to front of line
402 $record[$ptr] = join(' ', $1 , $record[$ptr]);
403 # tear off trailing subfield tag from preceeding line
404 $record[$ptr - 1] =~ s|</subfield>\n||;
405 # join current line onto preceeding line
406 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
408 my @a = @record[0 .. $ptr - 1];
409 my @b = @record[$ptr + 1 .. $#record];
411 # move record pointer to previous line
418 unless ($recmeta{prevline})
419 { print $OUT "No previously edited line to flip\n"; return }
420 my $temp = $record[$ptr];
421 $record[$ptr] = $recmeta{prevline};
422 $recmeta{prevline} = $temp;
428 $recmeta{killline} = $record[$ptr];
429 my @a = @record[0 .. $ptr - 1];
430 my @b = @record[$ptr + 1 .. $#record];
437 unless ($recmeta{killline})
438 { print $OUT "No killed line to yank\n"; return }
439 my @a = @record[0 .. $ptr - 1];
440 my @b = @record[$ptr .. $#record];
441 @record = (@a, $conf->{killline}, @b);
447 print $OUT "\nOrig. edit line :", $recmeta{origline};
448 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
449 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
455 my (@explanation) = @_;
456 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
457 write_record($EXMARC);
462 $ptr++ unless ($ptr == $#record);;
468 $ptr-- unless ($ptr == 0);
473 sub commit_edit { return 1 }
476 if ($conf->{window} == 15)
477 { print $OUT "Window can't be bigger than 15 lines\n"; return }
478 $conf->{window} += 2;
483 if ($conf->{window} == 5)
484 { print $OUT "Window can't be smaller than 5 lines\n"; return }
485 $conf->{window} -= 2;
491 Type a replacement for the indicated line, or enter a command.
493 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
494 < Expand context window | k Kill current line
495 > Contract context window | y Yank last killed line
496 p Move pointer to prev line | m Merge current line into preceding line
497 n Move pointer to next line | o Insert original line
498 c Print line context | f Flip current line and last edited line
499 d Print current saved lines |
500 -----------------------------+-------------------------------------------
501 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
502 contains spaces, it must be single-quoted
503 t Commit changes and resume automated operations
504 x Dump record to exception file
513 #-----------------------------------------------------------------------------------
515 #-----------------------------------------------------------------------------------
516 # defined a domain-specific language for specifying MARC tags to be dropped from
517 # records during processing. it is line oriented, and is specified as follows:
519 # each line may specify any number of tags to be included, either singly (\d{1,3})
520 # or as a range (\d{1,3}\.\.\d{1,3}
522 # if a single number is given, it must be between '000' and '999', inclusive.
524 # ranges obey the previous rule, and also the first number of the range must be less
525 # than the second number
527 # finally, any single range in a line may be followed by the keyword 'except'. every
528 # number or range after 'except' is excluded from the range specified. all these
529 # numbers must actually be within the range.
531 # specifying a tag twice is an error, to help prevent typos
534 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
535 open TRASH, '<', $conf->{trashfile}
536 or die "Can't open trash tags file!\n";
538 my $lastwasrange = 0;
539 my %lastrange = ( high => 0, low => 0);
542 my @chunks = split /\s+/;
543 while (my $chunk = shift @chunks) {
546 if ($chunk =~ /^\d{1,3}$/) {
547 trash_add($chunk, $except);
553 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
554 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
556 %lastrange = (low => $low, high => $high)
562 if ($chunk eq 'except') {
563 die "Keyword 'except' can only follow a range (line $.)\n"
564 unless $lastwasrange;
565 die "Keyword 'except' may only occur once per line (line $.)\n"
571 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
575 # remove original id sequence tag from trash hash if we know it
576 trash_add($conf->{'original-tag'}, 1)
577 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
580 sub trash_add_range {
581 my ($chunk, $except, $range) = @_;
582 my ($low,$high) = split /\.\./, $chunk;
583 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
586 die "Exception ranges must be within last addition range (line $.)\n"
587 if ($low < $range->{low} or $high > $range->{high});
589 for my $tag ($low..$high) {
590 trash_add($tag, $except)
596 my ($tag, $except) = @_;
597 my $trash = $conf->{trash};
599 die "Trash values must be valid tags (000-999)\n"
600 unless ($tag >= 0 and $tag <= 999);
603 delete $trash->{$tag};
605 die "Trash tag '$tag' specified twice (line $.)\n"
611 #-----------------------------------------------------------------------
615 Performs boring script initialization. Handles argument parsing,
624 # set mode on existing filehandles
625 binmode(STDIN, ':utf8');
627 my $rc = GetOptions( $c,
632 'renumber-from|rf=i',
634 'renumber-subfield|rs=s',
636 'original-subfield|os=s',
643 show_help() unless $rc;
644 show_help() if ($c->{help});
645 show_trashhelp() if ($c->{trashhelp});
648 $c->{output} = 'cleaned.marc.xml' unless defined $c->{output};
649 $c->{exception} = 'exceptions.marc.xml' unless defined $c->{exception};
650 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
651 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
654 # autotrash 901, 903 if strip-nines
655 if ($c->{'strip-nines'}) {
656 $c->{trash}{901} = 1;
657 $c->{trash}{903} = 1;
660 my @keys = keys %{$c};
661 show_help() unless (@ARGV and @keys);
666 Usage is: marc-cleanup [OPTIONS] <filelist>
668 --output -o Cleaned MARCXML output filename
669 (default: cleaned.marc.xml)
670 --exception -x Exception (dumped records) MARCXML filename
671 (exceptions.marc.xml)
672 --trashfile -t File containing trash tag data (see --trashhelp)
674 --renumber-from -rf Begin renumbering id sequence with this number
675 --renumber-tag -rt Tag to use in renumbering (default: 903)
676 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
677 --original-tag -ot Original id tag; will be kept in output even if
678 it appears in the trash file
679 --original-subfield -os Original id subfield code. If this is specified
680 and renumbering is in effect, an old-to-new mapping
681 file (old2new.map) will be generated.
683 --nocollapse -n Don't compress records to one line on output
684 --autoscrub -a Automatically remove non-numeric tags in data
685 --strip-nines Automatically remove any existing 901/903 tags in data
687 --script Store human-initiated ops in scriptfile (.mcscript)
695 The marc-cleanup trash tags file is a simple plaintext file. It is a
696 line oriented format. There are three basic tokens:
700 * The "except" clause
702 Any number of tags and/or tag ranges can appear on a single line. A
703 tag cannot appear twice in the file, either alone or as part of a
704 range. This is to prevent errors in the trash tag listing. Items do
705 not have to be sorted within a line. These following lines are valid:
707 850 852 870..879 886 890 896..899
710 Ranges must be ordered internally. That is, "870..879" is valid while
713 Finally, there can be only one "except" clause on a line. It is
714 composed of the word "except" followed by one or more tags or
715 ranges. Except clauses must follow a range, and all tags within the
716 clause must be within the range which the clause follows.
718 900..997 except 935 950..959 987 994