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