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