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();
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 # catch empty datafield elements
113 if ($record[$ptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
114 if ($record[$ptr + 1] =~ m|</datafield>|) {
115 my @a = @record[0 .. $ptr - 1];
116 my @b = @record[$ptr + 2 .. $#record];
118 message("Empty datafield scrubbed");
123 # and quasi-empty subfields
124 if ($record[$ptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
125 my $code = $1; my $content = $2;
126 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
127 my @a = @record[0 .. $ptr - 1];
128 my @b = @record[$ptr + 1 .. $#record];
130 message("Empty subfield scrubbed");
139 for $ptr (0 .. $#record) {
141 if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
143 if (length $leader < 24) {
144 $leader .= ' ' x (20 - length($leader));
146 $record[$ptr] = "<leader>$leader</leader>\n";
147 message("Short leader padded");
150 if ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
153 if (length $content < 40) {
154 $content .= ' ' x (40 - length($content));
155 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
156 message("Short 008 padded");
160 # clean misplaced dollarsigns
161 if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
162 $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
163 message("Dollar sign corrected");
166 # clean up tags with spaces in them
167 $record[$ptr] =~ s/tag=" /tag="00/g;
168 $record[$ptr] =~ s/tag=" /tag="0/g;
169 $record[$ptr] =~ s/tag="-/tag="0/g;
170 $record[$ptr] =~ s/tag="(\d\d) /tag="0$1/g;
172 # automatable subfield maladies
173 $record[$ptr] =~ s/code=" ">c/code="c">/;
174 $record[$ptr] =~ s/code=" ">\$/code="c"$>/;
178 sub stow_record_data {
179 # get tag data if we're looking at it
180 if ($record[$ptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
185 # and since we are looking at a tag, see if it's the original id
186 if ($conf->{'original-subfield'} and $1 == $conf->{'original-tag'}) {
187 my $line = $record[$ptr]; my $lptr = $ptr;
188 my $osub = $conf->{'original-subfield'};
189 $recmeta{oid} = 'NONE';
191 until ($line =~ m|</record>|) {
193 $line = $record[$lptr];
195 if ($line =~ /<subfield code="$osub">(.+?)</);
201 #-----------------------------------------------------------------------------------
203 #-----------------------------------------------------------------------------------
207 Handles the Term::ReadLine loop
214 return if $conf->{trash}{ $recmeta{tag} };
215 $conf->{editmsg} = $msg;
218 # stow original problem line
219 $recmeta{origline} = $record[$ptr];
222 my $line = $term->readline('marc-cleanup>');
223 my @chunks = split /\s+/, $line;
225 # lines with single-character first chunks are commands.
226 # make sure they exist.
227 if (length $chunks[0] == 1) {
228 unless (defined $commands{$chunks[0]}) {
229 print $OUT "No such command '", $chunks[0], "'\n";
234 if (defined $commands{$chunks[0]}) {
235 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
238 $recmeta{prevline} = $record[$ptr];
239 $record[$ptr] = "$line\n";
243 # set pointer to top on the way out
249 Constructs record arrays from the incoming MARC file and returns them
256 $l = <MARC> while (defined $l and $l !~ /<record>/);
257 return $l unless defined $l;
262 until ($l =~ m|</record>|)
263 { push @record, $l; $l = <MARC>; }
270 my $trash = $conf->{trash};
272 $conf->{rocount}++ if ($FH eq $NUMARC);
273 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
274 if(defined $recmeta{explanation});
276 # excise unwanted tags
277 if (keys %{$trash} or $conf->{autoscrub}) {
280 for my $line (@record) {
282 $istrash = 0 if $line =~ m|</datafield|;
285 if ($line =~ m/<datafield tag="(.{3})"/) {
287 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
292 push @trimmed, $line;
297 # add 903(?) with new record id
299 if ($conf->{'renumber-from'}) {
300 $recmeta{nid} = $conf->{'renumber-from'};
301 $renumber = join('', ' <datafield tag="', $conf->{'renumber-tag'},
302 '" ind1=" " ind2=" "> <subfield code="',
303 $conf->{'renumber-subfield'},
304 '">', $recmeta{nid}, "</subfield></datafield>\n");
305 my @tmp = @record[0 .. $#record - 1];
306 my $last = $record[$#record];
307 @record = (@tmp, $renumber, $last);
308 $conf->{'renumber-from'}++;
312 unless ($conf->{nocollapse})
313 { s/\n// for (@record) }
315 # write to old->new map file if needed
316 print $OLD2NEW $recmeta{oid}, "\t", $recmeta{nid}, "\n"
317 if ($conf->{'renumber-from'} and $conf->{'original-subfield'});
319 # and finally, actually write the record
320 print $FH @record,"\n";
323 sub print_fullcontext {
324 print $OUT "\r", ' ' x 72, "\n";
325 print $OUT $conf->{editmsg},"\n";
326 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
327 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
333 my $upper = int($conf->{window} / 2) + 1;
334 my $lower = int($conf->{window} / 2) - 1;
335 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
336 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
338 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
339 print $OUT '==> |', $record[$ptr];
340 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
347 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
350 #-----------------------------------------------------------------------------------
352 #-----------------------------------------------------------------------------------
355 my ($line_in, @chunks) = @_;
357 my $ofrom = shift @chunks;
358 if ($ofrom =~ /^'/ or !@chunks) {
359 until ($ofrom =~ /'$/)
360 { $ofrom .= join(' ','',shift @chunks) }
361 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
363 my $to = shift @chunks;
365 until ($to =~ /'$/ or !@chunks)
366 { $to .= join(' ','',shift @chunks) }
367 $to =~ s/^'//; $to =~ s/'$//;
371 for my $char (split(//,$ofrom)) {
372 $char = "\\" . $char if ($char =~ /\W/);
373 $from = join('', $from, $char);
376 $recmeta{prevline} = $record[$ptr];
377 $record[$ptr] =~ s/$from/$to/;
383 $recmeta{prevline} = $record[$ptr];
384 # remove <subfield stuff; extract (probably wrong) subfield code
385 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
386 # and move to front of line
387 $record[$ptr] = join(' ', $1 , $record[$ptr]);
388 # tear off trailing subfield tag from preceeding line
389 $record[$ptr - 1] =~ s|</subfield>\n||;
390 # join current line onto preceeding line
391 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
393 my @a = @record[0 .. $ptr - 1];
394 my @b = @record[$ptr + 1 .. $#record];
396 # move record pointer to previous line
403 unless ($recmeta{prevline})
404 { print $OUT "No previously edited line to flip\n"; return }
405 my $temp = $record[$ptr];
406 $record[$ptr] = $recmeta{prevline};
407 $recmeta{prevline} = $temp;
413 $recmeta{killline} = $record[$ptr];
414 my @a = @record[0 .. $ptr - 1];
415 my @b = @record[$ptr + 1 .. $#record];
422 unless ($recmeta{killline})
423 { print $OUT "No killed line to yank\n"; return }
424 my @a = @record[0 .. $ptr - 1];
425 my @b = @record[$ptr .. $#record];
426 @record = (@a, $conf->{killline}, @b);
432 print $OUT "\nOrig. edit line :", $recmeta{origline};
433 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
434 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
440 my ($line_in, @explanation) = @_;
441 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
442 write_record($EXMARC);
447 $ptr++ unless ($ptr == $#record);;
453 $ptr-- unless ($ptr == 0);
458 sub commit_edit { return 1 }
461 if ($conf->{window} == 15)
462 { print $OUT "Window can't be bigger than 15 lines\n"; return }
463 $conf->{window} += 2;
468 if ($conf->{window} == 5)
469 { print $OUT "Window can't be smaller than 5 lines\n"; return }
470 $conf->{window} -= 2;
476 Type a replacement for the indicated line, or enter a command.
478 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
479 < Expand context window | k Kill current line
480 > Contract context window | y Yank last killed line
481 p Move pointer to prev line | m Merge current line into preceding line
482 n Move pointer to next line | o Insert original line
483 c Print line context | f Flip current line and last edited line
484 d Print current saved lines |
485 -----------------------------+-------------------------------------------
486 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
487 contains spaces, it must be single-quoted
488 t Commit changes and resume automated operations
489 x Dump record to exception file
498 #-----------------------------------------------------------------------------------
500 #-----------------------------------------------------------------------------------
501 # defined a domain-specific language for specifying MARC tags to be dropped from
502 # records during processing. it is line oriented, and is specified as follows:
504 # each line may specify any number of tags to be included, either singly (\d{1,3})
505 # or as a range (\d{1,3}\.\.\d{1,3}
507 # if a single number is given, it must be between '000' and '999', inclusive.
509 # ranges obey the previous rule, and also the first number of the range must be less
510 # than the second number
512 # finally, any single range in a line may be followed by the keyword 'except'. every
513 # number or range after 'except' is excluded from the range specified. all these
514 # numbers must actually be within the range.
516 # specifying a tag twice is an error, to help prevent typos
519 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
520 open TRASH, '<', $conf->{trashfile}
521 or die "Can't open trash tags file!\n";
523 my $lastwasrange = 0;
524 my %lastrange = ( high => 0, low => 0);
527 my @chunks = split /\s+/;
528 while (my $chunk = shift @chunks) {
531 if ($chunk =~ /^\d{1,3}$/) {
532 trash_add($chunk, $except);
538 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
539 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
541 %lastrange = (low => $low, high => $high)
547 if ($chunk eq 'except') {
548 die "Keyword 'except' can only follow a range (line $.)\n"
549 unless $lastwasrange;
550 die "Keyword 'except' may only occur once per line (line $.)\n"
556 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
560 # remove original id sequence tag from trash hash if we know it
561 trash_add($conf->{'original-tag'}, 1)
562 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
565 sub trash_add_range {
566 my ($chunk, $except, $range) = @_;
567 my ($low,$high) = split /\.\./, $chunk;
568 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
571 die "Exception ranges must be within last addition range (line $.)\n"
572 if ($low < $range->{low} or $high > $range->{high});
574 for my $tag ($low..$high) {
575 trash_add($tag, $except)
581 my ($tag, $except) = @_;
582 my $trash = $conf->{trash};
584 die "Trash values must be valid tags (000-999)\n"
585 unless ($tag >= 0 and $tag <= 999);
588 delete $trash->{$tag};
590 die "Trash tag '$tag' specified twice (line $.)\n"
596 #-----------------------------------------------------------------------
600 Performs boring script initialization. Handles argument parsing,
609 # set mode on existing filehandles
610 binmode(STDIN, ':utf8');
612 my $rc = GetOptions( $c,
617 'renumber-from|rf=i',
619 'renumber-subfield|rs=i',
621 'original-subfield|os=i',
628 show_help() unless $rc;
629 show_help() if ($c->{help});
630 show_trashhelp() if ($c->{trashhelp});
633 $c->{output} = 'cleaned.marc.xml' unless defined $c->{output};
634 $c->{exception} = 'exceptions.marc.xml' unless defined $c->{exception};
635 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
636 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
639 # autotrash 901, 903 if strip-nines
640 if ($c->{'strip-nines'}) {
641 $c->{trash}{901} = 1;
642 $c->{trash}{903} = 1;
645 my @keys = keys %{$c};
646 show_help() unless (@ARGV and @keys);
651 Usage is: marc-cleanup [OPTIONS] <filelist>
653 --output -o Cleaned MARCXML output filename
654 (default: cleaned.marc.xml)
655 --exception -x Exception (dumped records) MARCXML filename
656 (exceptions.marc.xml)
657 --trashfile -t File containing trash tag data (see --trashhelp)
659 --renumber-from -rf Begin renumbering id sequence with this number
660 --renumber-tag -rt Tag to use in renumbering (default: 903)
661 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
662 --original-tag -ot Original id tag; will be kept in output even if
663 it appears in the trash file
664 --original-subfield -os Original id subfield code. If this is specified
665 and renumbering is in effect, an old-to-new mapping
666 file (old2new.incoming.map) will be generated.
668 --nocollapse -n Don't compress records to one line on output
669 --autoscrub -a Automatically remove non-numeric tags in data
670 --strip-nines Automatically remove any existing 901/903 tags in data
672 --script Store human-initiated ops in scriptfile (.mcscript)
680 The marc-cleanup trash tags file is a simple plaintext file. It is a
681 line oriented format. There are three basic tokens:
685 * The "except" clause
687 Any number of tags and/or tag ranges can appear on a single line. A
688 tag cannot appear twice in the file, either alone or as part of a
689 range. This is to prevent errors in the trash tag listing. Items do
690 not have to be sorted within a line. These following lines are valid:
692 850 852 870..879 886 890 896..899
695 Ranges must be ordered internally. That is, "870..879" is valid while
698 Finally, there can be only one "except" clause on a line. It is
699 composed of the word "except" followed by one or more tags or
700 ranges. Except clauses must follow a range, and all tags within the
701 clause must be within the range which the clause follows.
703 900..997 except 935 950..959 987 994