11 my $term = new Term::ReadLine 'yaz-cleanup';
12 my $OUT = $term->OUT || \*STDOUT;
14 # initialization and setup
17 populate_trash() if ($conf->{trash});
19 my @record = (); # current record storage
20 my %recmeta = (); # metadata about current record
21 my $recptr = 0; # record index pointer
23 my $input = shift || 'incoming.marc.xml';
25 open MARC, '<:utf8', $input;
26 open my $NUMARC, '>:utf8', $conf->{output};
27 print $NUMARC '<?xml version="1.0" encoding="UTF-8"?>',"\n";
28 print $NUMARC '<collection xmlns="http://www.loc.gov/MARC21/slim">',"\n";
30 open my $EXMARC, '>:utf8', $conf->{exception};
32 # this is the dispatch table which drives command selection in
34 my %commands = ( c => \&print_context,
35 C => \&print_linecontext,
48 my @spinner = qw(- / | \\);
51 while ( buildrecord() ) {
52 unless ($conf->{ricount} % 100) {
53 print "\rWorking... ", $spinner[$sidx];
54 $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
57 do_automated_cleanups();
60 until ($recptr == $#record) {
62 if ($record[$recptr] =~ /&/ && $record[$recptr] !~ /&\w+?;/)
63 { edit("Naked ampersand"); $recptr= 0; next }
65 # tags must be numeric
66 if ($record[$recptr] =~ /<datafield tag="(.+?)"/) {
69 edit("Non-numerics in tag");
75 # subfields can't be non-alphanumeric
76 if ($record[$recptr] =~ /<subfield code="(.*?)"/) {
78 if ($match =~ /\P{IsAlnum}/ or $match eq '') {
79 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 ($recptr == $#record) {
100 # catch empty datafield elements
101 if ($record[$recptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
102 if ($record[$recptr + 1] =~ m|</datafield>|) {
103 my @a = @record[0 .. $recptr - 1];
104 my @b = @record[$recptr + 2 .. $#record];
106 message("Empty datafield scrubbed");
111 # and quasi-empty subfields
112 if ($record[$recptr] =~ 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 .. $recptr - 1];
116 my @b = @record[$recptr + 1 .. $#record];
118 message("Empty subfield scrubbed");
127 for $recptr (0 .. $#record) {
129 if ($record[$recptr] =~ m|<leader>(.+?)</leader>|) {
131 if (length $leader < 24) {
132 $leader .= ' ' x (20 - length($leader));
134 $record[$recptr] = "<leader>$leader</leader>\n";
135 message("Short leader padded");
138 if ($record[$recptr] =~ m|<controlfield tag="008">(.+?)</control|) {
141 if (length $content < 40) {
142 $content .= ' ' x (40 - length($content));
143 $record[$recptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
144 message("Short 008 padded");
148 # clean misplaced dollarsigns
149 if ($record[$recptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
150 $record[$recptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
151 message("Dollar sign corrected");
154 # clean up tags with spaces in them
155 $record[$recptr] =~ s/tag=" /tag="00/g;
156 $record[$recptr] =~ s/tag=" /tag="0/g;
157 $record[$recptr] =~ s/tag="-/tag="0/g;
158 $record[$recptr] =~ s/tag="(\d\d) /tag="0$1/g;
160 # stow tag data if we're looking at it
161 if ($record[$recptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
167 # automatable subfield maladies
168 $record[$recptr] =~ s/code=" ">c/code="c">/;
169 $record[$recptr] =~ s/code=" ">\$/code="c"$>/;
173 #-----------------------------------------------------------------------------------
175 #-----------------------------------------------------------------------------------
180 Handles the Term::ReadLine loop
187 return if $conf->{trash}{ $recmeta{tag} };
192 my $line = $term->readline('marc-cleanup>');
193 my @chunks = split /\s+/, $line;
195 if (length $chunks[0] == 1)
196 { next unless (defined $commands{$chunks[0]}) }
198 if (defined $commands{$chunks[0]}) {
199 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
202 $record[$recptr] = "$line\n";
210 Constructs record arrays from the incoming MARC file and returns them
217 $l = <MARC> while (defined $l and $l !~ /<record>/);
218 return $l unless defined $l;
223 until ($l =~ m|</record>|)
224 { push @record, $l; $l = <MARC>; }
231 my $trash = $conf->{trash};
233 $conf->{rocount}++ if ($FH eq $NUMARC);
234 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
235 if(defined $recmeta{explanation});
237 # excise unwanted tags
238 if (keys %{$trash} or $conf->{autoscrub}) {
241 for my $line (@record) {
243 $istrash = 0 if $line =~ m|</datafield|;
246 if ($line =~ m/<datafield tag="(.{3})"/) {
248 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
253 push @trimmed, $line;
259 unless ($conf->{nocollapse}) {
260 s/\n// for (@record);
263 # add 903(?) with new record id
265 if ($conf->{'renumber-from'}) {
266 $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
267 '" ind1=" " ind2=" ">',
268 '<subfield code="', $conf->{'renumber-subfield'}, '">',
269 $conf->{'renumber-from'}, '</subfield></datafield>');
270 $renumber .= "\n" if $conf->{nocollapse};
271 push @record, $renumber;
272 $conf->{'renumber-from'}++;
276 print $FH "</record>\n";
280 print " Tag:",$recmeta{tag}, " Ind1:'",
281 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'\n";
286 sub print_linecontext {
287 my $low = ($recptr - 3 < 0) ? 0 : $recptr - 3;
288 print $OUT ' |', $record[$_] for ($low .. $recptr - 1);
289 print $OUT '==> |', $record[$recptr];
290 print $OUT ' |', $record[$recptr + 1], "\n";
295 my ($msg, $new) = @_;
296 print $OUT "\r", ' ' x 72, "\n" if $new;
297 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
301 #-----------------------------------------------------------------------------------
303 #-----------------------------------------------------------------------------------
306 my ($line_in, @chunks) = @_;
307 my $ofrom = shift @chunks;
308 if ($ofrom =~ /^'/ or !@chunks) {
309 until ($ofrom =~ /'$/)
310 { $ofrom .= join(' ','',shift @chunks) }
311 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
313 my $to = shift @chunks;
315 until ($to =~ /'$/ or !@chunks)
316 { $to .= join(' ','',shift @chunks) }
317 $to =~ s/^'//; $to =~ s/'$//;
321 for my $char (split(//,$ofrom)) {
322 $char = "\\" . $char if ($char =~ /\W/);
323 $from = join('', $from, $char);
325 $record[$recptr] =~ s/$from/$to/;
331 $record[$recptr] =~ s/^\s*<subfield code="(.*?)">//;
332 $record[$recptr] = join(' ', $1 , $record[$recptr]);
333 $record[$recptr - 1] =~ s|<subfield>\n||;
334 $record[$recptr - 1] = join('', $record[$recptr - 1], $record[$recptr]);
340 my @a = @record[0 .. $recptr - 1];
341 my @b = @record[$recptr + 1 .. $#record];
348 my ($line_in, @explanation) = @_;
349 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
350 write_record($EXMARC);
354 sub commit_edit { return 1 }
358 print $OUT "\n$line_in\n";
365 Type a replacement for the indicated line, or enter a command.
367 Commands: c Show record context again ('C' for brief context)
368 k Kill indicated line (remove from record)
369 m Merge indicated line with previous line
371 s Substitute ARG1 for ARG2 in indicated line
372 t Commit changes and resume stream edit
373 x Write this record to the exception file instead of output
382 #-----------------------------------------------------------------------------------
384 #-----------------------------------------------------------------------------------
385 # defined a domain-specific language for specifying MARC tags to be dropped from
386 # records during processing. it is line oriented, and is specified as follows:
388 # each line may specify any number of tags to be included, either singly (\d{1,3})
389 # or as a range (\d{1,3}\.\.\d{1,3}
391 # if a single number is given, it must be between '000' and '999', inclusive.
393 # ranges obey the previous rule, and also the first number of the range must be less
394 # than the second number
396 # finally, any single range in a line may be followed by the keyword 'except'. every
397 # number or range after 'except' is excluded from the range specified. all these
398 # numbers must actually be within the range.
400 # specifying a tag twice is an error, to help prevent typos
403 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
404 open TRASH, '<', $conf->{trash}
405 or die "Can't open trash tags file!\n";
407 my $lastwasrange = 0;
408 my %lastrange = ( high => 0, low => 0);
411 my @chunks = split /\s+/;
412 while (my $chunk = shift @chunks) {
415 if ($chunk =~ /^\d{1,3}$/) {
416 trash_add($chunk, $except);
422 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
423 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
425 %lastrange = (low => $low, high => $high)
431 if ($chunk eq 'except') {
432 die "Keyword 'except' can only follow a range (line $.)\n"
433 unless $lastwasrange;
434 die "Keyword 'except' may only occur once per line (line $.)\n"
440 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
444 # remove original id sequence tag from trash hash if we know it
445 trash_add($conf->{'original-tag'}, 1)
446 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
449 sub trash_add_range {
450 my ($chunk, $except, $range) = @_;
451 my ($low,$high) = split /\.\./, $chunk;
452 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
455 die "Exception ranges must be within last addition range (line $.)\n"
456 if ($low < $range->{low} or $high > $range->{high});
458 for my $tag ($low..$high) {
459 trash_add($tag, $except)
465 my ($tag, $except) = @_;
466 my $trash = $conf->{trash};
468 die "Trash values must be valid tags (000-999)\n"
469 unless ($tag >= 0 and $tag <= 999);
472 delete $trash->{$tag};
474 die "Trash tag '$tag' specified twice (line $.)\n"
480 #-----------------------------------------------------------------------
484 Performs boring script initialization. Handles argument parsing,
493 # set mode on existing filehandles
494 binmode(STDIN, ':utf8');
496 my $rc = GetOptions( $c,
501 'renumber-from|rf=i',
504 'renumber-subfield|rt=i',
508 show_help() unless $rc;
509 show_help() if ($c->{help});
512 $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
513 $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
514 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
515 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
517 my @keys = keys %{$c};
518 show_help() unless (@ARGV and @keys);
519 #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
520 # { push @missing, $key unless $c->{$key} }
522 # print "Required option: ", join(', ', @missing), " missing!\n";
529 Usage is: $0 [OPTIONS] <filelist>
531 --output -o Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
532 --exception -x Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)