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