improve marc_parses() test
[migration-tools.git] / marc_cleanup
1 #!/usr/bin/perl
2
3 # Copyright 2009-2012, Equinox Software, Inc.
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 require 5.10.0;
20
21 use strict;
22 use warnings;
23
24 use Getopt::Long;
25 use Term::ReadLine;
26 use Equinox::Migration::SimpleTagList;
27
28 my $term = new Term::ReadLine 'yaz-cleanup';
29 my $OUT = $term->OUT || \*STDOUT;
30 binmode STDOUT, ":utf8";
31 binmode $OUT, ":utf8";
32
33 $| = 1;
34
35 # initialization and setup
36 my $c = {};
37 initialize($c);
38
39 # set up files, since everything appears to be in order
40 open MARC, '<:utf8', $c->{marcfile}
41   or die "Can't open input file $!\n";
42 open my $NUMARC, '>:utf8', $c->{output}
43   or die "Can't open output file $!\n";
44 open my $OLD2NEW, '>', 'old2new.map'
45   if ($c->{'renumber-from'} and $c->{'original-tag'});
46 my $EXMARC = 'EX';
47 print $NUMARC "<collection xmlns=\"http://www.loc.gov/MARC21/slim\">\n";
48
49 $c->{totalrecs} = `grep -c '<record' $c->{marcfile}`;
50 chomp $c->{totalrecs};
51 $c->{percent}   = 0;
52
53 my @record;  # current record storage
54 my %recmeta; # metadata about current record
55 my $ptr = 0; # record index pointer
56
57 # this is the dispatch table which drives command selection in
58 # edit(), below
59 my %commands = ( c => \&print_fullcontext,
60                  n => \&next_line,
61                  p => \&prev_line,
62                  '<' => \&widen_window,
63                  '>' => \&narrow_window,
64                  d => \&display_lines,
65                  o => \&insert_original,
66                  k => \&kill_line,
67                  y => \&yank_line,
68                  f => \&flip_line,
69                  m => \&merge_lines,
70                  s => \&substitute,
71                  t => \&commit_edit,
72                  x => \&dump_record,
73                  q => \&quit,
74                  '?' => \&help,
75                  h   => \&help,
76                  help => \&help,
77                );
78
79 my @spinner = qw(- \\ | /);
80 my $sidx = 0;
81
82 while ( buildrecord() ) {
83     unless ($c->{ricount} % 50) {
84         $c->{percent} = int(($c->{ricount} / $c->{totalrecs}) * 100);
85         print "\rWorking (",$c->{percent},"%) ", $spinner[$sidx];
86         $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
87     }
88
89     my $rc = do_automated_cleanups();
90     next if $rc;
91
92     $ptr = 0;
93     until ($ptr == $#record) {
94         # get datafield/tag data if we have it
95         $rc = stow_record_data() if ($c->{'renumber-from'} and $c->{'original-tag'});
96         next if $rc;
97
98         # naked ampersands
99         if ($record[$ptr] =~ /&/ && $record[$ptr] !~ /&\w+?;/)
100           { edit("Naked ampersand"); $ptr= 0; next }
101
102         if ($record[$ptr] =~ /<datafield tag="(.+?)"/) {
103             my $match = $1;
104             # tags must be numeric
105             if ($match =~ /\D/) {
106                 edit("Non-numerics in tag") unless $c->{autoscrub};
107                 next;
108             }
109         }
110
111         # subfields can't be non-alphanumeric
112         if ($record[$ptr] =~ /<subfield code="(.*?)"/) {
113             if ($1 =~ /\P{IsAlnum}/ or $1 eq '') {
114                 edit("Junk in subfield code/Null subfield code");
115                 next;
116             }
117         }
118         # subfields can't be non-alphanumeric
119         if ($record[$ptr] =~ /<subfield code="(\w{2,})"/) {
120             edit("Subfield code larger than 1 char");
121             next;
122         }
123
124         $ptr++;
125     }
126     write_record($NUMARC);
127 }
128 print $NUMARC "</collection>\n";
129 print $OUT "\nDone. ",$c->{ricount}," in; ",$c->{rocount}," dumped          \n";
130
131
132 #-----------------------------------------------------------------------------------
133 # cleanup routines
134 #-----------------------------------------------------------------------------------
135
136 sub do_automated_cleanups {
137     $ptr = 0;
138     until ($ptr == $#record) {
139
140         # catch empty datafield elements
141         if ($record[$ptr] =~ m/<datafield tag="..."/) {
142             if ($record[$ptr + 1] =~ m|</datafield>|) {
143                 my @a = @record[0 .. $ptr - 1];
144                 my @b = @record[$ptr + 2 .. $#record];
145                 @record = (@a, @b);
146                 @a = undef; @b = undef;
147                 message("Empty datafield scrubbed");
148                 $ptr = 0;
149                 next;
150             }
151         }
152         # and quasi-empty subfields
153         if ($record[$ptr] =~ m|<subfield code="(.*?)">(.*?)</sub|) {
154             my $code = $1; my $content = $2;
155             if ($code =~ /\W/ and ($content =~ /\s+/ or $content eq '')) {
156                 my @a = @record[0 .. $ptr - 1];
157                 my @b = @record[$ptr + 1 .. $#record];
158                 @record = (@a, @b);
159                 @a = undef; @b = undef;
160                 message("Empty subfield scrubbed");
161                 $ptr = 0;
162                 next;
163             }
164         }
165         $ptr++;
166     }
167
168     # single-line fixes
169     for $ptr (0 .. $#record) {
170         # pad short leaders
171         if ($record[$ptr] =~ m|<leader>(.+?)</leader>|) {
172             my $leader = $1;
173             if (length $leader < 24) {
174                 $leader .= ' ' x (20 - length($leader));
175                 $leader .= "4500";
176                 $record[$ptr] = "<leader>$leader</leader>\n";
177                 message("Short leader padded");
178             }
179         }
180         if ($record[$ptr] =~ m|<controlfield tag="008">(.+?)</control|) {
181             #pad short 008
182             my $content = $1;
183             if (length $content < 40) {
184                 $content .= ' ' x (40 - length($content));
185                 $record[$ptr] = "<controlfield tag=\"008\">$content</controlfield>\n";
186                 message("Short 008 padded");
187             }
188         }
189
190         # clean misplaced dollarsigns
191         if ($record[$ptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
192             $record[$ptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
193             message("Dollar sign corrected");
194         }
195
196         # excessive trailing whitespace in subfield contents
197         if ($record[$ptr] =~ m|\s{10,}</subfield>|) {
198             $record[$ptr] =~ s|\s{10,}</subfield>|</subfield>|;
199             message("Trailing whitespace trimmed from subfield contents");
200         }
201
202         # automatable subfield maladies
203         $record[$ptr] =~ s/code=" ">c/code="c">/;
204         $record[$ptr] =~ s/code=" ">\$/code="c">\$/;
205     }
206     return 0;
207 }
208
209 sub stow_record_data {
210     # get tag data if we're looking at it
211     my $tag = 0;
212     if ($record[$ptr] =~ m/<(?:control|data)field tag="(.{3})"/) {
213         $recmeta{tag} = $1;
214         $tag = $recmeta{tag};
215         $record[$ptr] =~ m/ind1="(.)"/;
216         $recmeta{ind1} = $1 || '';
217         $record[$ptr] =~ m/ind2="(.)"/;
218         $recmeta{ind2} = $1 || '';
219
220         unless ($tag) {
221             message("Autokill record: no detectable tag");
222             dump_record("No detectable tag") ;
223             return 1;
224         }
225
226         # and since we are looking at a tag, see if it's the original id
227         if ($tag == $c->{'original-tag'}) {
228             my $oid = 0;
229             if ($tag < 10) {
230                 # controlfield
231                 if ($record[$ptr] =~ m|<controlfield tag="$tag">(.+?)</controlfield>|)
232                       { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
233             } elsif ($tag >= 10 and $c->{'original-subfield'}) {
234                 # datafield
235                 my $line = $record[$ptr]; my $lptr = $ptr;
236                 my $osub = $c->{'original-subfield'};
237                 # skim to end of this tag
238                 until ($line =~ m|</datafield>|) {
239                     if ($line =~ /<subfield code="$osub">(.+?)</)
240                       { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
241                     $lptr++;
242                     $line = $record[$lptr];
243                 }
244             } else {
245                 return 0;
246             }
247
248             # didn't find the old id!
249             unless ($oid) {
250                 message("Autokill record: no oldid when old2new mapping requested");
251                 dump_record("No old id found");
252                 return 1;
253             }
254
255             # got it; write to old->new map file
256             if ($c->{'renumber-from'} and $c->{'original-subfield'}) {
257             }
258
259         }
260     }
261     return 0;
262 }
263
264 #-----------------------------------------------------------------------------------
265 # driver routines
266 #-----------------------------------------------------------------------------------
267
268 =head2 edit
269
270 Handles the Term::ReadLine loop
271
272 =cut
273
274 sub edit {
275     my ($msg) = @_;
276
277     return if $c->{trash}->has( $recmeta{tag} );
278     if ( $c->{fullauto} )
279     { dump_record($msg); return }
280
281     $c->{editmsg} = $msg;
282     print_fullcontext();
283
284     # stow original problem line
285     $recmeta{origline} = $record[$ptr];
286
287     while (1) {
288         my $line = $term->readline('marc-cleanup>');
289         my @chunks = split /\s+/, $line;
290
291         # lines with single-character first chunks are commands.
292         # make sure they exist.
293         if (length $chunks[0] == 1) {
294             unless (defined $commands{$chunks[0]}) {
295                 print $OUT "No such command '", $chunks[0], "'\n";
296                 next;
297             }
298         }
299
300         if (defined $commands{$chunks[0]}) {
301             my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
302             last if $term;
303         } else {
304             $recmeta{prevline} = $record[$ptr];
305             $record[$ptr] = "$line\n";
306             print_context();
307         }
308     }
309     # set pointer to top on the way out
310     $ptr = 0;
311 }
312
313 =head2 buildrecord
314
315 Constructs record arrays from the incoming MARC file and returns them
316 to the driver loop.
317
318 =cut
319
320 sub buildrecord {
321     my $l = '';
322     my $istrash = 0;
323     my $trash = $c->{trash};
324
325     $l = <MARC> while (defined $l and $l !~ /<record/);
326     return $l unless defined $l;
327     $c->{ricount}++;
328
329     for (keys %recmeta) { $recmeta{$_} = undef }
330     for (0 .. @record)  { delete $record[$_] }
331
332     my $i = 0;
333     until ($l =~ m|</record>|) {
334         # clean up tags with spaces in them
335         $l =~ s/tag="  /tag="00/g;
336         $l =~ s/tag=" /tag="0/g;
337         $l =~ s/tag="-/tag="0/g;
338         $l =~ s/tag="(\d\d) /tag="0$1/g;
339
340         # excise unwanted tags
341         if ($istrash) {
342             $istrash = 0 if ($l =~ m|</datafield|);
343             $l = <MARC>;
344             next;
345         }
346         if ($l =~ m/<datafield tag="(.{3})"/) {
347             if ($trash->has($1) or ($c->{autoscrub} and $1 =~ /\D/))
348               { $istrash = 1; next }
349         }
350
351         push @record, $l;
352         $l = <MARC>;
353         $i++;
354     }
355
356     # add 903(?) with new record id
357     if ($c->{'renumber-from'}) {
358         $recmeta{nid} = $c->{'renumber-from'};
359         push @record, join('', ' <datafield tag="', $c->{'renumber-tag'},
360                            '" ind1=" " ind2=" "> <subfield code="',
361                            $c->{'renumber-subfield'},
362                            '">',
363                            $recmeta{nid},
364                            "</subfield></datafield>\n");
365         $c->{'renumber-from'}++;
366     }
367     $i++;
368
369     push @record, $l;
370     return 1;
371 }
372
373 sub write_record {
374     my ($FH) = @_;
375
376     if ($FH eq 'EX') {
377         $EXMARC = undef;
378         open $EXMARC, '>:utf8', $c->{exception}
379           or die "Can't open exception file $!\n";
380         $FH = $EXMARC;
381     }
382
383     print $FH '<!-- ', $recmeta{explanation}, " -->\n"
384       if(defined $recmeta{explanation});
385
386     # scrub newlines (unless told not to or writing exception record)
387     unless ($c->{nocollapse} or $FH eq $EXMARC)
388       { s/\n// for (@record) }
389
390     # actually write the record
391     print $FH @record,"\n";
392
393     # increment output record count (if not exception)
394     $c->{rocount}++ if ($FH eq $EXMARC);
395
396     # if we were dumping to exception file, nuke the record and set ptr
397     # to terminate processing loop
398     @record = ('a');
399     $ptr = 0;
400 }
401
402 sub print_fullcontext {
403     print $OUT "\r", ' ' x 72, "\n";
404     print $OUT $c->{editmsg},"\n";
405     print $OUT "\r    Tag:",$recmeta{tag}, " Ind1:'",
406       $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
407     print $OUT " @ ", $c->{ricount}, "/", $c->{totalrecs};
408     print_context();
409     return 0;
410 }
411
412 sub print_context {
413     my $upper = int($c->{window} / 2) + 1;
414     my $lower = int($c->{window} / 2) - 1;
415     my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
416     my $stop  = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
417     print $OUT "\n";
418     print $OUT '    |', $record[$_] for ($start .. $ptr - 1);
419     print $OUT '==> |', $record[$ptr];
420     print $OUT '    |', $record[$_] for ($ptr + 1 .. $stop);
421     print $OUT "\n";
422     return 0;
423 }
424
425 sub message {
426     my ($msg) = @_;
427     print $OUT "\r$msg at ",$c->{ricount},"/",$c->{totalrecs}, "\n";
428 }
429
430 #-----------------------------------------------------------------------------------
431 # command routines
432 #-----------------------------------------------------------------------------------
433
434 sub substitute {
435     my (@chunks) = @_;
436
437     my $ofrom = shift @chunks;
438     if ($ofrom =~ /^'/) {
439         until ($ofrom =~ /'$/ or !@chunks)
440           { $ofrom .= join(' ','',shift @chunks) }
441         $ofrom =~ s/^'//; $ofrom =~ s/'$//;
442     }
443     my $to = shift @chunks;
444     if ($to =~ /^'/) {
445         until ($to =~ /'$/ or !@chunks)
446           { $to .= join(' ','',shift @chunks) }
447         $to =~ s/^'//; $to =~ s/'$//;
448     }
449
450     my $from = '';
451     for my $char (split(//,$ofrom)) {
452         $char = "\\" . $char if ($char =~ /\W/);
453         $from = join('', $from, $char);
454     }
455
456     $recmeta{prevline} = $record[$ptr];
457     $record[$ptr] =~ s/$from/$to/;
458     $ofrom = undef; $to = undef; $from = undef;
459     print_context();
460     return 0;
461 }
462
463 sub merge_lines {
464     $recmeta{prevline} = $record[$ptr];
465     # remove <subfield stuff; extract (probably wrong) subfield code
466     $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
467     # and move to front of line
468     $record[$ptr] = join(' ', $1 , $record[$ptr]);
469     # tear off trailing subfield tag from preceeding line
470     $record[$ptr - 1] =~ s|</subfield>\n||;
471     # join current line onto preceeding line
472     $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
473     # erase current line
474     my @a = @record[0 .. $ptr - 1];
475     my @b = @record[$ptr + 1 .. $#record];
476     @record = (@a, @b);
477     # move record pointer to previous line
478     prev_line();
479     print_context();
480     return 0;
481 }
482
483 sub flip_line {
484     unless ($recmeta{prevline})
485       { print $OUT "No previously edited line to flip\n"; return }
486     my $temp = $record[$ptr];
487     $record[$ptr] = $recmeta{prevline};
488     $recmeta{prevline} = $temp;
489     $temp = undef;
490     print_context();
491     return 0;
492 }
493
494 sub kill_line {
495     $recmeta{killline} = $record[$ptr];
496     my @a = @record[0 .. $ptr - 1];
497     my @b = @record[$ptr + 1 .. $#record];
498     @record = (@a, @b);
499     @a = undef; @b = undef;
500     print_context();
501     return 0;
502 }
503
504 sub yank_line {
505     unless ($recmeta{killline})
506       { print $OUT "No killed line to yank\n"; return }
507     my @a = @record[0 .. $ptr - 1];
508     my @b = @record[$ptr .. $#record];
509     @record = (@a, $c->{killline}, @b);
510     @a = undef; @b = undef;
511     print_context();
512     return 0;
513 }
514
515 sub insert_original {
516     $record[$ptr] = $recmeta{origline};
517     print_context();
518     return 0;
519 }
520
521 sub display_lines {
522     print $OUT "\nOrig. edit line  :", $recmeta{origline};
523     print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
524     print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
525     print $OUT "\n";
526     return 0;
527 }
528
529 sub dump_record {
530     my (@explanation) = @_;
531     $recmeta{explanation} = join(' ', 'DUMPING RECORD: Tag', $recmeta{tag}, @explanation);
532     message( $recmeta{explanation} );
533     write_record($EXMARC);
534     return 1;
535 }
536
537 sub next_line {
538     $ptr++ unless ($ptr == $#record);;
539     print_context();
540     return 0;
541 }
542
543 sub prev_line {
544     $ptr-- unless ($ptr == 0);
545     print_context();
546     return 0;
547 }
548
549 sub commit_edit { return 1 }
550
551 sub widen_window {
552     if ($c->{window} == 15)
553       { print $OUT "Window can't be bigger than 15 lines\n"; return }
554     $c->{window} += 2;
555     print_context;
556 }
557
558 sub narrow_window {
559     if ($c->{window} == 5)
560       { print $OUT "Window can't be smaller than 5 lines\n"; return }
561     $c->{window} -= 2;
562     print_context;
563 }
564
565 sub help {
566 print $OUT <<HELP;
567 Type a replacement for the indicated line, or enter a command.
568
569 DISPLAY COMMANDS             | LINE AUTO-EDIT COMMANDS
570 <  Expand context window     | k  Kill current line
571 >  Contract context window   | y  Yank last killed line
572 p  Move pointer to prev line | m  Merge current line into preceding line
573 n  Move pointer to next line | o  Insert original line
574 c  Print line context        | f  Flip current line and last edited line
575 d  Print current saved lines |
576 -----------------------------+-------------------------------------------
577 s  Subtitute; replace ARG1 in current line with ARG2. If either ARG
578    contains spaces, it must be single-quoted
579 t  Commit changes and resume automated operations
580 x  Dump record to exception file
581 q  Quit
582
583 HELP
584 return 0;
585 }
586
587 sub quit { exit }
588
589 #-----------------------------------------------------------------------
590
591 =head2 initialize
592
593 Performs boring script initialization. Handles argument parsing,
594 mostly.
595
596 =cut
597
598 sub initialize {
599     my ($c) = @_;
600     my @missing = ();
601
602     # set mode on existing filehandles
603     binmode(STDIN, ':utf8');
604
605     my $rc = GetOptions( $c,
606                          'autoscrub|a',
607                          'fullauto',
608                          'exception|x=s',
609                          'output|o=s',
610                          'marcfile|m=s',
611                          'prefix|p=s',
612                          'nocollapse|n',
613                          'renumber-from|rf=i',
614                          'renumber-tag|rt=i',
615                          'renumber-subfield|rs=s',
616                          'original-tag|ot=i',
617                          'original-subfield|os=s',
618                          'script',
619                          'no-strip9',
620                          'trashfile|t=s',
621                          'trashhelp',
622                          'help|h',
623                        );
624     show_help() unless $rc;
625     show_help() if ($c->{help});
626     show_trashhelp() if ($c->{trashhelp});
627
628     # defaults
629     my $pfx = defined($c->{prefix}) ? $c->{prefix} : "bibs";
630     $c->{ricount} = 0;
631     $c->{rocount} = 0;
632     $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
633     $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
634     $c->{window} = 9;
635     if ($c->{prefix}) {
636         $c->{output} = join('.',$c->{prefix},'clean','marc','xml')
637           unless $c->{output};
638         $c->{exception} = join('.',$c->{prefix},'exception','marc','xml')
639           unless $c->{exception};
640         $c->{marcfile} = $c->{prefix} . '.marc.xml'
641           unless $c->{marcfile};
642     }
643     show_help() unless ($c->{marcfile} and $c->{output});
644
645     if ($c->{trashfile}) {
646         $c->{trash} = Equinox::Migration::SimpleTagList->new(file => $c->{trashfile})
647     } else {
648         $c->{trash} = Equinox::Migration::SimpleTagList->new;
649     }
650     # autotrash 901, 903 unless no strip-nines
651     unless ($c->{'no-strip9'}) {
652         $c->{trash}->add_tag(901);
653         $c->{trash}->add_tag(903);
654     }
655     # remove original id sequence tag from trash hash if we know it
656     $c->{trash}->remove_tag($c->{'original-tag'})
657       if ( $c->{'original-tag'} and $c->{trash}->has($c->{'original-tag'}) );
658 }
659
660 sub show_help {
661     print <<HELP;
662 Usage is: marc_cleanup [OPTIONS] <filelist>
663 Options
664   --output     -o  Cleaned MARCXML output filename
665   --exception  -x  Exception (dumped records) MARCXML filename
666        or
667   --prefix=<PREFIX>    -p  Shared prefix for output/exception files. Will produce
668                            PREFIX.clean.marc.xml and PREFIX.exception.marc.xml
669
670   --marcfile  -m  Input filename. Defaults to PREFIX.marc.xml
671
672   --renumber-from     -rf  Begin renumbering id sequence with this number
673   --renumber-tag      -rt  Tag to use in renumbering (default: 903)
674   --renumber-subfield -rs  Subfield code to use in renumbering (default: a)
675   --original-tag      -ot  Original id tag; will be kept in output even if
676                            it appears in the trash file
677   --original-subfield -os  Original id subfield code. If this is specified
678                            and renumbering is in effect, an old-to-new mapping
679                            file (old2new.map) will be generated.
680
681   --autoscrub  -a  Automatically remove non-numeric tags in data
682   --nocollapse -n  Don't compress records to one line on output
683   --no-strip9      Don't autoremove 901/903 tags in data
684   --trashfile  -t  File containing trash tag data (see --trashhelp)
685
686   --fullauto       No manual edits. All problematic records dumped to
687                    exception file.
688
689 HELP
690 exit;
691 }
692
693 sub show_trashhelp {
694     print <<HELP;
695 See
696
697 http://intra.lan.hq.esilibrary.com/dokuwiki/doku.php?id=migration:tag_files
698
699 for tag file syntax information.
700 HELP
701 exit;
702 }