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 (-e '.trashtags');
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">/;
115 # and stow line back in record
119 if ($line =~ /&/ && $line !~ /&\w+?;/)
120 { edit("Naked ampersand", $line); next }
122 # tags must be numeric
123 if ($line =~ /<datafield tag="(.+?)"/) {
125 if ($match =~ /\D/) {
126 edit("Non-numerics in tag", $line);
131 # subfields can't be non-alphanumeric
132 if ($line =~ /<subfield code="(.*?)"/) {
134 if ($match =~ /\P{IsAlnum}/) {
135 edit("Junk in subfield code", $line);
141 print $NUMARC "</collection>\n";
142 print $EXMARC "</collection>\n";
143 print $OUT "\nDone. \n";
147 Handles the Term::ReadLine loop
152 my ($msg, $line_in) = @_;
153 return if $trash{$recmeta{tag}};
158 my $line = $term->readline('marc-cleanup>');
159 my @chunks = split /\s+/, $line;
161 if (length $chunks[0] == 1)
162 { next unless (defined $commands{$chunks[0]}) }
164 if (defined $commands{$chunks[0]}) {
165 my $term = $commands{$chunks[0]}->($line_in, @chunks[1..$#chunks]);
168 if ($context[3] eq " [LINE KILLED]\n") {
169 push @record, "$line\n"
171 $record[-1] = "$line\n";
173 $context[3] = "$line\n";
181 Reads from the incoming MARC file; returns lines into the driver
182 loop. Batches records for output, and maintains the context listing.
190 if ($l =~ /<record>/) {
194 } elsif ($l =~ m|</record>|) {
195 write_record($NUMARC) if $reccount;
205 $oreccount++ if ($FH eq $NUMARC);
206 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
207 if(defined $recmeta{explanation});
209 # excise unwanted tags
210 if (keys %trash or $conf->{autoscrub}) {
213 for my $line (@record) {
215 $istrash = 0 if $line =~ m|</datafield|;
218 if ($line =~ m/<datafield tag="(.{3})"/) {
220 if ($trash{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
225 push @trimmed, $line;
231 unless ($conf->{nocollapse}) {
232 s/\n// for (@record);
235 # add 903(?) with new record id
237 if ($conf->{'renumber-from'}) {
238 $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
239 '" ind1=" " ind2=" ">',
240 '<subfield code="', $conf->{'renumber-subfield'}, '">',
241 $conf->{'renumber-from'}, '</subfield></datafield>');
242 $renumber .= "\n" if $conf->{nocollapse};
243 push @record, $renumber;
244 $conf->{'renumber-from'}++;
248 print $FH "</record>\n";
251 sub update_linecontext {
253 push @context, $line2;
254 shift @context if (@context > 5);
259 print $OUT "\r$msg at record $reccount/",$oreccount + 1,"\n";
263 #-----------------------------------------------------------------------------------
265 #-----------------------------------------------------------------------------------
268 my ($line_in, @chunks) = @_;
269 my $ofrom = shift @chunks;
270 if ($ofrom =~ /^'/ or !@chunks) {
271 until ($ofrom =~ /'$/)
272 { $ofrom .= join(' ','',shift @chunks) }
273 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
275 my $to = shift @chunks;
277 until ($to =~ /'$/ or !@chunks)
278 { $to .= join(' ','',shift @chunks) }
279 $to =~ s/^'//; $to =~ s/'$//;
283 for my $char (split(//,$ofrom)) {
284 $char = "\\" . $char if ($char =~ /\W/);
285 $from = join('', $from, $char);
287 $record[-1] =~ s/$from/$to/;
288 $context[3] = $record[-1];
294 my $last = pop @record;
296 $record[-1] =~ s/\n//;
297 $record[-1] = join('', $record[-1], $last);
299 push @temp, @context[0..1];
300 $temp[3] = $record[-1];
301 $temp[4] = $context[4];
309 $context[3] = " [LINE KILLED]\n";
315 my ($line_in, @explanation) = @_;
316 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
317 my $line = <MARC>; $count++;
318 update_linecontext();
319 until ($line =~ m|</record>|) {
321 $line = <MARC>; $count++;
322 update_linecontext();
325 write_record($EXMARC);
329 sub commit_edit { return 1 }
332 print "\n Tag:",$recmeta{tag}, " Ind1:'",
333 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
338 sub print_linecontext {
339 print $OUT "\n", join(' |','',@context[0..2]);
340 print $OUT '==> |', $context[3];
341 print $OUT ' |', $context[4],"\n";
347 print $OUT "\n$line_in\n";
354 Type a replacement for the indicated line, or enter a command.
356 Commands: c Show record context ('C' for brief context)
357 k Kill indicated line (remove from record)
358 m Merge indicated line with previous line
360 s Substitute ARG1 for ARG2 in indicated line
361 t Commit changes and resume stream edit
362 x Write this record to the exception file instead of output
371 #-----------------------------------------------------------------------------------
373 #-----------------------------------------------------------------------------------
374 # defined a domain-specific language for specifying MARC tags to be dropped from
375 # records during processing. it is line oriented, and is specified as follows:
377 # each line may specify any number of tags to be included, either singly (\d{1,3})
378 # or as a range (\d{1,3}\.\.\d{1,3}
380 # if a single number is given, it must be between '000' and '999', inclusive.
382 # ranges obey the previous rule, and also the first number of the range must be less
383 # than the second number
385 # finally, any single range in a line may be followed by the keyword 'except'. every
386 # number or range after 'except' is excluded from the range specified. all these
387 # numbers must actually be within the range.
389 # specifying a tag twice is an error, to help prevent typos
392 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT...\n";
393 open TRASH, '<', '.trashtags';
395 my $lastwasrange = 0;
396 my %lastrange = ( high => 0, low => 0);
399 my @chunks = split /\s+/;
400 while (my $chunk = shift @chunks) {
403 if ($chunk =~ /^\d{1,3}$/) {
404 trash_add($chunk, $except);
410 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
411 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
413 %lastrange = (low => $low, high => $high)
419 if ($chunk eq 'except') {
420 die "Keyword 'except' can only follow a range (line $.)\n"
421 unless $lastwasrange;
422 die "Keyword 'except' may only occur once per line (line $.)\n"
428 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
432 # remove original id sequence tag from trash hash if we know it
433 trash_add($conf->{'original-tag'}, 1)
434 if ($conf->{'original-tag'} and $trash{$conf->{'original-tag'}});
437 sub trash_add_range {
438 my ($chunk, $except, $range) = @_;
439 my ($low,$high) = split /\.\./, $chunk;
440 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
443 die "Exception ranges must be within last addition range (line $.)\n"
444 if ($low < $range->{low} or $high > $range->{high});
446 for my $tag ($low..$high) {
447 trash_add($tag, $except)
453 my ($tag, $except) = @_;
454 die "Trash values must be valid tags (000-999)\n"
455 unless ($tag >= 0 and $tag <= 999);
459 die "Trash tag '$tag' specified twice (line $.)\n"
465 #-----------------------------------------------------------------------
469 Performs boring script initialization. Handles argument parsing,
478 # set mode on existing filehandles
479 binmode(STDIN, ':utf8');
481 my $rc = GetOptions( $c,
486 'renumber-from|rf=i',
489 'renumber-subfield|rt=i',
492 show_help() unless $rc;
493 show_help() if ($c->{help});
496 $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
497 $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
498 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
499 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
501 my @keys = keys %{$c};
502 show_help() unless (@ARGV and @keys);
503 #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
504 # { push @missing, $key unless $c->{$key} }
506 # print "Required option: ", join(', ', @missing), " missing!\n";
513 Usage is: $0 [OPTIONS] <filelist>
515 --output -o Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
516 --exception -x Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)