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