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 open my $NUMARC, '>:utf8', $conf->{output};
22 open my $EXMARC, '>:utf8', $conf->{exception};
23 open my $OLD2NEW, '>', 'old2new.incoming.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 $conf->{rocount}++ if ($FH eq $NUMARC);
275 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
276 if(defined $recmeta{explanation});
278 # excise unwanted tags
279 if (keys %{$trash} or $conf->{autoscrub}) {
282 for my $line (@record) {
284 $istrash = 0 if $line =~ m|</datafield|;
287 if ($line =~ m/<datafield tag="(.{3})"/) {
289 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
294 push @trimmed, $line;
299 # add 903(?) with new record id
301 if ($conf->{'renumber-from'}) {
302 $recmeta{nid} = $conf->{'renumber-from'};
303 $renumber = join('', ' <datafield tag="', $conf->{'renumber-tag'},
304 '" ind1=" " ind2=" "> <subfield code="',
305 $conf->{'renumber-subfield'},
306 '">', $recmeta{nid}, "</subfield></datafield>\n");
307 my @tmp = @record[0 .. $#record - 1];
308 my $last = $record[$#record];
309 @record = (@tmp, $renumber, $last);
310 $conf->{'renumber-from'}++;
314 unless ($conf->{nocollapse})
315 { s/\n// for (@record) }
317 # write to old->new map file if needed
318 print $OLD2NEW $recmeta{oid}, "\t", $recmeta{nid}, "\n"
319 if ($conf->{'renumber-from'} and $conf->{'original-subfield'});
321 # and finally, actually write the record
322 print $FH @record,"\n";
325 sub print_fullcontext {
326 print $OUT "\r", ' ' x 72, "\n";
327 print $OUT $conf->{editmsg},"\n";
328 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
329 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
335 my $upper = int($conf->{window} / 2) + 1;
336 my $lower = int($conf->{window} / 2) - 1;
337 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
338 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
340 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
341 print $OUT '==> |', $record[$ptr];
342 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
349 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
352 #-----------------------------------------------------------------------------------
354 #-----------------------------------------------------------------------------------
359 my $ofrom = shift @chunks;
360 if ($ofrom =~ /^'/) {
361 until ($ofrom =~ /'$/ or !@chunks)
362 { $ofrom .= join(' ','',shift @chunks) }
363 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
365 my $to = shift @chunks;
367 until ($to =~ /'$/ or !@chunks)
368 { $to .= join(' ','',shift @chunks) }
369 $to =~ s/^'//; $to =~ s/'$//;
373 for my $char (split(//,$ofrom)) {
374 $char = "\\" . $char if ($char =~ /\W/);
375 $from = join('', $from, $char);
378 $recmeta{prevline} = $record[$ptr];
379 $record[$ptr] =~ s/$from/$to/;
385 $recmeta{prevline} = $record[$ptr];
386 # remove <subfield stuff; extract (probably wrong) subfield code
387 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
388 # and move to front of line
389 $record[$ptr] = join(' ', $1 , $record[$ptr]);
390 # tear off trailing subfield tag from preceeding line
391 $record[$ptr - 1] =~ s|</subfield>\n||;
392 # join current line onto preceeding line
393 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
395 my @a = @record[0 .. $ptr - 1];
396 my @b = @record[$ptr + 1 .. $#record];
398 # move record pointer to previous line
405 unless ($recmeta{prevline})
406 { print $OUT "No previously edited line to flip\n"; return }
407 my $temp = $record[$ptr];
408 $record[$ptr] = $recmeta{prevline};
409 $recmeta{prevline} = $temp;
415 $recmeta{killline} = $record[$ptr];
416 my @a = @record[0 .. $ptr - 1];
417 my @b = @record[$ptr + 1 .. $#record];
424 unless ($recmeta{killline})
425 { print $OUT "No killed line to yank\n"; return }
426 my @a = @record[0 .. $ptr - 1];
427 my @b = @record[$ptr .. $#record];
428 @record = (@a, $conf->{killline}, @b);
434 print $OUT "\nOrig. edit line :", $recmeta{origline};
435 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
436 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
442 my (@explanation) = @_;
443 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
444 write_record($EXMARC);
449 $ptr++ unless ($ptr == $#record);;
455 $ptr-- unless ($ptr == 0);
460 sub commit_edit { return 1 }
463 if ($conf->{window} == 15)
464 { print $OUT "Window can't be bigger than 15 lines\n"; return }
465 $conf->{window} += 2;
470 if ($conf->{window} == 5)
471 { print $OUT "Window can't be smaller than 5 lines\n"; return }
472 $conf->{window} -= 2;
478 Type a replacement for the indicated line, or enter a command.
480 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
481 < Expand context window | k Kill current line
482 > Contract context window | y Yank last killed line
483 p Move pointer to prev line | m Merge current line into preceding line
484 n Move pointer to next line | o Insert original line
485 c Print line context | f Flip current line and last edited line
486 d Print current saved lines |
487 -----------------------------+-------------------------------------------
488 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
489 contains spaces, it must be single-quoted
490 t Commit changes and resume automated operations
491 x Dump record to exception file
500 #-----------------------------------------------------------------------------------
502 #-----------------------------------------------------------------------------------
503 # defined a domain-specific language for specifying MARC tags to be dropped from
504 # records during processing. it is line oriented, and is specified as follows:
506 # each line may specify any number of tags to be included, either singly (\d{1,3})
507 # or as a range (\d{1,3}\.\.\d{1,3}
509 # if a single number is given, it must be between '000' and '999', inclusive.
511 # ranges obey the previous rule, and also the first number of the range must be less
512 # than the second number
514 # finally, any single range in a line may be followed by the keyword 'except'. every
515 # number or range after 'except' is excluded from the range specified. all these
516 # numbers must actually be within the range.
518 # specifying a tag twice is an error, to help prevent typos
521 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
522 open TRASH, '<', $conf->{trashfile}
523 or die "Can't open trash tags file!\n";
525 my $lastwasrange = 0;
526 my %lastrange = ( high => 0, low => 0);
529 my @chunks = split /\s+/;
530 while (my $chunk = shift @chunks) {
533 if ($chunk =~ /^\d{1,3}$/) {
534 trash_add($chunk, $except);
540 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
541 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
543 %lastrange = (low => $low, high => $high)
549 if ($chunk eq 'except') {
550 die "Keyword 'except' can only follow a range (line $.)\n"
551 unless $lastwasrange;
552 die "Keyword 'except' may only occur once per line (line $.)\n"
558 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
562 # remove original id sequence tag from trash hash if we know it
563 trash_add($conf->{'original-tag'}, 1)
564 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
567 sub trash_add_range {
568 my ($chunk, $except, $range) = @_;
569 my ($low,$high) = split /\.\./, $chunk;
570 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
573 die "Exception ranges must be within last addition range (line $.)\n"
574 if ($low < $range->{low} or $high > $range->{high});
576 for my $tag ($low..$high) {
577 trash_add($tag, $except)
583 my ($tag, $except) = @_;
584 my $trash = $conf->{trash};
586 die "Trash values must be valid tags (000-999)\n"
587 unless ($tag >= 0 and $tag <= 999);
590 delete $trash->{$tag};
592 die "Trash tag '$tag' specified twice (line $.)\n"
598 #-----------------------------------------------------------------------
602 Performs boring script initialization. Handles argument parsing,
611 # set mode on existing filehandles
612 binmode(STDIN, ':utf8');
614 my $rc = GetOptions( $c,
619 'renumber-from|rf=i',
621 'renumber-subfield|rs=i',
623 'original-subfield|os=i',
630 show_help() unless $rc;
631 show_help() if ($c->{help});
632 show_trashhelp() if ($c->{trashhelp});
635 $c->{output} = 'cleaned.marc.xml' unless defined $c->{output};
636 $c->{exception} = 'exceptions.marc.xml' unless defined $c->{exception};
637 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
638 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
641 # autotrash 901, 903 if strip-nines
642 if ($c->{'strip-nines'}) {
643 $c->{trash}{901} = 1;
644 $c->{trash}{903} = 1;
647 my @keys = keys %{$c};
648 show_help() unless (@ARGV and @keys);
653 Usage is: marc-cleanup [OPTIONS] <filelist>
655 --output -o Cleaned MARCXML output filename
656 (default: cleaned.marc.xml)
657 --exception -x Exception (dumped records) MARCXML filename
658 (exceptions.marc.xml)
659 --trashfile -t File containing trash tag data (see --trashhelp)
661 --renumber-from -rf Begin renumbering id sequence with this number
662 --renumber-tag -rt Tag to use in renumbering (default: 903)
663 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
664 --original-tag -ot Original id tag; will be kept in output even if
665 it appears in the trash file
666 --original-subfield -os Original id subfield code. If this is specified
667 and renumbering is in effect, an old-to-new mapping
668 file (old2new.incoming.map) will be generated.
670 --nocollapse -n Don't compress records to one line on output
671 --autoscrub -a Automatically remove non-numeric tags in data
672 --strip-nines Automatically remove any existing 901/903 tags in data
674 --script Store human-initiated ops in scriptfile (.mcscript)
682 The marc-cleanup trash tags file is a simple plaintext file. It is a
683 line oriented format. There are three basic tokens:
687 * The "except" clause
689 Any number of tags and/or tag ranges can appear on a single line. A
690 tag cannot appear twice in the file, either alone or as part of a
691 range. This is to prevent errors in the trash tag listing. Items do
692 not have to be sorted within a line. These following lines are valid:
694 850 852 870..879 886 890 896..899
697 Ranges must be ordered internally. That is, "870..879" is valid while
700 Finally, there can be only one "except" clause on a line. It is
701 composed of the word "except" followed by one or more tags or
702 ranges. Except clauses must follow a range, and all tags within the
703 clause must be within the range which the clause follows.
705 900..997 except 935 950..959 987 994