$recptr -> $ptr
[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                 $ptr = 0;
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                 $ptr = 0;
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     message($msg, 1);
191     print_context();
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_linecontext();
209         }
210     }
211 }
212
213 =head2 buildrecord
214
215 Constructs record arrays from the incoming MARC file and returns them
216 to the driver loop.
217
218 =cut
219
220 sub buildrecord {
221     my $l = '';
222     $l = <MARC> while (defined $l and $l !~ /<record>/);
223     return $l unless defined $l;
224     @record = ($l);
225     %recmeta = ();
226     $conf->{ricount}++;
227
228     until ($l =~ m|</record>|) 
229       { push @record, $l; $l = <MARC>; }
230     push @record, $l;
231     return 1;
232 }
233
234 sub write_record {
235     my ($FH) = @_;
236     my $trash = $conf->{trash};
237
238     $conf->{rocount}++ if ($FH eq $NUMARC);
239     print $FH '<!-- ', $recmeta{explanation}, " -->\n"
240       if(defined $recmeta{explanation});
241
242     # excise unwanted tags
243     if (keys %{$trash} or $conf->{autoscrub}) {
244         my @trimmed = ();
245         my $istrash = 0;
246         for my $line (@record) {
247             if ($istrash) {
248                 $istrash = 0 if $line =~ m|</datafield|;
249                 next;
250             }
251             if ($line =~ m/<datafield tag="(.{3})"/) {
252                 my $tag = $1;
253                 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
254                     $istrash = 1;
255                     next
256                 }
257             }
258             push @trimmed, $line;
259         }
260         @record = @trimmed;
261     }
262
263     # scrub newlines
264     unless ($conf->{nocollapse}) {
265         s/\n// for (@record);
266     }
267
268     # add 903(?) with new record id
269     my $renumber = '';
270     if ($conf->{'renumber-from'}) {
271         $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
272                          '" ind1=" " ind2=" ">',
273                          '<subfield code="', $conf->{'renumber-subfield'}, '">',
274                          $conf->{'renumber-from'}, '</subfield></datafield>');
275         $renumber .= "\n" if $conf->{nocollapse};
276         push @record, $renumber;
277         $conf->{'renumber-from'}++;
278     }
279
280     print $FH @record;
281     print $FH "</record>\n";
282 }
283
284 sub print_context {
285     print "    Tag:",$recmeta{tag}, " Ind1:'",
286       $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'\n";
287     print_linecontext();
288     return 0;
289 }
290
291 sub print_linecontext {
292     my $low = ($ptr - 3 < 0) ? 0 : $ptr - 3;
293     print $OUT '    |', $record[$_] for ($low .. $ptr - 1);
294     print $OUT '==> |', $record[$ptr];
295     print $OUT '    |', $record[$ptr + 1], "\n";
296     return 0;
297 }
298
299 sub message {
300     my ($msg, $new) = @_;
301     print $OUT "\r", ' ' x 72, "\n" if $new;
302     print $OUT "\r$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
303
304 }
305
306 #-----------------------------------------------------------------------------------
307 # command routines
308 #-----------------------------------------------------------------------------------
309
310 sub substitute {
311     my ($line_in, @chunks) = @_;
312
313     my $ofrom = shift @chunks;
314     if ($ofrom =~ /^'/ or !@chunks) {
315         until ($ofrom =~ /'$/)
316           { $ofrom .= join(' ','',shift @chunks) }
317         $ofrom =~ s/^'//; $ofrom =~ s/'$//;
318     }
319     my $to = shift @chunks;
320     if ($to =~ /^'/) {
321         until ($to =~ /'$/ or !@chunks)
322           { $to .= join(' ','',shift @chunks) }
323         $to =~ s/^'//; $to =~ s/'$//;
324     }
325
326     my $from = '';
327     for my $char (split(//,$ofrom)) {
328         $char = "\\" . $char if ($char =~ /\W/);
329         $from = join('', $from, $char);
330     }
331
332     $conf->{prevline} = $record[$ptr];
333     $record[$ptr] =~ s/$from/$to/;
334     print_linecontext();
335     return 0;
336 }
337
338 sub merge_lines {
339     $conf->{prevline} = $record[$ptr];
340     # remove <subfield stuff; extract (probably wrong) subfield code
341     $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
342     # and move to front of line
343     $record[$ptr] = join(' ', $1 , $record[$ptr]);
344     # tear off trailing subfield tag from preceeding line
345     $record[$ptr - 1] =~ s|</subfield>\n||;
346     # join current line onto preceeding line
347     $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
348     # erase current line
349     my @a = @record[0 .. $ptr - 1];
350     my @b = @record[$ptr + 1 .. $#record];
351     @record = (@a, @b);
352     # move record pointer to previous line
353     prev_line();
354     print_linecontext();
355     return 0;
356 }
357
358 sub flip_line {
359     my $temp = $record[$ptr];
360     $record[$ptr] = $conf->{prevline};
361     $conf->{prevline} = $temp;
362     print_linecontext();
363     return 0;
364 }
365
366 sub kill_line {
367     $conf->{prevline} = $record[$ptr];
368     my @a = @record[0 .. $ptr - 1];
369     my @b = @record[$ptr + 1 .. $#record];
370     @record = (@a, @b);
371     print_linecontext();
372     return 0;
373 }
374
375 sub yank_line {
376     my @a = @record[0 .. $ptr - 1];
377     my @b = @record[$ptr .. $#record];
378     @record = (@a, $conf->{prevline}, @b);
379     print_linecontext();
380     return 0;
381 }
382
383 sub show_original {
384     my ($line_in) = @_;
385     print $OUT "\n", $conf->{origline}, "\n";
386     return 0;
387 }
388
389 sub dump_record {
390     my ($line_in, @explanation) = @_;
391     $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
392     write_record($EXMARC);
393     return 1;
394 }
395
396 sub next_line {
397     $ptr++;
398     print_linecontext();
399     return 0;
400 }
401
402 sub prev_line {
403     $ptr--;
404     print_linecontext();
405     return 0;
406 }
407
408 sub commit_edit { return 1 }
409
410 sub help {
411 print $OUT <<HELP;
412
413 Type a replacement for the indicated line, or enter a command.
414
415 Commands: c  Show record context again ('C' for brief context)
416           k  Kill indicated line (remove from record)
417           m  Merge indicated line with previous line
418           o  Show original line
419           s  Substitute ARG1 for ARG2 in indicated line
420           t  Commit changes and resume stream edit
421           x  Write this record to the exception file instead of output
422           q  Quit
423
424 HELP
425 return 0;
426 }
427
428 sub quit { exit }
429
430 #-----------------------------------------------------------------------------------
431 # populate_trash
432 #-----------------------------------------------------------------------------------
433 # defined a domain-specific language for specifying MARC tags to be dropped from
434 # records during processing. it is line oriented, and is specified as follows:
435 #
436 # each line may specify any number of tags to be included, either singly (\d{1,3})
437 # or as a range (\d{1,3}\.\.\d{1,3}
438 #
439 # if a single number is given, it must be between '000' and '999', inclusive.
440 #
441 # ranges obey the previous rule, and also the first number of the range must be less
442 # than the second number
443 #
444 # finally, any single range in a line may be followed by the keyword 'except'. every
445 # number or range after 'except' is excluded from the range specified. all these
446 # numbers must actually be within the range.
447 #
448 # specifying a tag twice is an error, to help prevent typos
449
450 sub populate_trash {
451     print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
452     open TRASH, '<', $conf->{trash}
453       or die "Can't open trash tags file!\n";
454     while (<TRASH>) {
455         my $lastwasrange = 0;
456         my %lastrange = ( high => 0, low => 0);
457         my $except = 0;
458
459         my @chunks = split /\s+/;
460         while (my $chunk = shift @chunks) {
461
462             # single values
463             if ($chunk =~ /^\d{1,3}$/) {
464                 trash_add($chunk, $except);
465                 $lastwasrange = 0;
466                 next;
467             }
468
469             # ranges
470             if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
471                 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
472                 $lastwasrange = 1;
473                 %lastrange = (low => $low, high => $high)
474                   unless $except;
475                 next;
476             }
477
478             # 'except'
479             if ($chunk eq 'except') {
480                 die "Keyword 'except' can only follow a range (line $.)\n"
481                   unless $lastwasrange;
482                 die "Keyword 'except' may only occur once per line (line $.)\n"
483                   if $except;
484                 $except = 1;
485                 next;
486             }
487
488             die "Unknown chunk $chunk in .trashtags file (line $.)\n";
489         }
490     }
491
492     # remove original id sequence tag from trash hash if we know it
493     trash_add($conf->{'original-tag'}, 1)
494       if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
495 }
496
497 sub trash_add_range {
498     my ($chunk, $except, $range) = @_;
499     my ($low,$high) = split /\.\./, $chunk;
500     die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
501       if ($low > $high);
502     if ($except) {
503         die "Exception ranges must be within last addition range (line $.)\n"
504           if ($low < $range->{low} or $high > $range->{high});
505     }
506     for my $tag ($low..$high) {
507         trash_add($tag, $except)
508     }
509     return $low, $high;
510 }
511
512 sub trash_add {
513     my ($tag, $except) = @_;
514     my $trash = $conf->{trash};
515
516     die "Trash values must be valid tags (000-999)\n"
517       unless ($tag >= 0 and $tag <= 999);
518
519     if ($except) {
520         delete $trash->{$tag};
521     } else {
522         die "Trash tag '$tag' specified twice (line $.)\n"
523           if $trash->{$tag};
524         $trash->{$tag} = 1;
525     }
526 }
527
528 #-----------------------------------------------------------------------
529
530 =head2 initialize
531
532 Performs boring script initialization. Handles argument parsing,
533 mostly.
534
535 =cut
536
537 sub initialize {
538     my ($c) = @_;
539     my @missing = ();
540
541     # set mode on existing filehandles
542     binmode(STDIN, ':utf8');
543
544     my $rc = GetOptions( $c,
545                          'autoscrub|a',
546                          'exception|x=s',
547                          'output|o=s',
548                          'nocollapse|n',
549                          'renumber-from|rf=i',
550                          'original-tag|ot=i',
551                          'renumber-tag|rt=i',
552                          'renumber-subfield|rt=i',
553                          'trash|t=s',
554                          'help|h',
555                        );
556     show_help() unless $rc;
557     show_help() if ($c->{help});
558
559     # defaults
560     $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
561     $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
562     $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
563     $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
564
565     my @keys = keys %{$c};
566     show_help() unless (@ARGV and @keys);
567     #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
568     #  { push @missing, $key unless $c->{$key} }
569     #if (@missing) {
570     #    print "Required option: ", join(', ', @missing), " missing!\n";
571     #    show_help();
572     #}
573 }
574
575 sub show_help {
576     print <<HELP;
577 Usage is: $0 [OPTIONS] <filelist>
578 Options
579   --output     -o  Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
580   --exception  -x  Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)
581 HELP
582 exit;
583 }