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