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