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,
50 my @spinner = qw(- / | \\);
53 while ( buildrecord() ) {
54 unless ($conf->{ricount} % 100) {
55 print "\rWorking... ", $spinner[$sidx];
56 $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
59 do_automated_cleanups();
62 until ($recptr == $#record) {
64 if ($record[$recptr] =~ /&/ && $record[$recptr] !~ /&\w+?;/)
65 { edit("Naked ampersand"); $recptr= 0; next }
67 # tags must be numeric
68 if ($record[$recptr] =~ /<datafield tag="(.+?)"/) {
71 edit("Non-numerics in tag");
77 # subfields can't be non-alphanumeric
78 if ($record[$recptr] =~ /<subfield code="(.*?)"/) {
80 if ($match =~ /\P{IsAlnum}/ or $match eq '') {
81 edit("Junk in subfield code/Null subfield code");
88 write_record($NUMARC);
90 print $NUMARC "</collection>\n";
91 print $OUT "\nDone. \n";
94 #-----------------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------------
98 sub do_automated_cleanups {
100 until ($recptr == $#record) {
101 # catch empty datafield elements
102 if ($record[$recptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
103 if ($record[$recptr + 1] =~ m|</datafield>|) {
104 my @a = @record[0 .. $recptr - 1];
105 my @b = @record[$recptr + 2 .. $#record];
107 message("Empty datafield scrubbed");
112 # and quasi-empty subfields
113 if ($record[$recptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
114 my $code = $1; my $content = $2;
115 if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
116 my @a = @record[0 .. $recptr - 1];
117 my @b = @record[$recptr + 1 .. $#record];
119 message("Empty subfield scrubbed");
128 for $recptr (0 .. $#record) {
130 if ($record[$recptr] =~ m|<leader>(.+?)</leader>|) {
132 if (length $leader < 24) {
133 $leader .= ' ' x (20 - length($leader));
135 $record[$recptr] = "<leader>$leader</leader>\n";
136 message("Short leader padded");
139 if ($record[$recptr] =~ m|<controlfield tag="008">(.+?)</control|) {
142 if (length $content < 40) {
143 $content .= ' ' x (40 - length($content));
144 $record[$recptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
145 message("Short 008 padded");
149 # clean misplaced dollarsigns
150 if ($record[$recptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
151 $record[$recptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
152 message("Dollar sign corrected");
155 # clean up tags with spaces in them
156 $record[$recptr] =~ s/tag=" /tag="00/g;
157 $record[$recptr] =~ s/tag=" /tag="0/g;
158 $record[$recptr] =~ s/tag="-/tag="0/g;
159 $record[$recptr] =~ s/tag="(\d\d) /tag="0$1/g;
161 # stow tag data if we're looking at it
162 if ($record[$recptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
168 # automatable subfield maladies
169 $record[$recptr] =~ s/code=" ">c/code="c">/;
170 $record[$recptr] =~ s/code=" ">\$/code="c"$>/;
174 #-----------------------------------------------------------------------------------
176 #-----------------------------------------------------------------------------------
181 Handles the Term::ReadLine loop
188 return if $conf->{trash}{ $recmeta{tag} };
193 my $line = $term->readline('marc-cleanup>');
194 my @chunks = split /\s+/, $line;
196 if (length $chunks[0] == 1)
197 { next unless (defined $commands{$chunks[0]}) }
199 if (defined $commands{$chunks[0]}) {
200 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
203 $record[$recptr] = "$line\n";
211 Constructs record arrays from the incoming MARC file and returns them
218 $l = <MARC> while (defined $l and $l !~ /<record>/);
219 return $l unless defined $l;
224 until ($l =~ m|</record>|)
225 { push @record, $l; $l = <MARC>; }
232 my $trash = $conf->{trash};
234 $conf->{rocount}++ if ($FH eq $NUMARC);
235 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
236 if(defined $recmeta{explanation});
238 # excise unwanted tags
239 if (keys %{$trash} or $conf->{autoscrub}) {
242 for my $line (@record) {
244 $istrash = 0 if $line =~ m|</datafield|;
247 if ($line =~ m/<datafield tag="(.{3})"/) {
249 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
254 push @trimmed, $line;
260 unless ($conf->{nocollapse}) {
261 s/\n// for (@record);
264 # add 903(?) with new record id
266 if ($conf->{'renumber-from'}) {
267 $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
268 '" ind1=" " ind2=" ">',
269 '<subfield code="', $conf->{'renumber-subfield'}, '">',
270 $conf->{'renumber-from'}, '</subfield></datafield>');
271 $renumber .= "\n" if $conf->{nocollapse};
272 push @record, $renumber;
273 $conf->{'renumber-from'}++;
277 print $FH "</record>\n";
281 print " Tag:",$recmeta{tag}, " Ind1:'",
282 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'\n";
287 sub print_linecontext {
288 my $low = ($recptr - 3 < 0) ? 0 : $recptr - 3;
289 print $OUT ' |', $record[$_] for ($low .. $recptr - 1);
290 print $OUT '==> |', $record[$recptr];
291 print $OUT ' |', $record[$recptr + 1], "\n";
296 my ($msg, $new) = @_;
297 print $OUT "\r", ' ' x 72, "\n" if $new;
298 print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
302 #-----------------------------------------------------------------------------------
304 #-----------------------------------------------------------------------------------
307 my ($line_in, @chunks) = @_;
308 my $ofrom = shift @chunks;
309 if ($ofrom =~ /^'/ or !@chunks) {
310 until ($ofrom =~ /'$/)
311 { $ofrom .= join(' ','',shift @chunks) }
312 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
314 my $to = shift @chunks;
316 until ($to =~ /'$/ or !@chunks)
317 { $to .= join(' ','',shift @chunks) }
318 $to =~ s/^'//; $to =~ s/'$//;
322 for my $char (split(//,$ofrom)) {
323 $char = "\\" . $char if ($char =~ /\W/);
324 $from = join('', $from, $char);
326 $record[$recptr] =~ s/$from/$to/;
332 # remove <subfield stuff; extract (probably wrong) subfield code
333 $record[$recptr] =~ s/^\s*<subfield code="(.*?)">//;
334 # and move to front of line
335 $record[$recptr] = join(' ', $1 , $record[$recptr]);
336 # tear off trailing subfield tag from preceeding line
337 $record[$recptr - 1] =~ s|</subfield>\n||;
338 # join current line onto preceeding line
339 $record[$recptr - 1] = join('', $record[$recptr - 1], $record[$recptr]);
341 my @a = @record[0 .. $recptr - 1];
342 my @b = @record[$recptr + 1 .. $#record];
344 # move record pointer to previous line
350 my @a = @record[0 .. $recptr - 1];
351 my @b = @record[$recptr + 1 .. $#record];
358 my ($line_in, @explanation) = @_;
359 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
360 write_record($EXMARC);
376 sub commit_edit { return 1 }
380 print $OUT "\n$line_in\n";
387 Type a replacement for the indicated line, or enter a command.
389 Commands: c Show record context again ('C' for brief context)
390 k Kill indicated line (remove from record)
391 m Merge indicated line with previous line
393 s Substitute ARG1 for ARG2 in indicated line
394 t Commit changes and resume stream edit
395 x Write this record to the exception file instead of output
404 #-----------------------------------------------------------------------------------
406 #-----------------------------------------------------------------------------------
407 # defined a domain-specific language for specifying MARC tags to be dropped from
408 # records during processing. it is line oriented, and is specified as follows:
410 # each line may specify any number of tags to be included, either singly (\d{1,3})
411 # or as a range (\d{1,3}\.\.\d{1,3}
413 # if a single number is given, it must be between '000' and '999', inclusive.
415 # ranges obey the previous rule, and also the first number of the range must be less
416 # than the second number
418 # finally, any single range in a line may be followed by the keyword 'except'. every
419 # number or range after 'except' is excluded from the range specified. all these
420 # numbers must actually be within the range.
422 # specifying a tag twice is an error, to help prevent typos
425 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
426 open TRASH, '<', $conf->{trash}
427 or die "Can't open trash tags file!\n";
429 my $lastwasrange = 0;
430 my %lastrange = ( high => 0, low => 0);
433 my @chunks = split /\s+/;
434 while (my $chunk = shift @chunks) {
437 if ($chunk =~ /^\d{1,3}$/) {
438 trash_add($chunk, $except);
444 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
445 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
447 %lastrange = (low => $low, high => $high)
453 if ($chunk eq 'except') {
454 die "Keyword 'except' can only follow a range (line $.)\n"
455 unless $lastwasrange;
456 die "Keyword 'except' may only occur once per line (line $.)\n"
462 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
466 # remove original id sequence tag from trash hash if we know it
467 trash_add($conf->{'original-tag'}, 1)
468 if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
471 sub trash_add_range {
472 my ($chunk, $except, $range) = @_;
473 my ($low,$high) = split /\.\./, $chunk;
474 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
477 die "Exception ranges must be within last addition range (line $.)\n"
478 if ($low < $range->{low} or $high > $range->{high});
480 for my $tag ($low..$high) {
481 trash_add($tag, $except)
487 my ($tag, $except) = @_;
488 my $trash = $conf->{trash};
490 die "Trash values must be valid tags (000-999)\n"
491 unless ($tag >= 0 and $tag <= 999);
494 delete $trash->{$tag};
496 die "Trash tag '$tag' specified twice (line $.)\n"
502 #-----------------------------------------------------------------------
506 Performs boring script initialization. Handles argument parsing,
515 # set mode on existing filehandles
516 binmode(STDIN, ':utf8');
518 my $rc = GetOptions( $c,
523 'renumber-from|rf=i',
526 'renumber-subfield|rt=i',
530 show_help() unless $rc;
531 show_help() if ($c->{help});
534 $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
535 $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
536 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
537 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
539 my @keys = keys %{$c};
540 show_help() unless (@ARGV and @keys);
541 #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
542 # { push @missing, $key unless $c->{$key} }
544 # print "Required option: ", join(', ', @missing), " missing!\n";
551 Usage is: $0 [OPTIONS] <filelist>
553 --output -o Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
554 --exception -x Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)