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 my @record = (); # current record storage
18 my %recmeta = (); # metadata about current record
19 my $ptr = 0; # record index pointer
21 my $input = shift || 'incoming.marc.xml';
23 open MARC, '<:utf8', $input;
24 open my $NUMARC, '>:utf8', $conf->{output};
25 print $NUMARC '<?xml version="1.0" encoding="UTF-8"?>',"\n";
26 print $NUMARC '<collection xmlns="http://www.loc.gov/MARC21/slim">',"\n";
28 open my $EXMARC, '>:utf8', $conf->{exception};
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();
64 until ($ptr == $#record) {
66 if ($record[$ptr] =~ /&/ && $record[$ptr] !~ /&\w+?;/)
67 { edit("Naked ampersand"); $ptr= 0; next }
69 # tags must be numeric
70 if ($record[$ptr] =~ /<datafield tag="(.+?)"/) {
73 edit("Non-numerics in tag");
76 # test for existing 901/903 unless we're autocleaning them
77 unless ($conf->{'strip-nines'}) {
78 if ($match == 901 or $match == 903) {
79 edit("Incoming 901/903 found in data");
85 # subfields can't be non-alphanumeric
86 if ($record[$ptr] =~ /<subfield code="(.*?)"/) {
88 if ($match =~ /\P{IsAlnum}/ or $match eq '') {
89 edit("Junk in subfield code/Null subfield code");
96 write_record($NUMARC);
98 print $NUMARC "</collection>\n";
99 print $OUT "\nDone. \n";
102 #-----------------------------------------------------------------------------------
104 #-----------------------------------------------------------------------------------
106 sub do_automated_cleanups {
108 until ($ptr == $#record) {
109 # catch empty datafield elements
110 if ($record[$ptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
111 if ($record[$ptr + 1] =~ m|</datafield>|) {
112 my @a = @record[0 .. $ptr - 1];
113 my @b = @record[$ptr + 2 .. $#record];
115 message("Empty datafield scrubbed");
120 # and quasi-empty subfields
121 if ($record[$ptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
122 my $code = $1; my $content = $2;
123 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
124 my @a = @record[0 .. $ptr - 1];
125 my @b = @record[$ptr + 1 .. $#record];
127 message("Empty subfield scrubbed");
136 for $ptr (0 .. $#record) {
138 if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
140 if (length $leader < 24) {
141 $leader .= ' ' x (20 - length($leader));
143 $record[$ptr] = "<leader>$leader</leader>\n";
144 message("Short leader padded");
147 if ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
150 if (length $content < 40) {
151 $content .= ' ' x (40 - length($content));
152 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
153 message("Short 008 padded");
157 # clean misplaced dollarsigns
158 if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
159 $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
160 message("Dollar sign corrected");
163 # clean up tags with spaces in them
164 $record[$ptr] =~ s/tag=" /tag="00/g;
165 $record[$ptr] =~ s/tag=" /tag="0/g;
166 $record[$ptr] =~ s/tag="-/tag="0/g;
167 $record[$ptr] =~ s/tag="(\d\d) /tag="0$1/g;
169 # stow tag data if we're looking at it
170 if ($record[$ptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
176 # automatable subfield maladies
177 $record[$ptr] =~ s/code=" ">c/code="c">/;
178 $record[$ptr] =~ s/code=" ">\$/code="c"$>/;
182 #-----------------------------------------------------------------------------------
184 #-----------------------------------------------------------------------------------
189 Handles the Term::ReadLine loop
196 return if $conf->{trash}{ $recmeta{tag} };
197 $conf->{editmsg} = $msg;
200 # stow original problem line
201 $conf->{origline} = $record[$ptr];
204 my $line = $term->readline('marc-cleanup>');
205 my @chunks = split /\s+/, $line;
207 # lines with single-character first chunks are commands.
208 # make sure they exist.
209 if (length $chunks[0] == 1) {
210 unless (defined $commands{$chunks[0]}) {
211 print $OUT "No such command '", $chunks[0], "'\n";
216 if (defined $commands{$chunks[0]}) {
217 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
220 $record[$ptr] = "$line\n";
224 # set pointer to top on the way out
230 Constructs record arrays from the incoming MARC file and returns them
237 $l = <MARC> while (defined $l and $l !~ /<record>/);
238 return $l unless defined $l;
243 until ($l =~ m|</record>|)
244 { push @record, $l; $l = <MARC>; }
251 my $trash = $conf->{trash};
253 $conf->{rocount}++ if ($FH eq $NUMARC);
254 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
255 if(defined $recmeta{explanation});
257 # excise unwanted tags
258 if (keys %{$trash} or $conf->{autoscrub}) {
261 for my $line (@record) {
263 $istrash = 0 if $line =~ m|</datafield|;
266 if ($line =~ m/<datafield tag="(.{3})"/) {
268 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
273 push @trimmed, $line;
279 unless ($conf->{nocollapse}) {
280 s/\n// for (@record);
283 # add 903(?) with new record id
285 if ($conf->{'renumber-from'}) {
286 $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
287 '" ind1=" " ind2=" ">',
288 '<subfield code="', $conf->{'renumber-subfield'}, '">',
289 $conf->{'renumber-from'}, '</subfield></datafield>');
290 $renumber .= "\n" if $conf->{nocollapse};
291 push @record, $renumber;
292 $conf->{'renumber-from'}++;
296 print $FH "</record>\n";
299 sub print_fullcontext {
300 print $OUT "\r", ' ' x 72, "\n";
301 print $OUT $conf->{editmsg},"\n";
302 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
303 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
309 my $upper = int($conf->{window} / 2) + 1;
310 my $lower = int($conf->{window} / 2) - 1;
311 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
312 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
314 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
315 print $OUT '==> |', $record[$ptr];
316 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
323 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
326 #-----------------------------------------------------------------------------------
328 #-----------------------------------------------------------------------------------
331 my ($line_in, @chunks) = @_;
333 my $ofrom = shift @chunks;
334 if ($ofrom =~ /^'/ or !@chunks) {
335 until ($ofrom =~ /'$/)
336 { $ofrom .= join(' ','',shift @chunks) }
337 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
339 my $to = shift @chunks;
341 until ($to =~ /'$/ or !@chunks)
342 { $to .= join(' ','',shift @chunks) }
343 $to =~ s/^'//; $to =~ s/'$//;
347 for my $char (split(//,$ofrom)) {
348 $char = "\\" . $char if ($char =~ /\W/);
349 $from = join('', $from, $char);
352 $conf->{prevline} = $record[$ptr];
353 $record[$ptr] =~ s/$from/$to/;
359 $conf->{prevline} = $record[$ptr];
360 # remove <subfield stuff; extract (probably wrong) subfield code
361 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
362 # and move to front of line
363 $record[$ptr] = join(' ', $1 , $record[$ptr]);
364 # tear off trailing subfield tag from preceeding line
365 $record[$ptr - 1] =~ s|</subfield>\n||;
366 # join current line onto preceeding line
367 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
369 my @a = @record[0 .. $ptr - 1];
370 my @b = @record[$ptr + 1 .. $#record];
372 # move record pointer to previous line
379 unless ($conf->{prevline})
380 { print $OUT "No previously edited line to flip\n"; return }
381 my $temp = $record[$ptr];
382 $record[$ptr] = $conf->{prevline};
383 $conf->{prevline} = $temp;
389 $conf->{killline} = $record[$ptr];
390 my @a = @record[0 .. $ptr - 1];
391 my @b = @record[$ptr + 1 .. $#record];
398 unless ($conf->{killline})
399 { print $OUT "No killed line to yank\n"; return }
400 my @a = @record[0 .. $ptr - 1];
401 my @b = @record[$ptr .. $#record];
402 @record = (@a, $conf->{killline}, @b);
408 print $OUT "\nOrig. edit line :", $conf->{origline};
409 print $OUT "Current flip line:", $conf->{prevline} if $conf->{prevline};
410 print $OUT "Last killed line :", $conf->{killline} if $conf->{killline};
416 my ($line_in, @explanation) = @_;
417 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
418 write_record($EXMARC);
423 $ptr++ unless ($ptr == $#record);;
429 $ptr-- unless ($ptr == 0);
434 sub commit_edit { return 1 }
437 if ($conf->{window} == 15)
438 { print $OUT "Window can't be bigger than 15 lines\n"; return }
439 $conf->{window} += 2;
444 if ($conf->{window} == 5)
445 { print $OUT "Window can't be smaller than 5 lines\n"; return }
446 $conf->{window} -= 2;
452 Type a replacement for the indicated line, or enter a command.
454 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
455 < Expand context window | k Kill current line
456 > Contract context window | y Yank last killed line
457 p Move pointer to prev line | m Merge current line into preceding line
458 n Move pointer to next line | o Insert original line
459 c Print line context | f Flip current line and last edited line
460 d Print current saved lines |
461 -----------------------------+-------------------------------------------
462 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
463 contains spaces, it must be single-quoted
464 t Commit changes and resume automated operations
465 x Dump record to exception file
474 #-----------------------------------------------------------------------------------
476 #-----------------------------------------------------------------------------------
477 # defined a domain-specific language for specifying MARC tags to be dropped from
478 # records during processing. it is line oriented, and is specified as follows:
480 # each line may specify any number of tags to be included, either singly (\d{1,3})
481 # or as a range (\d{1,3}\.\.\d{1,3}
483 # if a single number is given, it must be between '000' and '999', inclusive.
485 # ranges obey the previous rule, and also the first number of the range must be less
486 # than the second number
488 # finally, any single range in a line may be followed by the keyword 'except'. every
489 # number or range after 'except' is excluded from the range specified. all these
490 # numbers must actually be within the range.
492 # specifying a tag twice is an error, to help prevent typos
495 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
496 open TRASH, '<', $conf->{trash}
497 or die "Can't open trash tags file!\n";
499 my $lastwasrange = 0;
500 my %lastrange = ( high => 0, low => 0);
503 my @chunks = split /\s+/;
504 while (my $chunk = shift @chunks) {
507 if ($chunk =~ /^\d{1,3}$/) {
508 trash_add($chunk, $except);
514 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
515 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
517 %lastrange = (low => $low, high => $high)
523 if ($chunk eq 'except') {
524 die "Keyword 'except' can only follow a range (line $.)\n"
525 unless $lastwasrange;
526 die "Keyword 'except' may only occur once per line (line $.)\n"
532 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
536 # remove original id sequence tag from trash hash if we know it
537 trash_add($conf->{'original-tag'}, 1)
538 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
541 sub trash_add_range {
542 my ($chunk, $except, $range) = @_;
543 my ($low,$high) = split /\.\./, $chunk;
544 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
547 die "Exception ranges must be within last addition range (line $.)\n"
548 if ($low < $range->{low} or $high > $range->{high});
550 for my $tag ($low..$high) {
551 trash_add($tag, $except)
557 my ($tag, $except) = @_;
558 my $trash = $conf->{trash};
560 die "Trash values must be valid tags (000-999)\n"
561 unless ($tag >= 0 and $tag <= 999);
564 delete $trash->{$tag};
566 die "Trash tag '$tag' specified twice (line $.)\n"
572 #-----------------------------------------------------------------------
576 Performs boring script initialization. Handles argument parsing,
585 # set mode on existing filehandles
586 binmode(STDIN, ':utf8');
588 my $rc = GetOptions( $c,
593 'renumber-from|rf=i',
596 'renumber-subfield|rt=i',
601 show_help() unless $rc;
602 show_help() if ($c->{help});
605 $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
606 $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
607 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
608 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
611 my @keys = keys %{$c};
612 show_help() unless (@ARGV and @keys);
617 Usage is: $0 [OPTIONS] <filelist>
619 --output -o Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
620 --exception -x Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)