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,
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 ($recptr == $#record) {
65 if ($record[$recptr] =~ /&/ && $record[$recptr] !~ /&\w+?;/)
66 { edit("Naked ampersand"); $recptr= 0; next }
68 # tags must be numeric
69 if ($record[$recptr] =~ /<datafield tag="(.+?)"/) {
72 edit("Non-numerics in tag");
78 # subfields can't be non-alphanumeric
79 if ($record[$recptr] =~ /<subfield code="(.*?)"/) {
81 if ($match =~ /\P{IsAlnum}/ or $match eq '') {
82 edit("Junk in subfield code/Null subfield code");
89 write_record($NUMARC);
91 print $NUMARC "</collection>\n";
92 print $OUT "\nDone. \n";
95 #-----------------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------------
99 sub do_automated_cleanups {
101 until ($recptr == $#record) {
102 # catch empty datafield elements
103 if ($record[$recptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
104 if ($record[$recptr + 1] =~ m|</datafield>|) {
105 my @a = @record[0 .. $recptr - 1];
106 my @b = @record[$recptr + 2 .. $#record];
108 message("Empty datafield scrubbed");
113 # and quasi-empty subfields
114 if ($record[$recptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
115 my $code = $1; my $content = $2;
116 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
117 my @a = @record[0 .. $recptr - 1];
118 my @b = @record[$recptr + 1 .. $#record];
120 message("Empty subfield scrubbed");
129 for $recptr (0 .. $#record) {
131 if ($record[$recptr] =~ m|<leader>(.+?)</leader>|) {
133 if (length $leader < 24) {
134 $leader .= ' ' x (20 - length($leader));
136 $record[$recptr] = "<leader>$leader</leader>\n";
137 message("Short leader padded");
140 if ($record[$recptr] =~ m|<controlfield tag="008">(.+?)</control|) {
143 if (length $content < 40) {
144 $content .= ' ' x (40 - length($content));
145 $record[$recptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
146 message("Short 008 padded");
150 # clean misplaced dollarsigns
151 if ($record[$recptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
152 $record[$recptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
153 message("Dollar sign corrected");
156 # clean up tags with spaces in them
157 $record[$recptr] =~ s/tag=" /tag="00/g;
158 $record[$recptr] =~ s/tag=" /tag="0/g;
159 $record[$recptr] =~ s/tag="-/tag="0/g;
160 $record[$recptr] =~ s/tag="(\d\d) /tag="0$1/g;
162 # stow tag data if we're looking at it
163 if ($record[$recptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
169 # automatable subfield maladies
170 $record[$recptr] =~ s/code=" ">c/code="c">/;
171 $record[$recptr] =~ s/code=" ">\$/code="c"$>/;
175 #-----------------------------------------------------------------------------------
177 #-----------------------------------------------------------------------------------
182 Handles the Term::ReadLine loop
189 return if $conf->{trash}{ $recmeta{tag} };
193 # stow original problem line
194 $conf->{origline} = $record[$recptr];
197 my $line = $term->readline('marc-cleanup>');
198 my @chunks = split /\s+/, $line;
200 if (length $chunks[0] == 1)
201 { next unless (defined $commands{$chunks[0]}) }
203 if (defined $commands{$chunks[0]}) {
204 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
207 $record[$recptr] = "$line\n";
215 Constructs record arrays from the incoming MARC file and returns them
222 $l = <MARC> while (defined $l and $l !~ /<record>/);
223 return $l unless defined $l;
228 until ($l =~ m|</record>|)
229 { push @record, $l; $l = <MARC>; }
236 my $trash = $conf->{trash};
238 $conf->{rocount}++ if ($FH eq $NUMARC);
239 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
240 if(defined $recmeta{explanation});
242 # excise unwanted tags
243 if (keys %{$trash} or $conf->{autoscrub}) {
246 for my $line (@record) {
248 $istrash = 0 if $line =~ m|</datafield|;
251 if ($line =~ m/<datafield tag="(.{3})"/) {
253 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
258 push @trimmed, $line;
264 unless ($conf->{nocollapse}) {
265 s/\n// for (@record);
268 # add 903(?) with new record id
270 if ($conf->{'renumber-from'}) {
271 $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
272 '" ind1=" " ind2=" ">',
273 '<subfield code="', $conf->{'renumber-subfield'}, '">',
274 $conf->{'renumber-from'}, '</subfield></datafield>');
275 $renumber .= "\n" if $conf->{nocollapse};
276 push @record, $renumber;
277 $conf->{'renumber-from'}++;
281 print $FH "</record>\n";
285 print " Tag:",$recmeta{tag}, " Ind1:'",
286 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'\n";
291 sub print_linecontext {
292 my $low = ($recptr - 3 < 0) ? 0 : $recptr - 3;
293 print $OUT ' |', $record[$_] for ($low .. $recptr - 1);
294 print $OUT '==> |', $record[$recptr];
295 print $OUT ' |', $record[$recptr + 1], "\n";
300 my ($msg, $new) = @_;
301 print $OUT "\r", ' ' x 72, "\n" if $new;
302 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
306 #-----------------------------------------------------------------------------------
308 #-----------------------------------------------------------------------------------
311 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);
330 $record[$recptr] =~ s/$from/$to/;
336 # remove <subfield stuff; extract (probably wrong) subfield code
337 $record[$recptr] =~ s/^\s*<subfield code="(.*?)">//;
338 # and move to front of line
339 $record[$recptr] = join(' ', $1 , $record[$recptr]);
340 # tear off trailing subfield tag from preceeding line
341 $record[$recptr - 1] =~ s|</subfield>\n||;
342 # join current line onto preceeding line
343 $record[$recptr - 1] = join('', $record[$recptr - 1], $record[$recptr]);
345 my @a = @record[0 .. $recptr - 1];
346 my @b = @record[$recptr + 1 .. $#record];
348 # move record pointer to previous line
355 my @a = @record[0 .. $recptr - 1];
356 my @b = @record[$recptr + 1 .. $#record];
363 my ($line_in, @explanation) = @_;
364 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
365 write_record($EXMARC);
383 print $OUT "\n", $conf->{origline}, "\n";
387 sub commit_edit { return 1 }
392 Type a replacement for the indicated line, or enter a command.
394 Commands: c Show record context again ('C' for brief context)
395 k Kill indicated line (remove from record)
396 m Merge indicated line with previous line
398 s Substitute ARG1 for ARG2 in indicated line
399 t Commit changes and resume stream edit
400 x Write this record to the exception file instead of output
409 #-----------------------------------------------------------------------------------
411 #-----------------------------------------------------------------------------------
412 # defined a domain-specific language for specifying MARC tags to be dropped from
413 # records during processing. it is line oriented, and is specified as follows:
415 # each line may specify any number of tags to be included, either singly (\d{1,3})
416 # or as a range (\d{1,3}\.\.\d{1,3}
418 # if a single number is given, it must be between '000' and '999', inclusive.
420 # ranges obey the previous rule, and also the first number of the range must be less
421 # than the second number
423 # finally, any single range in a line may be followed by the keyword 'except'. every
424 # number or range after 'except' is excluded from the range specified. all these
425 # numbers must actually be within the range.
427 # specifying a tag twice is an error, to help prevent typos
430 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
431 open TRASH, '<', $conf->{trash}
432 or die "Can't open trash tags file!\n";
434 my $lastwasrange = 0;
435 my %lastrange = ( high => 0, low => 0);
438 my @chunks = split /\s+/;
439 while (my $chunk = shift @chunks) {
442 if ($chunk =~ /^\d{1,3}$/) {
443 trash_add($chunk, $except);
449 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
450 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
452 %lastrange = (low => $low, high => $high)
458 if ($chunk eq 'except') {
459 die "Keyword 'except' can only follow a range (line $.)\n"
460 unless $lastwasrange;
461 die "Keyword 'except' may only occur once per line (line $.)\n"
467 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
471 # remove original id sequence tag from trash hash if we know it
472 trash_add($conf->{'original-tag'}, 1)
473 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
476 sub trash_add_range {
477 my ($chunk, $except, $range) = @_;
478 my ($low,$high) = split /\.\./, $chunk;
479 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
482 die "Exception ranges must be within last addition range (line $.)\n"
483 if ($low < $range->{low} or $high > $range->{high});
485 for my $tag ($low..$high) {
486 trash_add($tag, $except)
492 my ($tag, $except) = @_;
493 my $trash = $conf->{trash};
495 die "Trash values must be valid tags (000-999)\n"
496 unless ($tag >= 0 and $tag <= 999);
499 delete $trash->{$tag};
501 die "Trash tag '$tag' specified twice (line $.)\n"
507 #-----------------------------------------------------------------------
511 Performs boring script initialization. Handles argument parsing,
520 # set mode on existing filehandles
521 binmode(STDIN, ':utf8');
523 my $rc = GetOptions( $c,
528 'renumber-from|rf=i',
531 'renumber-subfield|rt=i',
535 show_help() unless $rc;
536 show_help() if ($c->{help});
539 $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
540 $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
541 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
542 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
544 my @keys = keys %{$c};
545 show_help() unless (@ARGV and @keys);
546 #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
547 # { push @missing, $key unless $c->{$key} }
549 # print "Required option: ", join(', ', @missing), " missing!\n";
556 Usage is: $0 [OPTIONS] <filelist>
558 --output -o Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
559 --exception -x Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)