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
184 if ($record[$ptr] =~ m/<datafield tag="(?<TAG>.{3})"/) {
185 $recmeta{tag} = $+{TAG};
186 $record[$ptr] =~ m/ind1="(?<IND1>.)"/;
187 $recmeta{ind1} = $+{IND1} || '';
188 $record[$ptr] =~ m/ind2="(?<IND2>.)"/;
189 $recmeta{ind2} = $+{IND2} || '';
191 unless (defined $recmeta{tag}) {
192 message("Autokill record: no detectable tag");
193 dump_record("No detectable tag") ;
196 # and since we are looking at a tag, see if it's the original id
197 if ($conf->{'original-subfield'} and
198 $recmeta{tag} == $conf->{'original-tag'}) {
199 my $line = $record[$ptr]; my $lptr = $ptr;
200 my $osub = $conf->{'original-subfield'};
201 $recmeta{oid} = 'NONE';
203 until ($line =~ m|</record>|) {
205 $line = $record[$lptr];
206 $recmeta{oid} = $+{TAG}
207 if ($line =~ /<subfield code="$osub">(.+?)</);
213 #-----------------------------------------------------------------------------------
215 #-----------------------------------------------------------------------------------
219 Handles the Term::ReadLine loop
226 return if $conf->{trash}{ $recmeta{tag} };
227 $conf->{editmsg} = $msg;
230 # stow original problem line
231 $recmeta{origline} = $record[$ptr];
234 my $line = $term->readline('marc-cleanup>');
235 my @chunks = split /\s+/, $line;
237 # lines with single-character first chunks are commands.
238 # make sure they exist.
239 if (length $chunks[0] == 1) {
240 unless (defined $commands{$chunks[0]}) {
241 print $OUT "No such command '", $chunks[0], "'\n";
246 if (defined $commands{$chunks[0]}) {
247 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
250 $recmeta{prevline} = $record[$ptr];
251 $record[$ptr] = "$line\n";
255 # set pointer to top on the way out
261 Constructs record arrays from the incoming MARC file and returns them
268 $l = <MARC> while (defined $l and $l !~ /<record>/);
269 return $l unless defined $l;
274 until ($l =~ m|</record>|)
275 { push @record, $l; $l = <MARC>; }
282 my $trash = $conf->{trash};
286 open $EXMARC, '>:utf8', $conf->{exception}
287 or die "Can't open exception file $!\n";
291 $conf->{rocount}++ if ($FH eq $NUMARC);
292 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
293 if(defined $recmeta{explanation});
295 # excise unwanted tags
296 if (keys %{$trash} or $conf->{autoscrub}) {
299 for my $line (@record) {
301 $istrash = 0 if $line =~ m|</datafield|;
304 if ($line =~ m/<datafield tag="(.{3})"/) {
306 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
311 push @trimmed, $line;
316 # add 903(?) with new record id
318 if ($conf->{'renumber-from'}) {
319 $recmeta{nid} = $conf->{'renumber-from'};
320 $renumber = join('', ' <datafield tag="', $conf->{'renumber-tag'},
321 '" ind1=" " ind2=" "> <subfield code="',
322 $conf->{'renumber-subfield'},
323 '">', $recmeta{nid}, "</subfield></datafield>\n");
324 my @tmp = @record[0 .. $#record - 1];
325 my $last = $record[$#record];
326 @record = (@tmp, $renumber, $last);
327 $conf->{'renumber-from'}++;
330 # scrub newlines (unless told not to or writing exception record)
331 unless ($conf->{nocollapse} or $FH eq $EXMARC)
332 { s/\n// for (@record) }
334 # write to old->new map file if needed
335 if ($conf->{'renumber-from'} and $conf->{'original-subfield'}) {
336 unless (defined $recmeta{oid}) {
337 my $msg = join(' ', "No old id num found");
340 print $OLD2NEW $recmeta{oid}, "\t", $recmeta{nid}, "\n"
344 # actually write the record
345 print $FH @record,"\n";
347 # if we were dumping to exception file, nuke the record and set ptr
348 # to terminate processing loop
353 sub print_fullcontext {
354 print $OUT "\r", ' ' x 72, "\n";
355 print $OUT $conf->{editmsg},"\n";
356 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
357 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
358 print $OUT " @ ", $conf->{ricount}, "/", $conf->{rocount} + 1;
364 my $upper = int($conf->{window} / 2) + 1;
365 my $lower = int($conf->{window} / 2) - 1;
366 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
367 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
369 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
370 print $OUT '==> |', $record[$ptr];
371 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
378 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
381 #-----------------------------------------------------------------------------------
383 #-----------------------------------------------------------------------------------
388 my $ofrom = shift @chunks;
389 if ($ofrom =~ /^'/) {
390 until ($ofrom =~ /'$/ or !@chunks)
391 { $ofrom .= join(' ','',shift @chunks) }
392 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
394 my $to = shift @chunks;
396 until ($to =~ /'$/ or !@chunks)
397 { $to .= join(' ','',shift @chunks) }
398 $to =~ s/^'//; $to =~ s/'$//;
402 for my $char (split(//,$ofrom)) {
403 $char = "\\" . $char if ($char =~ /\W/);
404 $from = join('', $from, $char);
407 $recmeta{prevline} = $record[$ptr];
408 $record[$ptr] =~ s/$from/$to/;
414 $recmeta{prevline} = $record[$ptr];
415 # remove <subfield stuff; extract (probably wrong) subfield code
416 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
417 # and move to front of line
418 $record[$ptr] = join(' ', $1 , $record[$ptr]);
419 # tear off trailing subfield tag from preceeding line
420 $record[$ptr - 1] =~ s|</subfield>\n||;
421 # join current line onto preceeding line
422 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
424 my @a = @record[0 .. $ptr - 1];
425 my @b = @record[$ptr + 1 .. $#record];
427 # move record pointer to previous line
434 unless ($recmeta{prevline})
435 { print $OUT "No previously edited line to flip\n"; return }
436 my $temp = $record[$ptr];
437 $record[$ptr] = $recmeta{prevline};
438 $recmeta{prevline} = $temp;
444 $recmeta{killline} = $record[$ptr];
445 my @a = @record[0 .. $ptr - 1];
446 my @b = @record[$ptr + 1 .. $#record];
453 unless ($recmeta{killline})
454 { print $OUT "No killed line to yank\n"; return }
455 my @a = @record[0 .. $ptr - 1];
456 my @b = @record[$ptr .. $#record];
457 @record = (@a, $conf->{killline}, @b);
462 sub insert_original {
463 $record[$ptr] = $recmeta{origline};
469 print $OUT "\nOrig. edit line :", $recmeta{origline};
470 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
471 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
477 my (@explanation) = @_;
478 print $OUT @explanation;
479 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
480 write_record($EXMARC);
485 $ptr++ unless ($ptr == $#record);;
491 $ptr-- unless ($ptr == 0);
496 sub commit_edit { return 1 }
499 if ($conf->{window} == 15)
500 { print $OUT "Window can't be bigger than 15 lines\n"; return }
501 $conf->{window} += 2;
506 if ($conf->{window} == 5)
507 { print $OUT "Window can't be smaller than 5 lines\n"; return }
508 $conf->{window} -= 2;
514 Type a replacement for the indicated line, or enter a command.
516 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
517 < Expand context window | k Kill current line
518 > Contract context window | y Yank last killed line
519 p Move pointer to prev line | m Merge current line into preceding line
520 n Move pointer to next line | o Insert original line
521 c Print line context | f Flip current line and last edited line
522 d Print current saved lines |
523 -----------------------------+-------------------------------------------
524 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
525 contains spaces, it must be single-quoted
526 t Commit changes and resume automated operations
527 x Dump record to exception file
536 #-----------------------------------------------------------------------------------
538 #-----------------------------------------------------------------------------------
539 # defined a domain-specific language for specifying MARC tags to be dropped from
540 # records during processing. it is line oriented, and is specified as follows:
542 # each line may specify any number of tags to be included, either singly (\d{1,3})
543 # or as a range (\d{1,3}\.\.\d{1,3}
545 # if a single number is given, it must be between '000' and '999', inclusive.
547 # ranges obey the previous rule, and also the first number of the range must be less
548 # than the second number
550 # finally, any single range in a line may be followed by the keyword 'except'. every
551 # number or range after 'except' is excluded from the range specified. all these
552 # numbers must actually be within the range.
554 # specifying a tag twice is an error, to help prevent typos
557 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
558 open TRASH, '<', $conf->{trashfile}
559 or die "Can't open trash tags file!\n";
561 my $lastwasrange = 0;
562 my %lastrange = ( high => 0, low => 0);
565 my @chunks = split /\s+/;
566 while (my $chunk = shift @chunks) {
569 if ($chunk =~ /^\d{1,3}$/) {
570 trash_add($chunk, $except);
576 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
577 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
579 %lastrange = (low => $low, high => $high)
585 if ($chunk eq 'except') {
586 die "Keyword 'except' can only follow a range (line $.)\n"
587 unless $lastwasrange;
588 die "Keyword 'except' may only occur once per line (line $.)\n"
594 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
598 # remove original id sequence tag from trash hash if we know it
599 trash_add($conf->{'original-tag'}, 1)
600 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
603 sub trash_add_range {
604 my ($chunk, $except, $range) = @_;
605 my ($low,$high) = split /\.\./, $chunk;
606 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
609 die "Exception ranges must be within last addition range (line $.)\n"
610 if ($low < $range->{low} or $high > $range->{high});
612 for my $tag ($low..$high) {
613 trash_add($tag, $except)
619 my ($tag, $except) = @_;
620 my $trash = $conf->{trash};
622 die "Trash values must be valid tags (000-999)\n"
623 unless ($tag >= 0 and $tag <= 999);
626 delete $trash->{$tag};
628 die "Trash tag '$tag' specified twice (line $.)\n"
634 #-----------------------------------------------------------------------
638 Performs boring script initialization. Handles argument parsing,
647 # set mode on existing filehandles
648 binmode(STDIN, ':utf8');
650 my $rc = GetOptions( $c,
656 'renumber-from|rf=i',
658 'renumber-subfield|rs=s',
660 'original-subfield|os=s',
667 show_help() unless $rc;
668 show_help() if ($c->{help});
669 show_trashhelp() if ($c->{trashhelp});
673 $c->{output} = join('.',$c->{prefix},'clean','marc','xml');
674 $c->{exception} = join('.',$c->{prefix},'marc','ex');
676 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
677 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
680 # autotrash 901, 903 if strip-nines
681 if ($c->{'strip-nines'}) {
682 $c->{trash}{901} = 1;
683 $c->{trash}{903} = 1;
686 my @keys = keys %{$c};
687 show_help() unless (@ARGV and @keys);
692 Usage is: marc-cleanup [OPTIONS] <filelist>
694 --output -o Cleaned MARCXML output filename
695 --exception -x Exception (dumped records) MARCXML filename
697 --prefix=<PREFIX>> -p Shared prefix for output/exception files. Will
698 produce PREFIX.marc.xml and PREFIX.ex.xml
700 --trashfile -t File containing trash tag data (see --trashhelp)
702 --renumber-from -rf Begin renumbering id sequence with this number
703 --renumber-tag -rt Tag to use in renumbering (default: 903)
704 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
705 --original-tag -ot Original id tag; will be kept in output even if
706 it appears in the trash file
707 --original-subfield -os Original id subfield code. If this is specified
708 and renumbering is in effect, an old-to-new mapping
709 file (old2new.map) will be generated.
711 --nocollapse -n Don't compress records to one line on output
712 --autoscrub -a Automatically remove non-numeric tags in data
713 --strip-nines Automatically remove any existing 901/903 tags in data
715 --script Store human-initiated ops in scriptfile (.mcscript)
723 The marc-cleanup trash tags file is a simple plaintext file. It is a
724 line oriented format. There are three basic tokens:
728 * The "except" clause
730 Any number of tags and/or tag ranges can appear on a single line. A
731 tag cannot appear twice in the file, either alone or as part of a
732 range. This is to prevent errors in the trash tag listing. Items do
733 not have to be sorted within a line. These following lines are valid:
735 850 852 870..879 886 890 896..899
738 Ranges must be ordered internally. That is, "870..879" is valid while
741 Finally, there can be only one "except" clause on a line. It is
742 composed of the word "except" followed by one or more tags or
743 ranges. Except clauses must follow a range, and all tags within the
744 clause must be within the range which the clause follows.
746 900..997 except 935 950..959 987 994