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");
78 # subfields can't be non-alphanumeric
79 if ($record[$ptr] =~ /<subfield code="(.*?)"/) {
81 if ($match =~ /\P{IsAlnum}/ or $match eq '') {
82 edit("Junk in subfield code/Null subfield code");
88 write_record($NUMARC);
90 print $NUMARC "</collection>\n";
91 print $OUT "\nDone. \n";
94 #-----------------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------------
98 sub do_automated_cleanups {
100 until ($ptr == $#record) {
101 # catch empty datafield elements
102 if ($record[$ptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
103 if ($record[$ptr + 1] =~ m|</datafield>|) {
104 my @a = @record[0 .. $ptr - 1];
105 my @b = @record[$ptr + 2 .. $#record];
107 message("Empty datafield scrubbed");
112 # and quasi-empty subfields
113 if ($record[$ptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
114 my $code = $1; my $content = $2;
115 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
116 my @a = @record[0 .. $ptr - 1];
117 my @b = @record[$ptr + 1 .. $#record];
119 message("Empty subfield scrubbed");
128 for $ptr (0 .. $#record) {
130 if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
132 if (length $leader < 24) {
133 $leader .= ' ' x (20 - length($leader));
135 $record[$ptr] = "<leader>$leader</leader>\n";
136 message("Short leader padded");
139 if ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
142 if (length $content < 40) {
143 $content .= ' ' x (40 - length($content));
144 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
145 message("Short 008 padded");
149 # clean misplaced dollarsigns
150 if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
151 $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
152 message("Dollar sign corrected");
155 # clean up tags with spaces in them
156 $record[$ptr] =~ s/tag=" /tag="00/g;
157 $record[$ptr] =~ s/tag=" /tag="0/g;
158 $record[$ptr] =~ s/tag="-/tag="0/g;
159 $record[$ptr] =~ s/tag="(\d\d) /tag="0$1/g;
161 # stow tag data if we're looking at it
162 if ($record[$ptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
168 # automatable subfield maladies
169 $record[$ptr] =~ s/code=" ">c/code="c">/;
170 $record[$ptr] =~ s/code=" ">\$/code="c"$>/;
174 #-----------------------------------------------------------------------------------
176 #-----------------------------------------------------------------------------------
181 Handles the Term::ReadLine loop
188 return if $conf->{trash}{ $recmeta{tag} };
189 $conf->{editmsg} = $msg;
192 # stow original problem line
193 $conf->{origline} = $record[$ptr];
196 my $line = $term->readline('marc-cleanup>');
197 my @chunks = split /\s+/, $line;
199 # lines with single-character first chunks are commands.
200 # make sure they exist.
201 if (length $chunks[0] == 1) {
202 unless (defined $commands{$chunks[0]}) {
203 print $OUT "No such command '", $chunks[0], "'\n";
208 if (defined $commands{$chunks[0]}) {
209 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
212 $record[$ptr] = "$line\n";
216 # set pointer to top on the way out
222 Constructs record arrays from the incoming MARC file and returns them
229 $l = <MARC> while (defined $l and $l !~ /<record>/);
230 return $l unless defined $l;
235 until ($l =~ m|</record>|)
236 { push @record, $l; $l = <MARC>; }
243 my $trash = $conf->{trash};
245 $conf->{rocount}++ if ($FH eq $NUMARC);
246 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
247 if(defined $recmeta{explanation});
249 # excise unwanted tags
250 if (keys %{$trash} or $conf->{autoscrub}) {
253 for my $line (@record) {
255 $istrash = 0 if $line =~ m|</datafield|;
258 if ($line =~ m/<datafield tag="(.{3})"/) {
260 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
265 push @trimmed, $line;
271 unless ($conf->{nocollapse}) {
272 s/\n// for (@record);
275 # add 903(?) with new record id
277 if ($conf->{'renumber-from'}) {
278 $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
279 '" ind1=" " ind2=" ">',
280 '<subfield code="', $conf->{'renumber-subfield'}, '">',
281 $conf->{'renumber-from'}, '</subfield></datafield>');
282 $renumber .= "\n" if $conf->{nocollapse};
283 push @record, $renumber;
284 $conf->{'renumber-from'}++;
288 print $FH "</record>\n";
291 sub print_fullcontext {
292 print $OUT "\r", ' ' x 72, "\n";
293 print $OUT $conf->{editmsg},"\n";
294 print $OUT "\r Tag:",$recmeta{tag}, " Ind1:'",
295 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
301 my $upper = int($conf->{window} / 2) + 1;
302 my $lower = int($conf->{window} / 2) - 1;
303 my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
304 my $stop = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
306 print $OUT ' |', $record[$_] for ($start .. $ptr - 1);
307 print $OUT '==> |', $record[$ptr];
308 print $OUT ' |', $record[$_] for ($ptr + 1 .. $stop);
315 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
318 #-----------------------------------------------------------------------------------
320 #-----------------------------------------------------------------------------------
323 my ($line_in, @chunks) = @_;
325 my $ofrom = shift @chunks;
326 if ($ofrom =~ /^'/ or !@chunks) {
327 until ($ofrom =~ /'$/)
328 { $ofrom .= join(' ','',shift @chunks) }
329 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
331 my $to = shift @chunks;
333 until ($to =~ /'$/ or !@chunks)
334 { $to .= join(' ','',shift @chunks) }
335 $to =~ s/^'//; $to =~ s/'$//;
339 for my $char (split(//,$ofrom)) {
340 $char = "\\" . $char if ($char =~ /\W/);
341 $from = join('', $from, $char);
344 $conf->{prevline} = $record[$ptr];
345 $record[$ptr] =~ s/$from/$to/;
351 $conf->{prevline} = $record[$ptr];
352 # remove <subfield stuff; extract (probably wrong) subfield code
353 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
354 # and move to front of line
355 $record[$ptr] = join(' ', $1 , $record[$ptr]);
356 # tear off trailing subfield tag from preceeding line
357 $record[$ptr - 1] =~ s|</subfield>\n||;
358 # join current line onto preceeding line
359 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
361 my @a = @record[0 .. $ptr - 1];
362 my @b = @record[$ptr + 1 .. $#record];
364 # move record pointer to previous line
371 unless ($conf->{prevline})
372 { print $OUT "No previously edited line to flip\n"; return }
373 my $temp = $record[$ptr];
374 $record[$ptr] = $conf->{prevline};
375 $conf->{prevline} = $temp;
381 $conf->{killline} = $record[$ptr];
382 my @a = @record[0 .. $ptr - 1];
383 my @b = @record[$ptr + 1 .. $#record];
390 unless ($conf->{killline})
391 { print $OUT "No killed line to yank\n"; return }
392 my @a = @record[0 .. $ptr - 1];
393 my @b = @record[$ptr .. $#record];
394 @record = (@a, $conf->{killline}, @b);
400 print $OUT "\nOrig. edit line :", $conf->{origline};
401 print $OUT "Current flip line:", $conf->{prevline} if $conf->{prevline};
402 print $OUT "Last killed line :", $conf->{killline} if $conf->{killline};
408 my ($line_in, @explanation) = @_;
409 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
410 write_record($EXMARC);
415 $ptr++ unless ($ptr == $#record);;
421 $ptr-- unless ($ptr == 0);
426 sub commit_edit { return 1 }
429 if ($conf->{window} == 15)
430 { print $OUT "Window can't be bigger than 15 lines\n"; return }
431 $conf->{window} += 2;
436 if ($conf->{window} == 5)
437 { print $OUT "Window can't be smaller than 5 lines\n"; return }
438 $conf->{window} -= 2;
444 Type a replacement for the indicated line, or enter a command.
446 DISPLAY COMMANDS | LINE AUTO-EDIT COMMANDS
447 < Expand context window | k Kill current line
448 > Contract context window | y Yank last killed line
449 p Move pointer to prev line | m Merge current line into preceding line
450 n Move pointer to next line | o Insert original line
451 c Print line context | f Flip current line and last edited line
452 d Print current saved lines |
453 -----------------------------+-------------------------------------------
454 s Subtitute; replace ARG1 in current line with ARG2. If either ARG
455 contains spaces, it must be single-quoted
456 t Commit changes and resume automated operations
457 x Dump record to exception file
466 #-----------------------------------------------------------------------------------
468 #-----------------------------------------------------------------------------------
469 # defined a domain-specific language for specifying MARC tags to be dropped from
470 # records during processing. it is line oriented, and is specified as follows:
472 # each line may specify any number of tags to be included, either singly (\d{1,3})
473 # or as a range (\d{1,3}\.\.\d{1,3}
475 # if a single number is given, it must be between '000' and '999', inclusive.
477 # ranges obey the previous rule, and also the first number of the range must be less
478 # than the second number
480 # finally, any single range in a line may be followed by the keyword 'except'. every
481 # number or range after 'except' is excluded from the range specified. all these
482 # numbers must actually be within the range.
484 # specifying a tag twice is an error, to help prevent typos
487 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
488 open TRASH, '<', $conf->{trash}
489 or die "Can't open trash tags file!\n";
491 my $lastwasrange = 0;
492 my %lastrange = ( high => 0, low => 0);
495 my @chunks = split /\s+/;
496 while (my $chunk = shift @chunks) {
499 if ($chunk =~ /^\d{1,3}$/) {
500 trash_add($chunk, $except);
506 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
507 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
509 %lastrange = (low => $low, high => $high)
515 if ($chunk eq 'except') {
516 die "Keyword 'except' can only follow a range (line $.)\n"
517 unless $lastwasrange;
518 die "Keyword 'except' may only occur once per line (line $.)\n"
524 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
528 # remove original id sequence tag from trash hash if we know it
529 trash_add($conf->{'original-tag'}, 1)
530 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
533 sub trash_add_range {
534 my ($chunk, $except, $range) = @_;
535 my ($low,$high) = split /\.\./, $chunk;
536 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
539 die "Exception ranges must be within last addition range (line $.)\n"
540 if ($low < $range->{low} or $high > $range->{high});
542 for my $tag ($low..$high) {
543 trash_add($tag, $except)
549 my ($tag, $except) = @_;
550 my $trash = $conf->{trash};
552 die "Trash values must be valid tags (000-999)\n"
553 unless ($tag >= 0 and $tag <= 999);
556 delete $trash->{$tag};
558 die "Trash tag '$tag' specified twice (line $.)\n"
564 #-----------------------------------------------------------------------
568 Performs boring script initialization. Handles argument parsing,
577 # set mode on existing filehandles
578 binmode(STDIN, ':utf8');
580 my $rc = GetOptions( $c,
585 'renumber-from|rf=i',
588 'renumber-subfield|rt=i',
592 show_help() unless $rc;
593 show_help() if ($c->{help});
596 $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
597 $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
598 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
599 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
602 my @keys = keys %{$c};
603 show_help() unless (@ARGV and @keys);
604 #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
605 # { push @missing, $key unless $c->{$key} }
607 # print "Required option: ", join(', ', @missing), " missing!\n";
614 Usage is: $0 [OPTIONS] <filelist>
616 --output -o Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
617 --exception -x Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)