10 my $term = new Term::ReadLine 'yaz-cleanup';
11 my $OUT = $term->OUT || \*STDOUT;
15 # initialization and setup
18 populate_trash() if ($conf->{trashfile});
20 # set up files, since everything appears to be in order
21 open MARC, '<:utf8', (shift || 'incoming.marc.xml')
22 or die "Can't open input file $!\n";
23 open my $NUMARC, '>:utf8', $conf->{output}
24 or die "Can't open output file $!\n";
25 open my $OLD2NEW, '>', 'old2new.map'
26 if ($conf->{'renumber-from'} and $conf->{'original-subfield'});
28 print $NUMARC "<collection>\n";
30 my @record = (); # current record storage
31 my %recmeta = (); # metadata about current record
32 my $ptr = 0; # record index pointer
34 # this is the dispatch table which drives command selection in
36 my %commands = ( c => \&print_fullcontext,
39 '<' => \&widen_window,
40 '>' => \&narrow_window,
42 o => \&insert_original,
56 my @spinner = qw(- / | \\);
59 while ( buildrecord() ) {
60 unless ($conf->{ricount} % 100) {
61 print "\rWorking... ", $spinner[$sidx];
62 $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
65 my $rc = do_automated_cleanups();
69 until ($ptr == $#record) {
71 if ($record[$ptr] =~ /&/ && $record[$ptr] !~ /&\w+?;/)
72 { edit("Naked ampersand"); $ptr= 0; next }
74 if ($record[$ptr] =~ /<datafield tag="(.+?)"/) {
76 # tags must be numeric
78 edit("Non-numerics in tag") unless $conf->{autoscrub};
81 # test for existing 901/903 unless we're autocleaning them
82 unless ($conf->{'strip-nines'}) {
83 if ($match == 901 or $match == 903) {
84 edit("Incoming 901/903 found in data");
90 # subfields can't be non-alphanumeric
91 if ($record[$ptr] =~ /<subfield code="(.*?)"/) {
92 if ($1 =~ /\P{IsAlnum}/ or $1 eq '') {
93 edit("Junk in subfield code/Null subfield code");
97 # subfields can't be non-alphanumeric
98 if ($record[$ptr] =~ /<subfield code="(\w{2,})"/) {
99 edit("Subfield code larger than 1 char");
105 write_record($NUMARC);
107 print $NUMARC "</collection>\n";
108 print $OUT "\nDone. \n";
111 #-----------------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------------
115 sub do_automated_cleanups {
117 until ($ptr == $#record) {
118 # get datafield/tag data if we have it
119 my $rc = stow_record_data();
122 # catch empty datafield elements
123 if ($record[$ptr] =~ m/<datafield tag="..."/) {
124 if ($record[$ptr + 1] =~ m|</datafield>|) {
125 my @a = @record[0 .. $ptr - 1];
126 my @b = @record[$ptr + 2 .. $#record];
128 message("Empty datafield scrubbed");
133 # and quasi-empty subfields
134 if ($record[$ptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
135 my $code = $1; my $content = $2;
136 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
137 my @a = @record[0 .. $ptr - 1];
138 my @b = @record[$ptr + 1 .. $#record];
140 message("Empty subfield scrubbed");
149 for $ptr (0 .. $#record) {
151 if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
153 if (length $leader < 24) {
154 $leader .= ' ' x (20 - length($leader));
156 $record[$ptr] = "<leader>$leader</leader>\n";
157 message("Short leader padded");
160 if ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
163 if (length $content < 40) {
164 $content .= ' ' x (40 - length($content));
165 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
166 message("Short 008 padded");
170 # clean misplaced dollarsigns
171 if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
172 $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
173 message("Dollar sign corrected");
176 # clean up tags with spaces in them
177 $record[$ptr] =~ s/tag=" /tag="00/g;
178 $record[$ptr] =~ s/tag=" /tag="0/g;
179 $record[$ptr] =~ s/tag="-/tag="0/g;
180 $record[$ptr] =~ s/tag="(\d\d) /tag="0$1/g;
182 # automatable subfield maladies
183 $record[$ptr] =~ s/code=" ">c/code="c">/;
184 $record[$ptr] =~ s/code=" ">\$/code="c">\$/;
189 sub stow_record_data {
190 # get tag data if we're looking at it
191 if ($record[$ptr] =~ m/<datafield tag="(?<TAG>.{3})"/) {
192 $recmeta{tag} = $+{TAG};
193 $record[$ptr] =~ m/ind1="(?<IND1>.)"/;
194 $recmeta{ind1} = $+{IND1} || '';
195 $record[$ptr] =~ m/ind2="(?<IND2>.)"/;
196 $recmeta{ind2} = $+{IND2} || '';
198 unless (defined $recmeta{tag}) {
199 message("Autokill record: no detectable tag");
200 dump_record("No detectable tag") ;
204 # and since we are looking at a tag, see if it's the original id
205 if ($conf->{'original-subfield'} and $recmeta{tag} == $conf->{'original-tag'}) {
206 my $line = $record[$ptr]; my $lptr = $ptr;
207 my $osub = $conf->{'original-subfield'};
208 $recmeta{oid} = 'NONE';
210 until ($line =~ m|</record>|) {
211 if ($line =~ /<subfield code="$osub">(.+?)</)
212 { $recmeta{oid} = $1 }
214 $line = $record[$lptr];
216 unless (defined $recmeta{oid}) {
217 message("Autokill record: no oldid when old2new mapping requested");
218 dump_record("No old id found");
226 #-----------------------------------------------------------------------------------
228 #-----------------------------------------------------------------------------------
232 Handles the Term::ReadLine loop
239 return if $conf->{trash}{ $recmeta{tag} };
240 $conf->{editmsg} = $msg;
243 # stow original problem line
244 $recmeta{origline} = $record[$ptr];
247 my $line = $term->readline('marc-cleanup>');
248 my @chunks = split /\s+/, $line;
250 # lines with single-character first chunks are commands.
251 # make sure they exist.
252 if (length $chunks[0] == 1) {
253 unless (defined $commands{$chunks[0]}) {
254 print $OUT "No such command '", $chunks[0], "'\n";
259 if (defined $commands{$chunks[0]}) {
260 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
263 $recmeta{prevline} = $record[$ptr];
264 $record[$ptr] = "$line\n";
268 # set pointer to top on the way out
274 Constructs record arrays from the incoming MARC file and returns them
281 $l = <MARC> while (defined $l and $l !~ /<record>/);
282 return $l unless defined $l;
287 until ($l =~ m|</record>|)
288 { push @record, $l; $l = <MARC>; }
295 my $trash = $conf->{trash};
299 open $EXMARC, '>:utf8', $conf->{exception}
300 or die "Can't open exception file $!\n";
304 $conf->{rocount}++ if ($FH eq $NUMARC);
305 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
306 if(defined $recmeta{explanation});
308 # excise unwanted tags
309 if (keys %{$trash} or $conf->{autoscrub}) {
312 for my $line (@record) {
314 $istrash = 0 if $line =~ m|</datafield|;
317 if ($line =~ m/<datafield tag="(.{3})"/) {
319 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
324 push @trimmed, $line;
329 # add 903(?) with new record id
331 if ($conf->{'renumber-from'}) {
332 $recmeta{nid} = $conf->{'renumber-from'};
333 $renumber = join('', ' <datafield tag="', $conf->{'renumber-tag'},
334 '" ind1=" " ind2=" "> <subfield code="',
335 $conf->{'renumber-subfield'},
336 '">', $recmeta{nid}, "</subfield></datafield>\n");
337 my @tmp = @record[0 .. $#record - 1];
338 my $last = $record[$#record];
339 @record = (@tmp, $renumber, $last);
340 $conf->{'renumber-from'}++;
343 # scrub newlines (unless told not to or writing exception record)
344 unless ($conf->{nocollapse} or $FH eq $EXMARC)
345 { s/\n// for (@record) }
347 # write to old->new map file if needed
348 if ($conf->{'renumber-from'} and $conf->{'original-subfield'}) {
349 print $OLD2NEW $recmeta{oid}, "\t", $recmeta{nid}, "\n"
352 # actually write the record
353 print $FH @record,"\n";
355 # if we were dumping to exception file, nuke the record and set ptr
356 # to terminate processing loop
361 sub print_fullcontext {
362 print $OUT "\r", ' ' x 72, "\n";
363 print $OUT $conf->{editmsg},"\n";
364 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
365 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
366 print $OUT " @ ", $conf->{ricount}, "/", $conf->{rocount} + 1;
372 my $upper = int($conf->{window} / 2) + 1;
373 my $lower = int($conf->{window} / 2) - 1;
374 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
375 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
377 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
378 print $OUT '==> |', $record[$ptr];
379 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
386 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
389 #-----------------------------------------------------------------------------------
391 #-----------------------------------------------------------------------------------
396 my $ofrom = shift @chunks;
397 if ($ofrom =~ /^'/) {
398 until ($ofrom =~ /'$/ or !@chunks)
399 { $ofrom .= join(' ','',shift @chunks) }
400 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
402 my $to = shift @chunks;
404 until ($to =~ /'$/ or !@chunks)
405 { $to .= join(' ','',shift @chunks) }
406 $to =~ s/^'//; $to =~ s/'$//;
410 for my $char (split(//,$ofrom)) {
411 $char = "\\" . $char if ($char =~ /\W/);
412 $from = join('', $from, $char);
415 $recmeta{prevline} = $record[$ptr];
416 $record[$ptr] =~ s/$from/$to/;
422 $recmeta{prevline} = $record[$ptr];
423 # remove <subfield stuff; extract (probably wrong) subfield code
424 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
425 # and move to front of line
426 $record[$ptr] = join(' ', $1 , $record[$ptr]);
427 # tear off trailing subfield tag from preceeding line
428 $record[$ptr - 1] =~ s|</subfield>\n||;
429 # join current line onto preceeding line
430 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
432 my @a = @record[0 .. $ptr - 1];
433 my @b = @record[$ptr + 1 .. $#record];
435 # move record pointer to previous line
442 unless ($recmeta{prevline})
443 { print $OUT "No previously edited line to flip\n"; return }
444 my $temp = $record[$ptr];
445 $record[$ptr] = $recmeta{prevline};
446 $recmeta{prevline} = $temp;
452 $recmeta{killline} = $record[$ptr];
453 my @a = @record[0 .. $ptr - 1];
454 my @b = @record[$ptr + 1 .. $#record];
461 unless ($recmeta{killline})
462 { print $OUT "No killed line to yank\n"; return }
463 my @a = @record[0 .. $ptr - 1];
464 my @b = @record[$ptr .. $#record];
465 @record = (@a, $conf->{killline}, @b);
470 sub insert_original {
471 $record[$ptr] = $recmeta{origline};
477 print $OUT "\nOrig. edit line :", $recmeta{origline};
478 print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
479 print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
485 my (@explanation) = @_;
486 print $OUT @explanation;
487 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
488 write_record($EXMARC);
493 $ptr++ unless ($ptr == $#record);;
499 $ptr-- unless ($ptr == 0);
504 sub commit_edit { return 1 }
507 if ($conf->{window} == 15)
508 { print $OUT "Window can't be bigger than 15 lines\n"; return }
509 $conf->{window} += 2;
514 if ($conf->{window} == 5)
515 { print $OUT "Window can't be smaller than 5 lines\n"; return }
516 $conf->{window} -= 2;
522 Type a replacement for the indicated line, or enter a command.
524 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
525 < Expand context window | k Kill current line
526 > Contract context window | y Yank last killed line
527 p Move pointer to prev line | m Merge current line into preceding line
528 n Move pointer to next line | o Insert original line
529 c Print line context | f Flip current line and last edited line
530 d Print current saved lines |
531 -----------------------------+-------------------------------------------
532 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
533 contains spaces, it must be single-quoted
534 t Commit changes and resume automated operations
535 x Dump record to exception file
544 #-----------------------------------------------------------------------------------
546 #-----------------------------------------------------------------------------------
547 # defined a domain-specific language for specifying MARC tags to be dropped from
548 # records during processing. it is line oriented, and is specified as follows:
550 # each line may specify any number of tags to be included, either singly (\d{1,3})
551 # or as a range (\d{1,3}\.\.\d{1,3}
553 # if a single number is given, it must be between '000' and '999', inclusive.
555 # ranges obey the previous rule, and also the first number of the range must be less
556 # than the second number
558 # finally, any single range in a line may be followed by the keyword 'except'. every
559 # number or range after 'except' is excluded from the range specified. all these
560 # numbers must actually be within the range.
562 # specifying a tag twice is an error, to help prevent typos
565 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
566 open TRASH, '<', $conf->{trashfile}
567 or die "Can't open trash tags file!\n";
569 my $lastwasrange = 0;
570 my %lastrange = ( high => 0, low => 0);
573 my @chunks = split /\s+/;
574 while (my $chunk = shift @chunks) {
577 if ($chunk =~ /^\d{1,3}$/) {
578 trash_add($chunk, $except);
584 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
585 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
587 %lastrange = (low => $low, high => $high)
593 if ($chunk eq 'except') {
594 die "Keyword 'except' can only follow a range (line $.)\n"
595 unless $lastwasrange;
596 die "Keyword 'except' may only occur once per line (line $.)\n"
602 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
606 # remove original id sequence tag from trash hash if we know it
607 trash_add($conf->{'original-tag'}, 1)
608 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
611 sub trash_add_range {
612 my ($chunk, $except, $range) = @_;
613 my ($low,$high) = split /\.\./, $chunk;
614 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
617 die "Exception ranges must be within last addition range (line $.)\n"
618 if ($low < $range->{low} or $high > $range->{high});
620 for my $tag ($low..$high) {
621 trash_add($tag, $except)
627 my ($tag, $except) = @_;
628 my $trash = $conf->{trash};
630 die "Trash values must be valid tags (000-999)\n"
631 unless ($tag >= 0 and $tag <= 999);
634 delete $trash->{$tag};
636 die "Trash tag '$tag' specified twice (line $.)\n"
642 #-----------------------------------------------------------------------
646 Performs boring script initialization. Handles argument parsing,
655 # set mode on existing filehandles
656 binmode(STDIN, ':utf8');
658 my $rc = GetOptions( $c,
664 'renumber-from|rf=i',
666 'renumber-subfield|rs=s',
668 'original-subfield|os=s',
675 show_help() unless $rc;
676 show_help() if ($c->{help});
677 show_trashhelp() if ($c->{trashhelp});
680 my $pfx = $c->{prefix} // "bibs";
681 $c->{output} = join('.',$c->{prefix},'clean','marc','xml');
682 $c->{exception} = join('.',$c->{prefix},'exception','marc','xml');
683 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
684 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
687 # autotrash 901, 903 if strip-nines
688 if ($c->{'strip-nines'}) {
689 $c->{trash}{901} = 1;
690 $c->{trash}{903} = 1;
693 my @keys = keys %{$c};
694 show_help() unless (@ARGV and @keys);
699 Usage is: marc-cleanup [OPTIONS] <filelist>
701 --output -o Cleaned MARCXML output filename
702 --exception -x Exception (dumped records) MARCXML filename
704 --prefix=<PREFIX>> -p Shared prefix for output/exception files. Will produce
705 PREFIX.clean.marc.xml and PREFIX.exception.marc.xml
707 --renumber-from -rf Begin renumbering id sequence with this number
708 --renumber-tag -rt Tag to use in renumbering (default: 903)
709 --renumber-subfield -rs Subfield code to use in renumbering (default: a)
710 --original-tag -ot Original id tag; will be kept in output even if
711 it appears in the trash file
712 --original-subfield -os Original id subfield code. If this is specified
713 and renumbering is in effect, an old-to-new mapping
714 file (old2new.map) will be generated.
716 --autoscrub -a Automatically remove non-numeric tags in data
717 --nocollapse -n Don't compress records to one line on output
718 --strip-nines Automatically remove any existing 901/903 tags in data
719 --trashfile -t File containing trash tag data (see --trashhelp)
722 --script Store human-initiated ops in scriptfile (.mcscript)
730 The marc-cleanup trash tags file is a simple plaintext file. It is a
731 line oriented format. There are three basic tokens:
735 * The "except" clause
737 Any number of tags and/or tag ranges can appear on a single line. A
738 tag cannot appear twice in the file, either alone or as part of a
739 range. This is to prevent errors in the trash tag listing. Items do
740 not have to be sorted within a line. These following lines are valid:
742 850 852 870..879 886 890 896..899
745 Ranges must be ordered internally. That is, "870..879" is valid while
748 Finally, there can be only one "except" clause on a line. It is
749 composed of the word "except" followed by one or more tags or
750 ranges. Except clauses must follow a range, and all tags within the
751 clause must be within the range which the clause follows.
753 900..997 except 935 950..959 987 994