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_context,
33 C => \&print_linecontext,
35 O => \&insert_original,
51 my @spinner = qw(- / | \\);
54 while ( buildrecord() ) {
55 unless ($conf->{ricount} % 100) {
56 print "\rWorking... ", $spinner[$sidx];
57 $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
60 do_automated_cleanups();
63 until ($ptr == $#record) {
65 if ($record[$ptr] =~ /&/ && $record[$ptr] !~ /&\w+?;/)
66 { edit("Naked ampersand"); $ptr= 0; next }
68 # tags must be numeric
69 if ($record[$ptr] =~ /<datafield tag="(.+?)"/) {
72 edit("Non-numerics in tag");
77 # subfields can't be non-alphanumeric
78 if ($record[$ptr] =~ /<subfield code="(.*?)"/) {
80 if ($match =~ /\P{IsAlnum}/ or $match eq '') {
81 edit("Junk in subfield code/Null subfield code");
87 write_record($NUMARC);
89 print $NUMARC "</collection>\n";
90 print $OUT "\nDone. \n";
93 #-----------------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------------
97 sub do_automated_cleanups {
99 until ($ptr == $#record) {
100 # catch empty datafield elements
101 if ($record[$ptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
102 if ($record[$ptr + 1] =~ m|</datafield>|) {
103 my @a = @record[0 .. $ptr - 1];
104 my @b = @record[$ptr + 2 .. $#record];
106 message("Empty datafield scrubbed");
111 # and quasi-empty subfields
112 if ($record[$ptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
113 my $code = $1; my $content = $2;
114 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
115 my @a = @record[0 .. $ptr - 1];
116 my @b = @record[$ptr + 1 .. $#record];
118 message("Empty subfield scrubbed");
127 for $ptr (0 .. $#record) {
129 if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
131 if (length $leader < 24) {
132 $leader .= ' ' x (20 - length($leader));
134 $record[$ptr] = "<leader>$leader</leader>\n";
135 message("Short leader padded");
138 if ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
141 if (length $content < 40) {
142 $content .= ' ' x (40 - length($content));
143 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
144 message("Short 008 padded");
148 # clean misplaced dollarsigns
149 if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
150 $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
151 message("Dollar sign corrected");
154 # clean up tags with spaces in them
155 $record[$ptr] =~ s/tag=" /tag="00/g;
156 $record[$ptr] =~ s/tag=" /tag="0/g;
157 $record[$ptr] =~ s/tag="-/tag="0/g;
158 $record[$ptr] =~ s/tag="(\d\d) /tag="0$1/g;
160 # stow tag data if we're looking at it
161 if ($record[$ptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
167 # automatable subfield maladies
168 $record[$ptr] =~ s/code=" ">c/code="c">/;
169 $record[$ptr] =~ s/code=" ">\$/code="c"$>/;
173 #-----------------------------------------------------------------------------------
175 #-----------------------------------------------------------------------------------
180 Handles the Term::ReadLine loop
187 return if $conf->{trash}{ $recmeta{tag} };
191 # stow original problem line
192 $conf->{origline} = $record[$ptr];
195 my $line = $term->readline('marc-cleanup>');
196 my @chunks = split /\s+/, $line;
198 if (length $chunks[0] == 1)
199 { next unless (defined $commands{$chunks[0]}) }
201 if (defined $commands{$chunks[0]}) {
202 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
205 $record[$ptr] = "$line\n";
214 Constructs record arrays from the incoming MARC file and returns them
221 $l = <MARC> while (defined $l and $l !~ /<record>/);
222 return $l unless defined $l;
227 until ($l =~ m|</record>|)
228 { push @record, $l; $l = <MARC>; }
235 my $trash = $conf->{trash};
237 $conf->{rocount}++ if ($FH eq $NUMARC);
238 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
239 if(defined $recmeta{explanation});
241 # excise unwanted tags
242 if (keys %{$trash} or $conf->{autoscrub}) {
245 for my $line (@record) {
247 $istrash = 0 if $line =~ m|</datafield|;
250 if ($line =~ m/<datafield tag="(.{3})"/) {
252 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
257 push @trimmed, $line;
263 unless ($conf->{nocollapse}) {
264 s/\n// for (@record);
267 # add 903(?) with new record id
269 if ($conf->{'renumber-from'}) {
270 $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
271 '" ind1=" " ind2=" ">',
272 '<subfield code="', $conf->{'renumber-subfield'}, '">',
273 $conf->{'renumber-from'}, '</subfield></datafield>');
274 $renumber .= "\n" if $conf->{nocollapse};
275 push @record, $renumber;
276 $conf->{'renumber-from'}++;
280 print $FH "</record>\n";
284 print " Tag:",$recmeta{tag}, " Ind1:'",
285 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'\n";
290 sub print_linecontext {
291 my $low = ($ptr - 3 < 0) ? 0 : $ptr - 3;
292 print $OUT ' |', $record[$_] for ($low .. $ptr - 1);
293 print $OUT '==> |', $record[$ptr];
294 print $OUT ' |', $record[$ptr + 1], "\n" unless ($ptr == $#record);
299 my ($msg, $new) = @_;
300 print $OUT "\r", ' ' x 72, "\n" if $new;
301 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
305 #-----------------------------------------------------------------------------------
307 #-----------------------------------------------------------------------------------
310 my ($line_in, @chunks) = @_;
312 my $ofrom = shift @chunks;
313 if ($ofrom =~ /^'/ or !@chunks) {
314 until ($ofrom =~ /'$/)
315 { $ofrom .= join(' ','',shift @chunks) }
316 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
318 my $to = shift @chunks;
320 until ($to =~ /'$/ or !@chunks)
321 { $to .= join(' ','',shift @chunks) }
322 $to =~ s/^'//; $to =~ s/'$//;
326 for my $char (split(//,$ofrom)) {
327 $char = "\\" . $char if ($char =~ /\W/);
328 $from = join('', $from, $char);
331 $conf->{prevline} = $record[$ptr];
332 $record[$ptr] =~ s/$from/$to/;
338 $conf->{prevline} = $record[$ptr];
339 # remove <subfield stuff; extract (probably wrong) subfield code
340 $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
341 # and move to front of line
342 $record[$ptr] = join(' ', $1 , $record[$ptr]);
343 # tear off trailing subfield tag from preceeding line
344 $record[$ptr - 1] =~ s|</subfield>\n||;
345 # join current line onto preceeding line
346 $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
348 my @a = @record[0 .. $ptr - 1];
349 my @b = @record[$ptr + 1 .. $#record];
351 # move record pointer to previous line
358 my $temp = $record[$ptr];
359 $record[$ptr] = $conf->{prevline};
360 $conf->{prevline} = $temp;
366 $conf->{prevline} = $record[$ptr];
367 my @a = @record[0 .. $ptr - 1];
368 my @b = @record[$ptr + 1 .. $#record];
375 my @a = @record[0 .. $ptr - 1];
376 my @b = @record[$ptr .. $#record];
377 @record = (@a, $conf->{prevline}, @b);
384 print $OUT "\n", $conf->{origline}, "\n";
389 my ($line_in, @explanation) = @_;
390 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
391 write_record($EXMARC);
396 $ptr++ unless ($ptr == $#record);;
402 $ptr-- unless ($ptr == 0);
407 sub commit_edit { return 1 }
412 Type a replacement for the indicated line, or enter a command.
414 Commands: c Show record context again ('C' for brief context)
415 k Kill indicated line (remove from record)
416 m Merge indicated line with previous line
418 s Substitute ARG1 for ARG2 in indicated line
419 t Commit changes and resume stream edit
420 x Write this record to the exception file instead of output
429 #-----------------------------------------------------------------------------------
431 #-----------------------------------------------------------------------------------
432 # defined a domain-specific language for specifying MARC tags to be dropped from
433 # records during processing. it is line oriented, and is specified as follows:
435 # each line may specify any number of tags to be included, either singly (\d{1,3})
436 # or as a range (\d{1,3}\.\.\d{1,3}
438 # if a single number is given, it must be between '000' and '999', inclusive.
440 # ranges obey the previous rule, and also the first number of the range must be less
441 # than the second number
443 # finally, any single range in a line may be followed by the keyword 'except'. every
444 # number or range after 'except' is excluded from the range specified. all these
445 # numbers must actually be within the range.
447 # specifying a tag twice is an error, to help prevent typos
450 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
451 open TRASH, '<', $conf->{trash}
452 or die "Can't open trash tags file!\n";
454 my $lastwasrange = 0;
455 my %lastrange = ( high => 0, low => 0);
458 my @chunks = split /\s+/;
459 while (my $chunk = shift @chunks) {
462 if ($chunk =~ /^\d{1,3}$/) {
463 trash_add($chunk, $except);
469 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
470 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
472 %lastrange = (low => $low, high => $high)
478 if ($chunk eq 'except') {
479 die "Keyword 'except' can only follow a range (line $.)\n"
480 unless $lastwasrange;
481 die "Keyword 'except' may only occur once per line (line $.)\n"
487 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
491 # remove original id sequence tag from trash hash if we know it
492 trash_add($conf->{'original-tag'}, 1)
493 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
496 sub trash_add_range {
497 my ($chunk, $except, $range) = @_;
498 my ($low,$high) = split /\.\./, $chunk;
499 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
502 die "Exception ranges must be within last addition range (line $.)\n"
503 if ($low < $range->{low} or $high > $range->{high});
505 for my $tag ($low..$high) {
506 trash_add($tag, $except)
512 my ($tag, $except) = @_;
513 my $trash = $conf->{trash};
515 die "Trash values must be valid tags (000-999)\n"
516 unless ($tag >= 0 and $tag <= 999);
519 delete $trash->{$tag};
521 die "Trash tag '$tag' specified twice (line $.)\n"
527 #-----------------------------------------------------------------------
531 Performs boring script initialization. Handles argument parsing,
540 # set mode on existing filehandles
541 binmode(STDIN, ':utf8');
543 my $rc = GetOptions( $c,
548 'renumber-from|rf=i',
551 'renumber-subfield|rt=i',
555 show_help() unless $rc;
556 show_help() if ($c->{help});
559 $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
560 $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
561 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
562 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
564 my @keys = keys %{$c};
565 show_help() unless (@ARGV and @keys);
566 #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
567 # { push @missing, $key unless $c->{$key} }
569 # print "Required option: ", join(', ', @missing), " missing!\n";
576 Usage is: $0 [OPTIONS] <filelist>
578 --output -o Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
579 --exception -x Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)