11 my $term = new Term::ReadLine 'yaz-cleanup';
12 my $OUT = $term->OUT || \*STDOUT;
20 my %trash = (); # hash for tags to be dumped
22 # initialization and setup
25 # read in trash tags file if it exists
26 populate_trash() if ($conf->{trash});
28 my @record = (); # current record storage
29 my %recmeta = (); # metadata about current record
30 my @context= (); # last 5 lines of file
32 my $input = shift || 'incoming.marc.xml';
34 open MARC, '<:utf8', $input;
35 open my $NUMARC, '>:utf8', $conf->{output};
36 print $NUMARC '<?xml version="1.0" encoding="UTF-8"?>',"\n";
37 print $NUMARC '<collection xmlns="http://www.loc.gov/MARC21/slim">',"\n";
39 open my $EXMARC, '>:utf8', $conf->{exception};
40 print $EXMARC '<?xml version="1.0" encoding="UTF-8"?>',"\n";
41 print $EXMARC '<collection xmlns="http://www.loc.gov/MARC21/slim">',"\n";
42 open MARC2, '<', $input;
45 # this is the dispatch table which drives command selection in
47 my %commands = ( c => \&print_context,
48 C => \&print_linecontext,
61 my @spinner = qw(- / | \\);
64 while (my $line = getline()) {
65 unless ($count % 2000) {
66 print "\rWorking... ", $spinner[$sidx];
67 $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
71 next if ($line =~ m|</record>|);
73 # catch empty datafield elements
74 if ($line =~ m|</datafield>|) {
75 if ($record[-2] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
76 pop @record; pop @record;
77 message("Empty datafield scrubbed");
83 if ($line =~ m|<leader>(.+?)</leader>|) {
85 if (length $leader < 24) {
86 $leader .= ' ' x (20 - length($leader));
88 $line = "<leader>$leader</leader>\n";
89 message("Short leader padded");
93 # clean misplaced dollarsigns
94 if ($line =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
95 $line =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
96 message("Dollar sign corrected");
99 # clean up tags with spaces in them
100 $line =~ s/tag=" /tag="00/g;
101 $line =~ s/tag=" /tag="0/g;
102 $line =~ s/tag="-/tag="0/g;
103 $line =~ s/tag="(\d\d) /tag="0$1/g;
105 # stow tag data if we're looking at it
106 if ($line =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
112 # automatable subfield maladies
113 $line =~ s/code=" ">c/code="c">/;
114 $line =~ s/code=" ">\$/code="c"$>/;
116 # and stow line back in record
120 if ($line =~ /&/ && $line !~ /&\w+?;/)
121 { edit("Naked ampersand", $line); next }
123 # tags must be numeric
124 if ($line =~ /<datafield tag="(.+?)"/) {
126 if ($match =~ /\D/) {
127 edit("Non-numerics in tag", $line);
132 # subfields can't be non-alphanumeric
133 if ($line =~ /<subfield code="(.*?)"/) {
135 if ($match =~ /\P{IsAlnum}/ or $match eq '') {
136 edit("Junk in subfield code/Null subfield code", $line);
142 print $NUMARC "</collection>\n";
143 print $EXMARC "</collection>\n";
144 print $OUT "\nDone. \n";
148 Handles the Term::ReadLine loop
153 my ($msg, $line_in) = @_;
154 return if $trash{$recmeta{tag}};
159 my $line = $term->readline('marc-cleanup>');
160 my @chunks = split /\s+/, $line;
162 if (length $chunks[0] == 1)
163 { next unless (defined $commands{$chunks[0]}) }
165 if (defined $commands{$chunks[0]}) {
166 my $term = $commands{$chunks[0]}->($line_in, @chunks[1..$#chunks]);
169 if ($context[3] eq " [LINE KILLED]\n") {
170 push @record, "$line\n"
172 $record[-1] = "$line\n";
174 $context[3] = "$line\n";
182 Reads from the incoming MARC file; returns lines into the driver
183 loop. Batches records for output, and maintains the context listing.
191 if ($l =~ /<record>/) {
195 } elsif ($l =~ m|</record>|) {
196 write_record($NUMARC) if $reccount;
206 $oreccount++ if ($FH eq $NUMARC);
207 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
208 if(defined $recmeta{explanation});
210 # excise unwanted tags
211 if (keys %trash or $conf->{autoscrub}) {
214 for my $line (@record) {
216 $istrash = 0 if $line =~ m|</datafield|;
219 if ($line =~ m/<datafield tag="(.{3})"/) {
221 if ($trash{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
226 push @trimmed, $line;
232 unless ($conf->{nocollapse}) {
233 s/\n// for (@record);
236 # add 903(?) with new record id
238 if ($conf->{'renumber-from'}) {
239 $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
240 '" ind1=" " ind2=" ">',
241 '<subfield code="', $conf->{'renumber-subfield'}, '">',
242 $conf->{'renumber-from'}, '</subfield></datafield>');
243 $renumber .= "\n" if $conf->{nocollapse};
244 push @record, $renumber;
245 $conf->{'renumber-from'}++;
249 print $FH "</record>\n";
252 sub update_linecontext {
254 push @context, $line2;
255 shift @context if (@context > 5);
260 print $OUT "\r$msg at record $reccount/",$oreccount + 1,"\n";
264 #-----------------------------------------------------------------------------------
266 #-----------------------------------------------------------------------------------
269 my ($line_in, @chunks) = @_;
270 my $ofrom = shift @chunks;
271 if ($ofrom =~ /^'/ or !@chunks) {
272 until ($ofrom =~ /'$/)
273 { $ofrom .= join(' ','',shift @chunks) }
274 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
276 my $to = shift @chunks;
278 until ($to =~ /'$/ or !@chunks)
279 { $to .= join(' ','',shift @chunks) }
280 $to =~ s/^'//; $to =~ s/'$//;
284 for my $char (split(//,$ofrom)) {
285 $char = "\\" . $char if ($char =~ /\W/);
286 $from = join('', $from, $char);
288 $record[-1] =~ s/$from/$to/;
289 $context[3] = $record[-1];
295 my $last = pop @record;
297 $record[-1] =~ s/\n//;
298 $record[-1] = join('', $record[-1], $last);
300 push @temp, @context[0..1];
301 $temp[3] = $record[-1];
302 $temp[4] = $context[4];
310 $context[3] = " [LINE KILLED]\n";
316 my ($line_in, @explanation) = @_;
317 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
318 my $line = <MARC>; $count++;
319 update_linecontext();
320 until ($line =~ m|</record>|) {
322 $line = <MARC>; $count++;
323 update_linecontext();
326 write_record($EXMARC);
330 sub commit_edit { return 1 }
333 print "\n Tag:",$recmeta{tag}, " Ind1:'",
334 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
339 sub print_linecontext {
340 print $OUT "\n", join(' |','',@context[0..2]);
341 print $OUT '==> |', $context[3];
342 print $OUT ' |', $context[4],"\n";
348 print $OUT "\n$line_in\n";
355 Type a replacement for the indicated line, or enter a command.
357 Commands: c Show record context ('C' for brief context)
358 k Kill indicated line (remove from record)
359 m Merge indicated line with previous line
361 s Substitute ARG1 for ARG2 in indicated line
362 t Commit changes and resume stream edit
363 x Write this record to the exception file instead of output
372 #-----------------------------------------------------------------------------------
374 #-----------------------------------------------------------------------------------
375 # defined a domain-specific language for specifying MARC tags to be dropped from
376 # records during processing. it is line oriented, and is specified as follows:
378 # each line may specify any number of tags to be included, either singly (\d{1,3})
379 # or as a range (\d{1,3}\.\.\d{1,3}
381 # if a single number is given, it must be between '000' and '999', inclusive.
383 # ranges obey the previous rule, and also the first number of the range must be less
384 # than the second number
386 # finally, any single range in a line may be followed by the keyword 'except'. every
387 # number or range after 'except' is excluded from the range specified. all these
388 # numbers must actually be within the range.
390 # specifying a tag twice is an error, to help prevent typos
393 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
394 open TRASH, '<', $conf->{trash}
395 or die "Can't open trash tags file!\n";
397 my $lastwasrange = 0;
398 my %lastrange = ( high => 0, low => 0);
401 my @chunks = split /\s+/;
402 while (my $chunk = shift @chunks) {
405 if ($chunk =~ /^\d{1,3}$/) {
406 trash_add($chunk, $except);
412 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
413 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
415 %lastrange = (low => $low, high => $high)
421 if ($chunk eq 'except') {
422 die "Keyword 'except' can only follow a range (line $.)\n"
423 unless $lastwasrange;
424 die "Keyword 'except' may only occur once per line (line $.)\n"
430 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
434 # remove original id sequence tag from trash hash if we know it
435 trash_add($conf->{'original-tag'}, 1)
436 if ($conf->{'original-tag'} and $trash{$conf->{'original-tag'}});
439 sub trash_add_range {
440 my ($chunk, $except, $range) = @_;
441 my ($low,$high) = split /\.\./, $chunk;
442 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
445 die "Exception ranges must be within last addition range (line $.)\n"
446 if ($low < $range->{low} or $high > $range->{high});
448 for my $tag ($low..$high) {
449 trash_add($tag, $except)
455 my ($tag, $except) = @_;
456 die "Trash values must be valid tags (000-999)\n"
457 unless ($tag >= 0 and $tag <= 999);
461 die "Trash tag '$tag' specified twice (line $.)\n"
467 #-----------------------------------------------------------------------
471 Performs boring script initialization. Handles argument parsing,
480 # set mode on existing filehandles
481 binmode(STDIN, ':utf8');
483 my $rc = GetOptions( $c,
488 'renumber-from|rf=i',
491 'renumber-subfield|rt=i',
495 show_help() unless $rc;
496 show_help() if ($c->{help});
499 $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
500 $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
501 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
502 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
504 my @keys = keys %{$c};
505 show_help() unless (@ARGV and @keys);
506 #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
507 # { push @missing, $key unless $c->{$key} }
509 # print "Required option: ", join(', ', @missing), " missing!\n";
516 Usage is: $0 [OPTIONS] <filelist>
518 --output -o Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
519 --exception -x Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)