continues work
[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             $record[$recptr] = "$line\n";
188             print_linecontext();
189         }
190     }
191 }
192
193 =head2 buildrecord
194
195 Constructs record arrays from the incoming MARC file and returns them
196 to the driver loop.
197
198 =cut
199
200 sub buildrecord {
201     my $l = <MARC>;
202     return $l unless defined $l;
203
204     $l = <MARC> until ($l =~ /<record>/);
205     @record = ($l);
206     %recmeta = ();
207     $conf->{ricount}++;
208
209     until ($l =~ m|</record>|) 
210       { push @record, $l; $l = <MARC>; }
211     push @record, $l;
212     return 1;
213 }
214
215 sub write_record {
216     my ($FH) = @_;
217     my $trash = $conf->{trash};
218
219     $conf->{rocount}++ if ($FH eq $NUMARC);
220     print $FH '<!-- ', $recmeta{explanation}, " -->\n"
221       if(defined $recmeta{explanation});
222
223     # excise unwanted tags
224     if (keys %{$trash} or $conf->{autoscrub}) {
225         my @trimmed = ();
226         my $istrash = 0;
227         for my $line (@record) {
228             if ($istrash) {
229                 $istrash = 0 if $line =~ m|</datafield|;
230                 next;
231             }
232             if ($line =~ m/<datafield tag="(.{3})"/) {
233                 my $tag = $1;
234                 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
235                     $istrash = 1;
236                     next
237                 }
238             }
239             push @trimmed, $line;
240         }
241         @record = @trimmed;
242     }
243
244     # scrub newlines
245     unless ($conf->{nocollapse}) {
246         s/\n// for (@record);
247     }
248
249     # add 903(?) with new record id
250     my $renumber = '';
251     if ($conf->{'renumber-from'}) {
252         $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
253                          '" ind1=" " ind2=" ">',
254                          '<subfield code="', $conf->{'renumber-subfield'}, '">',
255                          $conf->{'renumber-from'}, '</subfield></datafield>');
256         $renumber .= "\n" if $conf->{nocollapse};
257         push @record, $renumber;
258         $conf->{'renumber-from'}++;
259     }
260
261     print $FH @record;
262     print $FH "</record>\n";
263 }
264
265 sub message {
266     my ($msg) = @_;
267     print $OUT "\r", ' ' x 72, "\n";
268     print $OUT "$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
269
270 }
271
272 #-----------------------------------------------------------------------------------
273 # command routines
274 #-----------------------------------------------------------------------------------
275
276 sub substitute {
277     my ($line_in, @chunks) = @_;
278     my $ofrom = shift @chunks;
279     if ($ofrom =~ /^'/ or !@chunks) {
280         until ($ofrom =~ /'$/)
281           { $ofrom .= join(' ','',shift @chunks) }
282         $ofrom =~ s/^'//; $ofrom =~ s/'$//;
283     }
284     my $to = shift @chunks;
285     if ($to =~ /^'/) {
286         until ($to =~ /'$/ or !@chunks)
287           { $to .= join(' ','',shift @chunks) }
288         $to =~ s/^'//; $to =~ s/'$//;
289     }
290
291     my $from = '';
292     for my $char (split(//,$ofrom)) {
293         $char = "\\" . $char if ($char =~ /\W/);
294         $from = join('', $from, $char);
295     }
296     $record[$recptr] =~ s/$from/$to/;
297     print_linecontext();
298     return 0;
299 }
300
301 sub merge_lines {
302     $record[$recptr] =~ s/^\s*<subfield code="(.*?)">//;
303     $record[$recptr] = join(' ', $1 , $record[$recptr]);
304     $record[$recptr - 1] =~ s|<subfield>\n||;
305     $record[$recptr - 1] = join('', $record[$recptr - 1], $record[$recptr]);
306     print_linecontext();
307     return 0;
308 }
309
310 sub kill_line {
311     delete $record[$recptr];
312     print_linecontext();
313     return 0;
314 }
315
316 sub dump_record {
317     my ($line_in, @explanation) = @_;
318     $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
319     write_record($EXMARC);
320     return 1;
321 }
322
323 sub commit_edit { return 1 }
324
325 sub print_context {
326     print " Tag:",$recmeta{tag}, " Ind1:'",
327       $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
328     print_linecontext();
329     return 0;
330 }
331
332 sub print_linecontext {
333     my $low = ($recptr - 3 < 0) ? 0 : $recptr - 3;
334     print $OUT '     ', $record[$_], "\n" for ($low .. $recptr - 1);
335     print $OUT '==> |', $record[$recptr];
336     print $OUT '     ', $record[$recptr + 1], "\n";
337     return 0;
338 }
339
340 sub show_original {
341     my ($line_in) = @_;
342     print $OUT "\n$line_in\n";
343     return 0;
344 }
345
346 sub help {
347 print $OUT <<HELP;
348
349 Type a replacement for the indicated line, or enter a command.
350
351 Commands: c  Show record context again ('C' for brief context)
352           k  Kill indicated line (remove from record)
353           m  Merge indicated line with previous line
354           o  Show original line
355           s  Substitute ARG1 for ARG2 in indicated line
356           t  Commit changes and resume stream edit
357           x  Write this record to the exception file instead of output
358           q  Quit
359
360 HELP
361 return 0;
362 }
363
364 sub quit { exit }
365
366 #-----------------------------------------------------------------------------------
367 # populate_trash
368 #-----------------------------------------------------------------------------------
369 # defined a domain-specific language for specifying MARC tags to be dropped from
370 # records during processing. it is line oriented, and is specified as follows:
371 #
372 # each line may specify any number of tags to be included, either singly (\d{1,3})
373 # or as a range (\d{1,3}\.\.\d{1,3}
374 #
375 # if a single number is given, it must be between '000' and '999', inclusive.
376 #
377 # ranges obey the previous rule, and also the first number of the range must be less
378 # than the second number
379 #
380 # finally, any single range in a line may be followed by the keyword 'except'. every
381 # number or range after 'except' is excluded from the range specified. all these
382 # numbers must actually be within the range.
383 #
384 # specifying a tag twice is an error, to help prevent typos
385
386 sub populate_trash {
387     print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
388     open TRASH, '<', $conf->{trash}
389       or die "Can't open trash tags file!\n";
390     while (<TRASH>) {
391         my $lastwasrange = 0;
392         my %lastrange = ( high => 0, low => 0);
393         my $except = 0;
394
395         my @chunks = split /\s+/;
396         while (my $chunk = shift @chunks) {
397
398             # single values
399             if ($chunk =~ /^\d{1,3}$/) {
400                 trash_add($chunk, $except);
401                 $lastwasrange = 0;
402                 next;
403             }
404
405             # ranges
406             if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
407                 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
408                 $lastwasrange = 1;
409                 %lastrange = (low => $low, high => $high)
410                   unless $except;
411                 next;
412             }
413
414             # 'except'
415             if ($chunk eq 'except') {
416                 die "Keyword 'except' can only follow a range (line $.)\n"
417                   unless $lastwasrange;
418                 die "Keyword 'except' may only occur once per line (line $.)\n"
419                   if $except;
420                 $except = 1;
421                 next;
422             }
423
424             die "Unknown chunk $chunk in .trashtags file (line $.)\n";
425         }
426     }
427
428     # remove original id sequence tag from trash hash if we know it
429     trash_add($conf->{'original-tag'}, 1)
430       if ($conf->{'original-tag'} and $conf->{trash}{ $conf->{'original-tag'} });
431 }
432
433 sub trash_add_range {
434     my ($chunk, $except, $range) = @_;
435     my ($low,$high) = split /\.\./, $chunk;
436     die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
437       if ($low > $high);
438     if ($except) {
439         die "Exception ranges must be within last addition range (line $.)\n"
440           if ($low < $range->{low} or $high > $range->{high});
441     }
442     for my $tag ($low..$high) {
443         trash_add($tag, $except)
444     }
445     return $low, $high;
446 }
447
448 sub trash_add {
449     my ($tag, $except) = @_;
450     my $trash = $conf->{trash};
451
452     die "Trash values must be valid tags (000-999)\n"
453       unless ($tag >= 0 and $tag <= 999);
454
455     if ($except) {
456         delete $trash->{$tag};
457     } else {
458         die "Trash tag '$tag' specified twice (line $.)\n"
459           if $trash->{$tag};
460         $trash->{$tag} = 1;
461     }
462 }
463
464 #-----------------------------------------------------------------------
465
466 =head2 initialize
467
468 Performs boring script initialization. Handles argument parsing,
469 mostly.
470
471 =cut
472
473 sub initialize {
474     my ($c) = @_;
475     my @missing = ();
476
477     # set mode on existing filehandles
478     binmode(STDIN, ':utf8');
479
480     my $rc = GetOptions( $c,
481                          'autoscrub|a',
482                          'exception|x=s',
483                          'output|o=s',
484                          'nocollapse|n',
485                          'renumber-from|rf=i',
486                          'original-tag|ot=i',
487                          'renumber-tag|rt=i',
488                          'renumber-subfield|rt=i',
489                          'trash|t=s',
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 }