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