834331e3aa13315bd1c19a1d7e2664e238180df1
[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 my $term = new Term::ReadLine 'yaz-cleanup';
10 my $OUT = $term->OUT || \*STDOUT;
11
12 # initialization and setup
13 my $conf = {};
14 initialize($conf);
15 populate_trash() if ($conf->{trash});
16
17 my @record  = (); # current record storage
18 my %recmeta = (); # metadata about current record
19 my $ptr  = 0;  # record index pointer
20
21 my $input = shift || 'incoming.marc.xml';
22
23 open MARC, '<:utf8', $input;
24 open my $NUMARC, '>:utf8', $conf->{output};
25 print $NUMARC '<?xml version="1.0" encoding="UTF-8"?>',"\n";
26 print $NUMARC '<collection xmlns="http://www.loc.gov/MARC21/slim">',"\n";
27
28 open my $EXMARC, '>:utf8', $conf->{exception};
29
30 # this is the dispatch table which drives command selection in
31 # edit(), below
32 my %commands = ( c => \&print_context,
33                  C => \&print_linecontext,
34                  o => \&show_original,
35                  O => \&insert_original,
36                  f => \&flip_lines,
37                  k => \&kill_line,
38                  y => \&yank_line,
39                  m => \&merge_lines,
40                  n => \&next_line,
41                  p => \&prev_line,
42                  s => \&substitute,
43                  t => \&commit_edit,
44                  x => \&dump_record,
45                  q => \&quit,
46                  '?' => \&help,
47                  h   => \&help,
48                  help => \&help,
49                );
50
51 my @spinner = qw(- / | \\);
52 my $sidx = 0;
53
54 while ( buildrecord() ) {
55     unless ($conf->{ricount} % 100) {
56         print "\rWorking... ", $spinner[$sidx];
57         $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
58     }
59
60     do_automated_cleanups();
61
62     $ptr = 0;
63     until ($ptr == $#record) {
64         # naked ampersands
65         if ($record[$ptr] =~ /&/ && $record[$ptr] !~ /&\w+?;/)
66           { edit("Naked ampersand"); $ptr= 0; next }
67
68         # tags must be numeric
69         if ($record[$ptr] =~ /<datafield tag="(.+?)"/) {
70             my $match = $1;
71             if ($match =~ /\D/) {
72                 edit("Non-numerics in tag");
73                 next;
74             }
75         }
76
77         # subfields can't be non-alphanumeric
78         if ($record[$ptr] =~ /<subfield code="(.*?)"/) {
79             my $match = $1;
80             if ($match =~ /\P{IsAlnum}/ or $match eq '') {
81                 edit("Junk in subfield code/Null subfield code");
82                 next;
83             }
84         }
85         $ptr++;
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     $ptr = 0;
99     until ($ptr == $#record) {
100         # catch empty datafield elements
101         if ($record[$ptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
102             if ($record[$ptr + 1] =~ m|</datafield>|) {
103                 my @a = @record[0 .. $ptr - 1];
104                 my @b = @record[$ptr + 2 .. $#record];
105                 @record = (@a, @b);
106                 message("Empty datafield scrubbed");
107                 $ptr = 0;
108                 next;
109             }
110         }
111         # and quasi-empty subfields
112         if ($record[$ptr] =~ 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 .. $ptr - 1];
116                 my @b = @record[$ptr + 1 .. $#record];
117                 @record = (@a, @b);
118                 message("Empty subfield scrubbed");
119                 $ptr = 0;
120                 next;
121             }
122         }
123         $ptr++;
124     }
125
126     # single-line fixes
127     for $ptr (0 .. $#record) {
128         # pad short leaders
129         if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
130             my $leader = $1;
131             if (length $leader < 24) {
132                 $leader .= ' ' x (20 - length($leader));
133                 $leader .= "4500";
134                 $record[$ptr] = "<leader>$leader</leader>\n";
135                 message("Short leader padded");
136             }
137         }
138         if ($record[$ptr] =~ 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[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
144                 message("Short 008 padded");
145             }
146         }
147
148         # clean misplaced dollarsigns
149         if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
150             $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
151             message("Dollar sign corrected");
152         }
153
154         # clean up tags with spaces in them
155         $record[$ptr] =~ s/tag="  /tag="00/g;
156         $record[$ptr] =~ s/tag=" /tag="0/g;
157         $record[$ptr] =~ s/tag="-/tag="0/g;
158         $record[$ptr] =~ s/tag="(\d\d) /tag="0$1/g;
159
160         # stow tag data if we're looking at it
161         if ($record[$ptr] =~ 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[$ptr] =~ s/code=" ">c/code="c">/;
169         $record[$ptr] =~ 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     # stow original problem line
192     $conf->{origline} = $record[$ptr];
193
194     while (1) {
195         my $line = $term->readline('marc-cleanup>');
196         my @chunks = split /\s+/, $line;
197
198         if (length $chunks[0] == 1)
199           { next unless (defined $commands{$chunks[0]}) }
200
201         if (defined $commands{$chunks[0]}) {
202             my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
203             last if $term;
204         } else {
205             $record[$ptr] = "$line\n";
206             print_linecontext();
207         }
208     }
209     $ptr = 0;
210 }
211
212 =head2 buildrecord
213
214 Constructs record arrays from the incoming MARC file and returns them
215 to the driver loop.
216
217 =cut
218
219 sub buildrecord {
220     my $l = '';
221     $l = <MARC> while (defined $l and $l !~ /<record>/);
222     return $l unless defined $l;
223     @record = ($l);
224     %recmeta = ();
225     $conf->{ricount}++;
226
227     until ($l =~ m|</record>|) 
228       { push @record, $l; $l = <MARC>; }
229     push @record, $l;
230     return 1;
231 }
232
233 sub write_record {
234     my ($FH) = @_;
235     my $trash = $conf->{trash};
236
237     $conf->{rocount}++ if ($FH eq $NUMARC);
238     print $FH '<!-- ', $recmeta{explanation}, " -->\n"
239       if(defined $recmeta{explanation});
240
241     # excise unwanted tags
242     if (keys %{$trash} or $conf->{autoscrub}) {
243         my @trimmed = ();
244         my $istrash = 0;
245         for my $line (@record) {
246             if ($istrash) {
247                 $istrash = 0 if $line =~ m|</datafield|;
248                 next;
249             }
250             if ($line =~ m/<datafield tag="(.{3})"/) {
251                 my $tag = $1;
252                 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
253                     $istrash = 1;
254                     next
255                 }
256             }
257             push @trimmed, $line;
258         }
259         @record = @trimmed;
260     }
261
262     # scrub newlines
263     unless ($conf->{nocollapse}) {
264         s/\n// for (@record);
265     }
266
267     # add 903(?) with new record id
268     my $renumber = '';
269     if ($conf->{'renumber-from'}) {
270         $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
271                          '" ind1=" " ind2=" ">',
272                          '<subfield code="', $conf->{'renumber-subfield'}, '">',
273                          $conf->{'renumber-from'}, '</subfield></datafield>');
274         $renumber .= "\n" if $conf->{nocollapse};
275         push @record, $renumber;
276         $conf->{'renumber-from'}++;
277     }
278
279     print $FH @record;
280     print $FH "</record>\n";
281 }
282
283 sub print_context {
284     print "    Tag:",$recmeta{tag}, " Ind1:'",
285       $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'\n";
286     print_linecontext();
287     return 0;
288 }
289
290 sub print_linecontext {
291     my $low = ($ptr - 3 < 0) ? 0 : $ptr - 3;
292     print $OUT '    |', $record[$_] for ($low .. $ptr - 1);
293     print $OUT '==> |', $record[$ptr];
294     print $OUT '    |', $record[$ptr + 1], "\n" unless ($ptr == $#record);
295     return 0;
296 }
297
298 sub message {
299     my ($msg, $new) = @_;
300     print $OUT "\r", ' ' x 72, "\n" if $new;
301     print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
302
303 }
304
305 #-----------------------------------------------------------------------------------
306 # command routines
307 #-----------------------------------------------------------------------------------
308
309 sub substitute {
310     my ($line_in, @chunks) = @_;
311
312     my $ofrom = shift @chunks;
313     if ($ofrom =~ /^'/ or !@chunks) {
314         until ($ofrom =~ /'$/)
315           { $ofrom .= join(' ','',shift @chunks) }
316         $ofrom =~ s/^'//; $ofrom =~ s/'$//;
317     }
318     my $to = shift @chunks;
319     if ($to =~ /^'/) {
320         until ($to =~ /'$/ or !@chunks)
321           { $to .= join(' ','',shift @chunks) }
322         $to =~ s/^'//; $to =~ s/'$//;
323     }
324
325     my $from = '';
326     for my $char (split(//,$ofrom)) {
327         $char = "\\" . $char if ($char =~ /\W/);
328         $from = join('', $from, $char);
329     }
330
331     $conf->{prevline} = $record[$ptr];
332     $record[$ptr] =~ s/$from/$to/;
333     print_linecontext();
334     return 0;
335 }
336
337 sub merge_lines {
338     $conf->{prevline} = $record[$ptr];
339     # remove <subfield stuff; extract (probably wrong) subfield code
340     $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
341     # and move to front of line
342     $record[$ptr] = join(' ', $1 , $record[$ptr]);
343     # tear off trailing subfield tag from preceeding line
344     $record[$ptr - 1] =~ s|</subfield>\n||;
345     # join current line onto preceeding line
346     $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
347     # erase current line
348     my @a = @record[0 .. $ptr - 1];
349     my @b = @record[$ptr + 1 .. $#record];
350     @record = (@a, @b);
351     # move record pointer to previous line
352     prev_line();
353     print_linecontext();
354     return 0;
355 }
356
357 sub flip_line {
358     my $temp = $record[$ptr];
359     $record[$ptr] = $conf->{prevline};
360     $conf->{prevline} = $temp;
361     print_linecontext();
362     return 0;
363 }
364
365 sub kill_line {
366     $conf->{prevline} = $record[$ptr];
367     my @a = @record[0 .. $ptr - 1];
368     my @b = @record[$ptr + 1 .. $#record];
369     @record = (@a, @b);
370     print_linecontext();
371     return 0;
372 }
373
374 sub yank_line {
375     my @a = @record[0 .. $ptr - 1];
376     my @b = @record[$ptr .. $#record];
377     @record = (@a, $conf->{prevline}, @b);
378     print_linecontext();
379     return 0;
380 }
381
382 sub show_original {
383     my ($line_in) = @_;
384     print $OUT "\n", $conf->{origline}, "\n";
385     return 0;
386 }
387
388 sub dump_record {
389     my ($line_in, @explanation) = @_;
390     $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
391     write_record($EXMARC);
392     return 1;
393 }
394
395 sub next_line {
396     $ptr++ unless ($ptr == $#record);;
397     print_linecontext();
398     return 0;
399 }
400
401 sub prev_line {
402     $ptr-- unless ($ptr == 0);
403     print_linecontext();
404     return 0;
405 }
406
407 sub commit_edit { return 1 }
408
409 sub help {
410 print $OUT <<HELP;
411
412 Type a replacement for the indicated line, or enter a command.
413
414 Commands: c  Show record context again ('C' for brief context)
415           k  Kill indicated line (remove from record)
416           m  Merge indicated line with previous line
417           o  Show original line
418           s  Substitute ARG1 for ARG2 in indicated line
419           t  Commit changes and resume stream edit
420           x  Write this record to the exception file instead of output
421           q  Quit
422
423 HELP
424 return 0;
425 }
426
427 sub quit { exit }
428
429 #-----------------------------------------------------------------------------------
430 # populate_trash
431 #-----------------------------------------------------------------------------------
432 # defined a domain-specific language for specifying MARC tags to be dropped from
433 # records during processing. it is line oriented, and is specified as follows:
434 #
435 # each line may specify any number of tags to be included, either singly (\d{1,3})
436 # or as a range (\d{1,3}\.\.\d{1,3}
437 #
438 # if a single number is given, it must be between '000' and '999', inclusive.
439 #
440 # ranges obey the previous rule, and also the first number of the range must be less
441 # than the second number
442 #
443 # finally, any single range in a line may be followed by the keyword 'except'. every
444 # number or range after 'except' is excluded from the range specified. all these
445 # numbers must actually be within the range.
446 #
447 # specifying a tag twice is an error, to help prevent typos
448
449 sub populate_trash {
450     print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
451     open TRASH, '<', $conf->{trash}
452       or die "Can't open trash tags file!\n";
453     while (<TRASH>) {
454         my $lastwasrange = 0;
455         my %lastrange = ( high => 0, low => 0);
456         my $except = 0;
457
458         my @chunks = split /\s+/;
459         while (my $chunk = shift @chunks) {
460
461             # single values
462             if ($chunk =~ /^\d{1,3}$/) {
463                 trash_add($chunk, $except);
464                 $lastwasrange = 0;
465                 next;
466             }
467
468             # ranges
469             if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
470                 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
471                 $lastwasrange = 1;
472                 %lastrange = (low => $low, high => $high)
473                   unless $except;
474                 next;
475             }
476
477             # 'except'
478             if ($chunk eq 'except') {
479                 die "Keyword 'except' can only follow a range (line $.)\n"
480                   unless $lastwasrange;
481                 die "Keyword 'except' may only occur once per line (line $.)\n"
482                   if $except;
483                 $except = 1;
484                 next;
485             }
486
487             die "Unknown chunk $chunk in .trashtags file (line $.)\n";
488         }
489     }
490
491     # remove original id sequence tag from trash hash if we know it
492     trash_add($conf->{'original-tag'}, 1)
493       if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
494 }
495
496 sub trash_add_range {
497     my ($chunk, $except, $range) = @_;
498     my ($low,$high) = split /\.\./, $chunk;
499     die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
500       if ($low > $high);
501     if ($except) {
502         die "Exception ranges must be within last addition range (line $.)\n"
503           if ($low < $range->{low} or $high > $range->{high});
504     }
505     for my $tag ($low..$high) {
506         trash_add($tag, $except)
507     }
508     return $low, $high;
509 }
510
511 sub trash_add {
512     my ($tag, $except) = @_;
513     my $trash = $conf->{trash};
514
515     die "Trash values must be valid tags (000-999)\n"
516       unless ($tag >= 0 and $tag <= 999);
517
518     if ($except) {
519         delete $trash->{$tag};
520     } else {
521         die "Trash tag '$tag' specified twice (line $.)\n"
522           if $trash->{$tag};
523         $trash->{$tag} = 1;
524     }
525 }
526
527 #-----------------------------------------------------------------------
528
529 =head2 initialize
530
531 Performs boring script initialization. Handles argument parsing,
532 mostly.
533
534 =cut
535
536 sub initialize {
537     my ($c) = @_;
538     my @missing = ();
539
540     # set mode on existing filehandles
541     binmode(STDIN, ':utf8');
542
543     my $rc = GetOptions( $c,
544                          'autoscrub|a',
545                          'exception|x=s',
546                          'output|o=s',
547                          'nocollapse|n',
548                          'renumber-from|rf=i',
549                          'original-tag|ot=i',
550                          'renumber-tag|rt=i',
551                          'renumber-subfield|rt=i',
552                          'trash|t=s',
553                          'help|h',
554                        );
555     show_help() unless $rc;
556     show_help() if ($c->{help});
557
558     # defaults
559     $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
560     $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
561     $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
562     $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
563
564     my @keys = keys %{$c};
565     show_help() unless (@ARGV and @keys);
566     #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
567     #  { push @missing, $key unless $c->{$key} }
568     #if (@missing) {
569     #    print "Required option: ", join(', ', @missing), " missing!\n";
570     #    show_help();
571     #}
572 }
573
574 sub show_help {
575     print <<HELP;
576 Usage is: $0 [OPTIONS] <filelist>
577 Options
578   --output     -o  Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
579   --exception  -x  Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)
580 HELP
581 exit;
582 }