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