5984c364297f2cbb10b09d7803294592daf5bf89
[migration-tools.git] / marc-cleanup
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Getopt::Long;
7 use Term::ReadLine;
8
9 $| = 1;
10
11 my $term = new Term::ReadLine 'yaz-cleanup';
12 my $OUT = $term->OUT || \*STDOUT;
13
14 # initialization and setup
15 my $conf = {};
16 initialize($conf);
17 populate_trash() if ($conf->{trash});
18
19 my @record  = (); # current record storage
20 my %recmeta = (); # metadata about current record
21 my $recptr  = 0;  # record index pointer
22
23 my $input = shift || 'incoming.marc.xml';
24
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";
29
30 open my $EXMARC, '>:utf8', $conf->{exception};
31
32 # this is the dispatch table which drives command selection in
33 # edit(), below
34 my %commands = ( c => \&print_context,
35                  C => \&print_linecontext,
36                  k => \&kill_line,
37                  o => \&show_original,
38                  m => \&merge_lines,
39                  s => \&substitute,
40                  t => \&commit_edit,
41                  x => \&dump_record,
42                  q => \&quit,
43                  '?' => \&help,
44                  h   => \&help,
45                  help => \&help,
46                );
47
48 my @spinner = qw(- / | \\);
49 my $sidx = 0;
50
51 while ( buildrecord() ) {
52     unless ($conf->{ricount} % 100) {
53         print "\rWorking... ", $spinner[$sidx];
54         $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
55     }
56
57     do_automated_cleanups();
58
59     $recptr = 0;
60     until ($recptr == $#record) {
61         # naked ampersands
62         if ($record[$recptr] =~ /&/ && $record[$recptr] !~ /&\w+?;/)
63           { edit("Naked ampersand"); $recptr= 0; next }
64
65         # tags must be numeric
66         if ($record[$recptr] =~ /<datafield tag="(.+?)"/) {
67             my $match = $1;
68             if ($match =~ /\D/) {
69                 edit("Non-numerics in tag");
70                 $recptr = 0;
71                 next;
72             }
73         }
74
75         # subfields can't be non-alphanumeric
76         if ($record[$recptr] =~ /<subfield code="(.*?)"/) {
77             my $match = $1;
78             if ($match =~ /\P{IsAlnum}/ or $match eq '') {
79                 edit("Junk in subfield code/Null subfield code");
80                 $recptr = 0;
81                 next;
82             }
83         }
84         $recptr++;
85     }
86
87     write_record($NUMARC);
88 }
89 print $NUMARC "</collection>\n";
90 print $OUT "\nDone.               \n";
91
92
93 #-----------------------------------------------------------------------------------
94 # cleanup routines
95 #-----------------------------------------------------------------------------------
96
97 sub do_automated_cleanups {
98     $recptr = 0;
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];
105                 @record = (@a, @b);
106                 message("Empty datafield scrubbed");
107                 $recptr = 0;
108                 next;
109             }
110         }
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];
117                 @record = (@a, @b);
118                 message("Empty subfield scrubbed");
119                 $recptr = 0;
120                 next;
121             }
122         }
123         $recptr++;
124     }
125
126     # single-line fixes
127     for $recptr (0 .. $#record) {
128         # pad short leaders
129         if ($record[$recptr] =~ m|<leader>(.+?)</leader>|) {
130             my $leader = $1;
131             if (length $leader < 24) {
132                 $leader .= ' ' x (20 - length($leader));
133                 $leader .= "4500";
134                 $record[$recptr] = "<leader>$leader</leader>\n";
135                 message("Short leader padded");
136             }
137         }
138         if ($record[$recptr] =~ m|<controlfield tag="008">(.+?)</control|) {
139             #pad short 008
140             my $content = $1;
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");
145             }
146         }
147
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");
152         }
153
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;
159
160         # stow tag data if we're looking at it
161         if ($record[$recptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
162             $recmeta{tag}  = $1;
163             $recmeta{ind1} = $2;
164             $recmeta{ind2} = $3;
165         }
166
167         # automatable subfield maladies
168         $record[$recptr] =~ s/code=" ">c/code="c">/;
169         $record[$recptr] =~ s/code=" ">\$/code="c"$>/;
170     }
171 }
172
173 #-----------------------------------------------------------------------------------
174 # driver routines
175 #-----------------------------------------------------------------------------------
176
177
178 =head2 edit
179
180 Handles the Term::ReadLine loop
181
182 =cut
183
184 sub edit {
185     my ($msg) = @_;
186
187     return if $conf->{trash}{ $recmeta{tag} };
188     message($msg, 1);
189     print_context();
190
191     while (1) {
192         my $line = $term->readline('marc-cleanup>');
193         my @chunks = split /\s+/, $line;
194
195         if (length $chunks[0] == 1)
196           { next unless (defined $commands{$chunks[0]}) }
197
198         if (defined $commands{$chunks[0]}) {
199             my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
200             last if $term;
201         } else {
202             $record[$recptr] = "$line\n";
203             print_linecontext();
204         }
205     }
206 }
207
208 =head2 buildrecord
209
210 Constructs record arrays from the incoming MARC file and returns them
211 to the driver loop.
212
213 =cut
214
215 sub buildrecord {
216     my $l = '';
217     $l = <MARC> while (defined $l and $l !~ /<record>/);
218     return $l unless defined $l;
219     @record = ($l);
220     %recmeta = ();
221     $conf->{ricount}++;
222
223     until ($l =~ m|</record>|) 
224       { push @record, $l; $l = <MARC>; }
225     push @record, $l;
226     return 1;
227 }
228
229 sub write_record {
230     my ($FH) = @_;
231     my $trash = $conf->{trash};
232
233     $conf->{rocount}++ if ($FH eq $NUMARC);
234     print $FH '<!-- ', $recmeta{explanation}, " -->\n"
235       if(defined $recmeta{explanation});
236
237     # excise unwanted tags
238     if (keys %{$trash} or $conf->{autoscrub}) {
239         my @trimmed = ();
240         my $istrash = 0;
241         for my $line (@record) {
242             if ($istrash) {
243                 $istrash = 0 if $line =~ m|</datafield|;
244                 next;
245             }
246             if ($line =~ m/<datafield tag="(.{3})"/) {
247                 my $tag = $1;
248                 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
249                     $istrash = 1;
250                     next
251                 }
252             }
253             push @trimmed, $line;
254         }
255         @record = @trimmed;
256     }
257
258     # scrub newlines
259     unless ($conf->{nocollapse}) {
260         s/\n// for (@record);
261     }
262
263     # add 903(?) with new record id
264     my $renumber = '';
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'}++;
273     }
274
275     print $FH @record;
276     print $FH "</record>\n";
277 }
278
279 sub print_context {
280     print "    Tag:",$recmeta{tag}, " Ind1:'",
281       $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'\n";
282     print_linecontext();
283     return 0;
284 }
285
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";
291     return 0;
292 }
293
294 sub message {
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";
298
299 }
300
301 #-----------------------------------------------------------------------------------
302 # command routines
303 #-----------------------------------------------------------------------------------
304
305 sub substitute {
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/'$//;
312     }
313     my $to = shift @chunks;
314     if ($to =~ /^'/) {
315         until ($to =~ /'$/ or !@chunks)
316           { $to .= join(' ','',shift @chunks) }
317         $to =~ s/^'//; $to =~ s/'$//;
318     }
319
320     my $from = '';
321     for my $char (split(//,$ofrom)) {
322         $char = "\\" . $char if ($char =~ /\W/);
323         $from = join('', $from, $char);
324     }
325     $record[$recptr] =~ s/$from/$to/;
326     print_linecontext();
327     return 0;
328 }
329
330 sub merge_lines {
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]);
335     print_linecontext();
336     return 0;
337 }
338
339 sub kill_line {
340     my @a = @record[0 .. $recptr - 1];
341     my @b = @record[$recptr + 1 .. $#record];
342     @record = (@a, @b);
343     print_linecontext();
344     return 0;
345 }
346
347 sub dump_record {
348     my ($line_in, @explanation) = @_;
349     $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
350     write_record($EXMARC);
351     return 1;
352 }
353
354 sub commit_edit { return 1 }
355
356 sub show_original {
357     my ($line_in) = @_;
358     print $OUT "\n$line_in\n";
359     return 0;
360 }
361
362 sub help {
363 print $OUT <<HELP;
364
365 Type a replacement for the indicated line, or enter a command.
366
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
370           o  Show original 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
374           q  Quit
375
376 HELP
377 return 0;
378 }
379
380 sub quit { exit }
381
382 #-----------------------------------------------------------------------------------
383 # populate_trash
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:
387 #
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}
390 #
391 # if a single number is given, it must be between '000' and '999', inclusive.
392 #
393 # ranges obey the previous rule, and also the first number of the range must be less
394 # than the second number
395 #
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.
399 #
400 # specifying a tag twice is an error, to help prevent typos
401
402 sub populate_trash {
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";
406     while (<TRASH>) {
407         my $lastwasrange = 0;
408         my %lastrange = ( high => 0, low => 0);
409         my $except = 0;
410
411         my @chunks = split /\s+/;
412         while (my $chunk = shift @chunks) {
413
414             # single values
415             if ($chunk =~ /^\d{1,3}$/) {
416                 trash_add($chunk, $except);
417                 $lastwasrange = 0;
418                 next;
419             }
420
421             # ranges
422             if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
423                 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
424                 $lastwasrange = 1;
425                 %lastrange = (low => $low, high => $high)
426                   unless $except;
427                 next;
428             }
429
430             # 'except'
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"
435                   if $except;
436                 $except = 1;
437                 next;
438             }
439
440             die "Unknown chunk $chunk in .trashtags file (line $.)\n";
441         }
442     }
443
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'} });
447 }
448
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"
453       if ($low > $high);
454     if ($except) {
455         die "Exception ranges must be within last addition range (line $.)\n"
456           if ($low < $range->{low} or $high > $range->{high});
457     }
458     for my $tag ($low..$high) {
459         trash_add($tag, $except)
460     }
461     return $low, $high;
462 }
463
464 sub trash_add {
465     my ($tag, $except) = @_;
466     my $trash = $conf->{trash};
467
468     die "Trash values must be valid tags (000-999)\n"
469       unless ($tag >= 0 and $tag <= 999);
470
471     if ($except) {
472         delete $trash->{$tag};
473     } else {
474         die "Trash tag '$tag' specified twice (line $.)\n"
475           if $trash->{$tag};
476         $trash->{$tag} = 1;
477     }
478 }
479
480 #-----------------------------------------------------------------------
481
482 =head2 initialize
483
484 Performs boring script initialization. Handles argument parsing,
485 mostly.
486
487 =cut
488
489 sub initialize {
490     my ($c) = @_;
491     my @missing = ();
492
493     # set mode on existing filehandles
494     binmode(STDIN, ':utf8');
495
496     my $rc = GetOptions( $c,
497                          'autoscrub|a',
498                          'exception|x=s',
499                          'output|o=s',
500                          'nocollapse|n',
501                          'renumber-from|rf=i',
502                          'original-tag|ot=i',
503                          'renumber-tag|rt=i',
504                          'renumber-subfield|rt=i',
505                          'trash|t=s',
506                          'help|h',
507                        );
508     show_help() unless $rc;
509     show_help() if ($c->{help});
510
511     # defaults
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'};
516
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} }
521     #if (@missing) {
522     #    print "Required option: ", join(', ', @missing), " missing!\n";
523     #    show_help();
524     #}
525 }
526
527 sub show_help {
528     print <<HELP;
529 Usage is: $0 [OPTIONS] <filelist>
530 Options
531   --output     -o  Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
532   --exception  -x  Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)
533 HELP
534 exit;
535 }