fb4f702f9c58df7add654b18b8a534864daa650f
[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     write_record($NUMARC);
87 }
88 print $NUMARC "</collection>\n";
89 print $OUT "\nDone.               \n";
90
91
92 #-----------------------------------------------------------------------------------
93 # cleanup routines
94 #-----------------------------------------------------------------------------------
95
96 sub do_automated_cleanups {
97     $recptr = 0;
98     until ($recptr == $#record) {
99         # catch empty datafield elements
100         if ($record[$recptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
101             if ($record[$recptr + 1] =~ m|</datafield>|) {
102                 my @a = @record[0 .. $recptr - 1];
103                 my @b = @record[$recptr + 2 .. $#record];
104                 @record = (@a, @b);
105                 message("Empty datafield scrubbed");
106                 $recptr = 0;
107                 next;
108             }
109         }
110         # and quasi-empty subfields
111         if ($record[$recptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
112             my $code = $1; my $content = $2;
113             if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
114                 my @a = @record[0 .. $recptr - 1];
115                 my @b = @record[$recptr + 1 .. $#record];
116                 @record = (@a, @b);
117                 message("Empty subfield scrubbed");
118                 $recptr = 0;
119                 next;
120             }
121         }
122         $recptr++;
123     }
124
125     # single-line fixes
126     for $recptr (0 .. $#record) {
127         # pad short leaders
128         if ($record[$recptr] =~ m|<leader>(.+?)</leader>|) {
129             my $leader = $1;
130             if (length $leader < 24) {
131                 $leader .= ' ' x (20 - length($leader));
132                 $leader .= "4500";
133                 $record[$recptr] = "<leader>$leader</leader>\n";
134                 message("Short leader padded");
135             }
136         }
137         if ($record[$recptr] =~ m|<controlfield tag="008">(.+?)</control|) {
138             #pad short 008
139             my $content = $1;
140             if (length $content < 40) {
141                 $content .= ' ' x (40 - length($content));
142                 $record[$recptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
143                 message("Short 008 padded");
144             }
145         }
146
147         # clean misplaced dollarsigns
148         if ($record[$recptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
149             $record[$recptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
150             message("Dollar sign corrected");
151         }
152
153         # clean up tags with spaces in them
154         $record[$recptr] =~ s/tag="  /tag="00/g;
155         $record[$recptr] =~ s/tag=" /tag="0/g;
156         $record[$recptr] =~ s/tag="-/tag="0/g;
157         $record[$recptr] =~ s/tag="(\d\d) /tag="0$1/g;
158
159         # stow tag data if we're looking at it
160         if ($record[$recptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
161             $recmeta{tag}  = $1;
162             $recmeta{ind1} = $2;
163             $recmeta{ind2} = $3;
164         }
165
166         # automatable subfield maladies
167         $record[$recptr] =~ s/code=" ">c/code="c">/;
168         $record[$recptr] =~ s/code=" ">\$/code="c"$>/;
169     }
170 }
171
172 #-----------------------------------------------------------------------------------
173 # driver routines
174 #-----------------------------------------------------------------------------------
175
176
177 =head2 edit
178
179 Handles the Term::ReadLine loop
180
181 =cut
182
183 sub edit {
184     my ($msg) = @_;
185
186     return if $conf->{trash}{ $recmeta{tag} };
187     message($msg, 1);
188     print_context();
189
190     while (1) {
191         my $line = $term->readline('marc-cleanup>');
192         my @chunks = split /\s+/, $line;
193
194         if (length $chunks[0] == 1)
195           { next unless (defined $commands{$chunks[0]}) }
196
197         if (defined $commands{$chunks[0]}) {
198             my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
199             last if $term;
200         } else {
201             $record[$recptr] = "$line\n";
202             print_linecontext();
203         }
204     }
205 }
206
207 =head2 buildrecord
208
209 Constructs record arrays from the incoming MARC file and returns them
210 to the driver loop.
211
212 =cut
213
214 sub buildrecord {
215     my $l = '';
216     $l = <MARC> while (defined $l and $l !~ /<record>/);
217     return $l unless defined $l;
218     @record = ($l);
219     %recmeta = ();
220     $conf->{ricount}++;
221
222     until ($l =~ m|</record>|) 
223       { push @record, $l; $l = <MARC>; }
224     push @record, $l;
225     return 1;
226 }
227
228 sub write_record {
229     my ($FH) = @_;
230     my $trash = $conf->{trash};
231
232     $conf->{rocount}++ if ($FH eq $NUMARC);
233     print $FH '<!-- ', $recmeta{explanation}, " -->\n"
234       if(defined $recmeta{explanation});
235
236     # excise unwanted tags
237     if (keys %{$trash} or $conf->{autoscrub}) {
238         my @trimmed = ();
239         my $istrash = 0;
240         for my $line (@record) {
241             if ($istrash) {
242                 $istrash = 0 if $line =~ m|</datafield|;
243                 next;
244             }
245             if ($line =~ m/<datafield tag="(.{3})"/) {
246                 my $tag = $1;
247                 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
248                     $istrash = 1;
249                     next
250                 }
251             }
252             push @trimmed, $line;
253         }
254         @record = @trimmed;
255     }
256
257     # scrub newlines
258     unless ($conf->{nocollapse}) {
259         s/\n// for (@record);
260     }
261
262     # add 903(?) with new record id
263     my $renumber = '';
264     if ($conf->{'renumber-from'}) {
265         $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
266                          '" ind1=" " ind2=" ">',
267                          '<subfield code="', $conf->{'renumber-subfield'}, '">',
268                          $conf->{'renumber-from'}, '</subfield></datafield>');
269         $renumber .= "\n" if $conf->{nocollapse};
270         push @record, $renumber;
271         $conf->{'renumber-from'}++;
272     }
273
274     print $FH @record;
275     print $FH "</record>\n";
276 }
277
278 sub print_context {
279     print "    Tag:",$recmeta{tag}, " Ind1:'",
280       $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'\n";
281     print_linecontext();
282     return 0;
283 }
284
285 sub print_linecontext {
286     my $low = ($recptr - 3 < 0) ? 0 : $recptr - 3;
287     print $OUT '    |', $record[$_] for ($low .. $recptr - 1);
288     print $OUT '==> |', $record[$recptr];
289     print $OUT '    |', $record[$recptr + 1], "\n";
290     return 0;
291 }
292
293 sub message {
294     my ($msg, $new) = @_;
295     print $OUT "\r", ' ' x 72, "\n" if $new;
296     print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
297
298 }
299
300 #-----------------------------------------------------------------------------------
301 # command routines
302 #-----------------------------------------------------------------------------------
303
304 sub substitute {
305     my ($line_in, @chunks) = @_;
306     my $ofrom = shift @chunks;
307     if ($ofrom =~ /^'/ or !@chunks) {
308         until ($ofrom =~ /'$/)
309           { $ofrom .= join(' ','',shift @chunks) }
310         $ofrom =~ s/^'//; $ofrom =~ s/'$//;
311     }
312     my $to = shift @chunks;
313     if ($to =~ /^'/) {
314         until ($to =~ /'$/ or !@chunks)
315           { $to .= join(' ','',shift @chunks) }
316         $to =~ s/^'//; $to =~ s/'$//;
317     }
318
319     my $from = '';
320     for my $char (split(//,$ofrom)) {
321         $char = "\\" . $char if ($char =~ /\W/);
322         $from = join('', $from, $char);
323     }
324     $record[$recptr] =~ s/$from/$to/;
325     print_linecontext();
326     return 0;
327 }
328
329 sub merge_lines {
330     # remove <subfield stuff; extract (probably wrong) subfield code
331     $record[$recptr] =~ s/^\s*<subfield code="(.*?)">//;
332     # and move to front of line
333     $record[$recptr] = join(' ', $1 , $record[$recptr]);
334     # tear off trailing subfield tag from preceeding line
335     $record[$recptr - 1] =~ s|</subfield>\n||;
336     # join current line onto preceeding line
337     $record[$recptr - 1] = join('', $record[$recptr - 1], $record[$recptr]);
338     # erase current line
339     my @a = @record[0 .. $recptr - 1];
340     my @b = @record[$recptr + 1 .. $#record];
341     @record = (@a, @b);
342     # move recorde pointer to previous line
343     $recptr--;
344     print_linecontext();
345     return 0;
346 }
347
348 sub kill_line {
349     my @a = @record[0 .. $recptr - 1];
350     my @b = @record[$recptr + 1 .. $#record];
351     @record = (@a, @b);
352     print_linecontext();
353     return 0;
354 }
355
356 sub dump_record {
357     my ($line_in, @explanation) = @_;
358     $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
359     write_record($EXMARC);
360     return 1;
361 }
362
363 sub commit_edit { return 1 }
364
365 sub show_original {
366     my ($line_in) = @_;
367     print $OUT "\n$line_in\n";
368     return 0;
369 }
370
371 sub help {
372 print $OUT <<HELP;
373
374 Type a replacement for the indicated line, or enter a command.
375
376 Commands: c  Show record context again ('C' for brief context)
377           k  Kill indicated line (remove from record)
378           m  Merge indicated line with previous line
379           o  Show original line
380           s  Substitute ARG1 for ARG2 in indicated line
381           t  Commit changes and resume stream edit
382           x  Write this record to the exception file instead of output
383           q  Quit
384
385 HELP
386 return 0;
387 }
388
389 sub quit { exit }
390
391 #-----------------------------------------------------------------------------------
392 # populate_trash
393 #-----------------------------------------------------------------------------------
394 # defined a domain-specific language for specifying MARC tags to be dropped from
395 # records during processing. it is line oriented, and is specified as follows:
396 #
397 # each line may specify any number of tags to be included, either singly (\d{1,3})
398 # or as a range (\d{1,3}\.\.\d{1,3}
399 #
400 # if a single number is given, it must be between '000' and '999', inclusive.
401 #
402 # ranges obey the previous rule, and also the first number of the range must be less
403 # than the second number
404 #
405 # finally, any single range in a line may be followed by the keyword 'except'. every
406 # number or range after 'except' is excluded from the range specified. all these
407 # numbers must actually be within the range.
408 #
409 # specifying a tag twice is an error, to help prevent typos
410
411 sub populate_trash {
412     print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
413     open TRASH, '<', $conf->{trash}
414       or die "Can't open trash tags file!\n";
415     while (<TRASH>) {
416         my $lastwasrange = 0;
417         my %lastrange = ( high => 0, low => 0);
418         my $except = 0;
419
420         my @chunks = split /\s+/;
421         while (my $chunk = shift @chunks) {
422
423             # single values
424             if ($chunk =~ /^\d{1,3}$/) {
425                 trash_add($chunk, $except);
426                 $lastwasrange = 0;
427                 next;
428             }
429
430             # ranges
431             if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
432                 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
433                 $lastwasrange = 1;
434                 %lastrange = (low => $low, high => $high)
435                   unless $except;
436                 next;
437             }
438
439             # 'except'
440             if ($chunk eq 'except') {
441                 die "Keyword 'except' can only follow a range (line $.)\n"
442                   unless $lastwasrange;
443                 die "Keyword 'except' may only occur once per line (line $.)\n"
444                   if $except;
445                 $except = 1;
446                 next;
447             }
448
449             die "Unknown chunk $chunk in .trashtags file (line $.)\n";
450         }
451     }
452
453     # remove original id sequence tag from trash hash if we know it
454     trash_add($conf->{'original-tag'}, 1)
455       if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
456 }
457
458 sub trash_add_range {
459     my ($chunk, $except, $range) = @_;
460     my ($low,$high) = split /\.\./, $chunk;
461     die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
462       if ($low > $high);
463     if ($except) {
464         die "Exception ranges must be within last addition range (line $.)\n"
465           if ($low < $range->{low} or $high > $range->{high});
466     }
467     for my $tag ($low..$high) {
468         trash_add($tag, $except)
469     }
470     return $low, $high;
471 }
472
473 sub trash_add {
474     my ($tag, $except) = @_;
475     my $trash = $conf->{trash};
476
477     die "Trash values must be valid tags (000-999)\n"
478       unless ($tag >= 0 and $tag <= 999);
479
480     if ($except) {
481         delete $trash->{$tag};
482     } else {
483         die "Trash tag '$tag' specified twice (line $.)\n"
484           if $trash->{$tag};
485         $trash->{$tag} = 1;
486     }
487 }
488
489 #-----------------------------------------------------------------------
490
491 =head2 initialize
492
493 Performs boring script initialization. Handles argument parsing,
494 mostly.
495
496 =cut
497
498 sub initialize {
499     my ($c) = @_;
500     my @missing = ();
501
502     # set mode on existing filehandles
503     binmode(STDIN, ':utf8');
504
505     my $rc = GetOptions( $c,
506                          'autoscrub|a',
507                          'exception|x=s',
508                          'output|o=s',
509                          'nocollapse|n',
510                          'renumber-from|rf=i',
511                          'original-tag|ot=i',
512                          'renumber-tag|rt=i',
513                          'renumber-subfield|rt=i',
514                          'trash|t=s',
515                          'help|h',
516                        );
517     show_help() unless $rc;
518     show_help() if ($c->{help});
519
520     # defaults
521     $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
522     $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
523     $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
524     $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
525
526     my @keys = keys %{$c};
527     show_help() unless (@ARGV and @keys);
528     #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
529     #  { push @missing, $key unless $c->{$key} }
530     #if (@missing) {
531     #    print "Required option: ", join(', ', @missing), " missing!\n";
532     #    show_help();
533     #}
534 }
535
536 sub show_help {
537     print <<HELP;
538 Usage is: $0 [OPTIONS] <filelist>
539 Options
540   --output     -o  Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
541   --exception  -x  Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)
542 HELP
543 exit;
544 }