9 my $term = new Term::ReadLine 'yaz-cleanup';
10 my $OUT = $term->OUT || \*STDOUT;
12 # initialization and setup
15 populate_trash() if ($conf->{trash});
17 # set up files, since everything appears to be in order
18 open MARC, '<:utf8', shift || 'incoming.marc.xml';
19 open my $NUMARC, '>:utf8', $conf->{output};
20 open my $EXMARC, '>:utf8', $conf->{exception};
21 open my $OLD2NEW, '>', 'old2new.incoming.map'
22 if ($conf->{'renumber-from'} and $conf->{'original-subfield'});
23 print $NUMARC '<?xml version="1.0" encoding="UTF-8"?>',"\n";
24 print $NUMARC '<collection xmlns="http://www.loc.gov/MARC21/slim">',"\n";
26 my @record = (); # current record storage
27 my %recmeta = (); # metadata about current record
28 my $ptr = 0; # record index pointer
30 # this is the dispatch table which drives command selection in
32 my %commands = ( c => \&print_fullcontext,
35 '<' => \&widen_window,
36 '>' => \&narrow_window,
38 o => \&insert_original,
52 my @spinner = qw(- / | \\);
55 while ( buildrecord() ) {
56 unless ($conf->{ricount} % 100) {
57 print "\rWorking... ", $spinner[$sidx];
58 $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
61 do_automated_cleanups();
65 until ($ptr == $#record) {
67 if ($record[$ptr] =~ /&/ && $record[$ptr] !~ /&\w+?;/)
68 { edit("Naked ampersand"); $ptr= 0; next }
70 if ($record[$ptr] =~ /<datafield tag="(.+?)"/) {
72 # tags must be numeric
74 edit("Non-numerics in tag") unless $conf->{autoscrub};
77 # test for existing 901/903 unless we're autocleaning them
78 unless ($conf->{'strip-nines'}) {
79 if ($match == 901 or $match == 903) {
80 edit("Incoming 901/903 found in data");
86 # subfields can't be non-alphanumeric
87 if ($record[$ptr] =~ /<subfield code="(.*?)"/) {
89 if ($match =~ /\P{IsAlnum}/ or $match eq '') {
90 edit("Junk in subfield code/Null subfield code");
97 write_record($NUMARC);
99 print $NUMARC "</collection>\n";
100 print $OUT "\nDone. \n";
103 #-----------------------------------------------------------------------------------
105 #-----------------------------------------------------------------------------------
107 sub do_automated_cleanups {
109 until ($ptr == $#record) {
110 # catch empty datafield elements
111 if ($record[$ptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
112 if ($record[$ptr + 1] =~ m|</datafield>|) {
113 my @a = @record[0 .. $ptr - 1];
114 my @b = @record[$ptr + 2 .. $#record];
116 message("Empty datafield scrubbed");
121 # and quasi-empty subfields
122 if ($record[$ptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
123 my $code = $1; my $content = $2;
124 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
125 my @a = @record[0 .. $ptr - 1];
126 my @b = @record[$ptr + 1 .. $#record];
128 message("Empty subfield scrubbed");
137 for $ptr (0 .. $#record) {
139 if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
141 if (length $leader < 24) {
142 $leader .= ' ' x (20 - length($leader));
144 $record[$ptr] = "<leader>$leader</leader>\n";
145 message("Short leader padded");
148 if ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
151 if (length $content < 40) {
152 $content .= ' ' x (40 - length($content));
153 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
154 message("Short 008 padded");
158 # clean misplaced dollarsigns
159 if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
160 $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
161 message("Dollar sign corrected");
164 # clean up tags with spaces in them
165 $record[$ptr] =~ s/tag=" /tag="00/g;
166 $record[$ptr] =~ s/tag=" /tag="0/g;
167 $record[$ptr] =~ s/tag="-/tag="0/g;
168 $record[$ptr] =~ s/tag="(\d\d) /tag="0$1/g;
170 # automatable subfield maladies
171 $record[$ptr] =~ s/code=" ">c/code="c">/;
172 $record[$ptr] =~ s/code=" ">\$/code="c"$>/;
176 sub stow_record_data {
177 # get tag data if we're looking at it
178 if ($record[$ptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
183 # and since we are looking at a tag, see if it's the original id
184 if ($conf->{'original-subfield'} and $1 == $conf->{'original-tag'}) {
185 my $line = $record[$ptr]; my $lptr = $ptr;
186 my $osub = $conf->{'original-subfield'};
187 $recmeta{oid} = 'NONE';
189 until ($line =~ m|</record>|) {
191 $line = $record[$lptr];
193 if ($line =~ /<subfield code="$osub">(.+?)</);
199 #-----------------------------------------------------------------------------------
201 #-----------------------------------------------------------------------------------
205 Handles the Term::ReadLine loop
212 return if $conf->{trash}{ $recmeta{tag} };
213 $conf->{editmsg} = $msg;
216 # stow original problem line
217 $conf->{origline} = $record[$ptr];
220 my $line = $term->readline('marc-cleanup>');
221 my @chunks = split /\s+/, $line;
223 # lines with single-character first chunks are commands.
224 # make sure they exist.
225 if (length $chunks[0] == 1) {
226 unless (defined $commands{$chunks[0]}) {
227 print $OUT "No such command '", $chunks[0], "'\n";
232 if (defined $commands{$chunks[0]}) {
233 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
236 $record[$ptr] = "$line\n";
240 # set pointer to top on the way out
246 Constructs record arrays from the incoming MARC file and returns them
253 $l = <MARC> while (defined $l and $l !~ /<record>/);
254 return $l unless defined $l;
259 until ($l =~ m|</record>|)
260 { push @record, $l; $l = <MARC>; }
267 my $trash = $conf->{trash};
269 $conf->{rocount}++ if ($FH eq $NUMARC);
270 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
271 if(defined $recmeta{explanation});
273 # excise unwanted tags
274 if (keys %{$trash} or $conf->{autoscrub}) {
277 for my $line (@record) {
279 $istrash = 0 if $line =~ m|</datafield|;
282 if ($line =~ m/<datafield tag="(.{3})"/) {
284 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
289 push @trimmed, $line;
294 # add 903(?) with new record id
296 if ($conf->{'renumber-from'}) {
297 $recmeta{nid} = $conf->{'renumber=from'};
298 $renumber = join('', ' <datafield tag="', $conf->{'renumber-tag'},
299 '" ind1=" " ind2=" "> <subfield code="',
300 $conf->{'renumber-subfield'},
301 '">', $recmeta{nid}, "</subfield></datafield>\n");
302 my @tmp = @record[0 .. $#record - 1];
303 my $last = $record[$#record];
304 @record = (@tmp, $renumber, $last);
305 $conf->{'renumber-from'}++;
309 unless ($conf->{nocollapse})
310 { s/\n// for (@record) }
312 # write to old->new map file if needed
313 print $OLD2NEW $recmeta{oid}, "\t", $recmeta{nid}, "\n"
314 if ($conf->{'renumber-from'} and $conf->{'original-subfield'});
316 # and finally, actually write the record
320 sub print_fullcontext {
321 print $OUT "\r", ' ' x 72, "\n";
322 print $OUT $conf->{editmsg},"\n";
323 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
324 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
330 my $upper = int($conf->{window} / 2) + 1;
331 my $lower = int($conf->{window} / 2) - 1;
332 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
333 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
335 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
336 print $OUT '==> |', $record[$ptr];
337 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
344 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
347 #-----------------------------------------------------------------------------------
349 #-----------------------------------------------------------------------------------
352 my ($line_in, @chunks) = @_;
354 my $ofrom = shift @chunks;
355 if ($ofrom =~ /^'/ or !@chunks) {
356 until ($ofrom =~ /'$/)
357 { $ofrom .= join(' ','',shift @chunks) }
358 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
360 my $to = shift @chunks;
362 until ($to =~ /'$/ or !@chunks)
363 { $to .= join(' ','',shift @chunks) }
364 $to =~ s/^'//; $to =~ s/'$//;
368 for my $char (split(//,$ofrom)) {
369 $char = "\\" . $char if ($char =~ /\W/);
370 $from = join('', $from, $char);
373 $conf->{prevline} = $record[$ptr];
374 $record[$ptr] =~ s/$from/$to/;
380 $conf->{prevline} = $record[$ptr];
381 # remove <subfield stuff; extract (probably wrong) subfield code
382 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
383 # and move to front of line
384 $record[$ptr] = join(' ', $1 , $record[$ptr]);
385 # tear off trailing subfield tag from preceeding line
386 $record[$ptr - 1] =~ s|</subfield>\n||;
387 # join current line onto preceeding line
388 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
390 my @a = @record[0 .. $ptr - 1];
391 my @b = @record[$ptr + 1 .. $#record];
393 # move record pointer to previous line
400 unless ($conf->{prevline})
401 { print $OUT "No previously edited line to flip\n"; return }
402 my $temp = $record[$ptr];
403 $record[$ptr] = $conf->{prevline};
404 $conf->{prevline} = $temp;
410 $conf->{killline} = $record[$ptr];
411 my @a = @record[0 .. $ptr - 1];
412 my @b = @record[$ptr + 1 .. $#record];
419 unless ($conf->{killline})
420 { print $OUT "No killed line to yank\n"; return }
421 my @a = @record[0 .. $ptr - 1];
422 my @b = @record[$ptr .. $#record];
423 @record = (@a, $conf->{killline}, @b);
429 print $OUT "\nOrig. edit line :", $conf->{origline};
430 print $OUT "Current flip line:", $conf->{prevline} if $conf->{prevline};
431 print $OUT "Last killed line :", $conf->{killline} if $conf->{killline};
437 my ($line_in, @explanation) = @_;
438 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
439 write_record($EXMARC);
444 $ptr++ unless ($ptr == $#record);;
450 $ptr-- unless ($ptr == 0);
455 sub commit_edit { return 1 }
458 if ($conf->{window} == 15)
459 { print $OUT "Window can't be bigger than 15 lines\n"; return }
460 $conf->{window} += 2;
465 if ($conf->{window} == 5)
466 { print $OUT "Window can't be smaller than 5 lines\n"; return }
467 $conf->{window} -= 2;
473 Type a replacement for the indicated line, or enter a command.
475 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
476 < Expand context window | k Kill current line
477 > Contract context window | y Yank last killed line
478 p Move pointer to prev line | m Merge current line into preceding line
479 n Move pointer to next line | o Insert original line
480 c Print line context | f Flip current line and last edited line
481 d Print current saved lines |
482 -----------------------------+-------------------------------------------
483 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
484 contains spaces, it must be single-quoted
485 t Commit changes and resume automated operations
486 x Dump record to exception file
495 #-----------------------------------------------------------------------------------
497 #-----------------------------------------------------------------------------------
498 # defined a domain-specific language for specifying MARC tags to be dropped from
499 # records during processing. it is line oriented, and is specified as follows:
501 # each line may specify any number of tags to be included, either singly (\d{1,3})
502 # or as a range (\d{1,3}\.\.\d{1,3}
504 # if a single number is given, it must be between '000' and '999', inclusive.
506 # ranges obey the previous rule, and also the first number of the range must be less
507 # than the second number
509 # finally, any single range in a line may be followed by the keyword 'except'. every
510 # number or range after 'except' is excluded from the range specified. all these
511 # numbers must actually be within the range.
513 # specifying a tag twice is an error, to help prevent typos
516 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
517 open TRASH, '<', $conf->{trash}
518 or die "Can't open trash tags file!\n";
520 my $lastwasrange = 0;
521 my %lastrange = ( high => 0, low => 0);
524 my @chunks = split /\s+/;
525 while (my $chunk = shift @chunks) {
528 if ($chunk =~ /^\d{1,3}$/) {
529 trash_add($chunk, $except);
535 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
536 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
538 %lastrange = (low => $low, high => $high)
544 if ($chunk eq 'except') {
545 die "Keyword 'except' can only follow a range (line $.)\n"
546 unless $lastwasrange;
547 die "Keyword 'except' may only occur once per line (line $.)\n"
553 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
557 # remove original id sequence tag from trash hash if we know it
558 trash_add($conf->{'original-tag'}, 1)
559 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
562 sub trash_add_range {
563 my ($chunk, $except, $range) = @_;
564 my ($low,$high) = split /\.\./, $chunk;
565 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
568 die "Exception ranges must be within last addition range (line $.)\n"
569 if ($low < $range->{low} or $high > $range->{high});
571 for my $tag ($low..$high) {
572 trash_add($tag, $except)
578 my ($tag, $except) = @_;
579 my $trash = $conf->{trash};
581 die "Trash values must be valid tags (000-999)\n"
582 unless ($tag >= 0 and $tag <= 999);
585 delete $trash->{$tag};
587 die "Trash tag '$tag' specified twice (line $.)\n"
593 #-----------------------------------------------------------------------
597 Performs boring script initialization. Handles argument parsing,
606 # set mode on existing filehandles
607 binmode(STDIN, ':utf8');
609 my $rc = GetOptions( $c,
614 'renumber-from|rf=i',
616 'renumber-subfield|rs=i',
618 'original-subfield|os=i',
624 show_help() unless $rc;
625 show_help() if ($c->{help});
626 show_trashhelp() if ($c->{trashhelp});
629 $c->{output} = 'cleaned.incoming.marc.xml' unless defined $c->{output};
630 $c->{exception} = 'cleaned.exceptions.marc.xml' unless defined $c->{exception};
631 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
632 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
635 # autotrash 901, 903 if strip-nines
636 if ($c->{'strip-nines'}) {
637 $c->{trash}{901} = 1;
638 $c->{trash}{903} = 1;
641 my @keys = keys %{$c};
642 show_help() unless (@ARGV and @keys);
647 Usage is: marc-cleanup [OPTIONS] <filelist>
649 --output -o Cleaned MARCXML output filename
650 (default: cleaned.incoming.marc.xml)
651 --exception -x Exception (dumped records) MARCXML filename
652 (cleaned.exceptions.marc.xml)
653 --trash File containing trash tag data (see --trashhelp)
655 --renumber-from=NUM -rf Begin renumbering id sequence with this number
656 --renumber-tag -rt Tag to use in renumbering (default: 903)
657 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
658 --original-tag -ot Original id tag; will be kept in output even if
659 it appears in the trash file
660 --original-subfield -os Original id subfield code. If this is specified
661 and renumbering is in effect, an old-to-new mapping
662 file (old2new.incoming.map) will be generated.
664 --nocollapse -n Don't compress records to one line on output
665 --autoscrub -a Automatically remove non-numeric tags in data
666 --strip-nines Automatically remove any existing 901/903 tags in data
673 The marc-cleanup trash tags file is a simple plaintext file. It is a
674 line oriented format. There are three basic tokens:
678 * The "except" clause
680 Any number of tags and/or tag ranges can appear on a single line. A
681 tag cannot appear twice in the file, either alone or as part of a
682 range. This is to prevent errors in the trash tag listing. Items do
683 not have to be sorted within a line. These following lines are valid:
685 850 852 870..879 886 890 896..899
688 Ranges must be ordered internally. That is, "870..879" is valid while
691 Finally, there can be only one "except" clause on a line. It is
692 composed of the word "except" followed by one or more tags or
693 ranges. Except clauses must follow a range, and all tags within the
694 clause must be within the range which the clause follows.
696 900..997 except 935 950..959 987 994