add more copyright and license statements
[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         return $rc 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         # automatable subfield maladies
197         $record[$ptr] =~ s/code=" ">c/code="c">/;
198         $record[$ptr] =~ s/code=" ">\$/code="c">\$/;
199     }
200     return 0;
201 }
202
203 sub stow_record_data {
204     # get tag data if we're looking at it
205     my $tag = 0;
206     if ($record[$ptr] =~ m/<(?:control|data)field tag="(.{3})"/) {
207         $recmeta{tag} = $1;
208         $tag = $recmeta{tag};
209         $record[$ptr] =~ m/ind1="(.)"/;
210         $recmeta{ind1} = $1 || '';
211         $record[$ptr] =~ m/ind2="(.)"/;
212         $recmeta{ind2} = $1 || '';
213
214         unless ($tag) {
215             message("Autokill record: no detectable tag");
216             dump_record("No detectable tag") ;
217             return 1;
218         }
219
220         # and since we are looking at a tag, see if it's the original id
221         if ($tag == $c->{'original-tag'}) {
222             my $oid = 0;
223             if ($tag < 10) {
224                 # controlfield
225                 if ($record[$ptr] =~ m|<controlfield tag="$tag">(.+?)</controlfield>|)
226                       { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
227             } elsif ($tag >= 10 and $c->{'original-subfield'}) {
228                 # datafield
229                 my $line = $record[$ptr]; my $lptr = $ptr;
230                 my $osub = $c->{'original-subfield'};
231                 # skim to end of this tag
232                 until ($line =~ m|</datafield>|) {
233                     if ($line =~ /<subfield code="$osub">(.+?)</)
234                       { $oid = $1; print $OLD2NEW "$oid\t", $recmeta{nid}, "\n" }
235                     $lptr++;
236                     $line = $record[$lptr];
237                 }
238             } else {
239                 return 0;
240             }
241
242             # didn't find the old id!
243             unless ($oid) {
244                 message("Autokill record: no oldid when old2new mapping requested");
245                 dump_record("No old id found");
246                 return 1;
247             }
248
249             # got it; write to old->new map file
250             if ($c->{'renumber-from'} and $c->{'original-subfield'}) {
251             }
252
253         }
254     }
255     return 0;
256 }
257
258 #-----------------------------------------------------------------------------------
259 # driver routines
260 #-----------------------------------------------------------------------------------
261
262 =head2 edit
263
264 Handles the Term::ReadLine loop
265
266 =cut
267
268 sub edit {
269     my ($msg) = @_;
270
271     return if $c->{trash}->has( $recmeta{tag} );
272     if ( $c->{fullauto} )
273     { dump_record($msg); return }
274
275     $c->{editmsg} = $msg;
276     print_fullcontext();
277
278     # stow original problem line
279     $recmeta{origline} = $record[$ptr];
280
281     while (1) {
282         my $line = $term->readline('marc-cleanup>');
283         my @chunks = split /\s+/, $line;
284
285         # lines with single-character first chunks are commands.
286         # make sure they exist.
287         if (length $chunks[0] == 1) {
288             unless (defined $commands{$chunks[0]}) {
289                 print $OUT "No such command '", $chunks[0], "'\n";
290                 next;
291             }
292         }
293
294         if (defined $commands{$chunks[0]}) {
295             my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
296             last if $term;
297         } else {
298             $recmeta{prevline} = $record[$ptr];
299             $record[$ptr] = "$line\n";
300             print_context();
301         }
302     }
303     # set pointer to top on the way out
304     $ptr = 0;
305 }
306
307 =head2 buildrecord
308
309 Constructs record arrays from the incoming MARC file and returns them
310 to the driver loop.
311
312 =cut
313
314 sub buildrecord {
315     my $l = '';
316     my $istrash = 0;
317     my $trash = $c->{trash};
318
319     $l = <MARC> while (defined $l and $l !~ /<record>/);
320     return $l unless defined $l;
321     $c->{ricount}++;
322
323     for (keys %recmeta) { $recmeta{$_} = undef }
324     for (0 .. @record)  { delete $record[$_] }
325
326     my $i = 0;
327     until ($l =~ m|</record>|) {
328         # clean up tags with spaces in them
329         $l =~ s/tag="  /tag="00/g;
330         $l =~ s/tag=" /tag="0/g;
331         $l =~ s/tag="-/tag="0/g;
332         $l =~ s/tag="(\d\d) /tag="0$1/g;
333
334         # excise unwanted tags
335         if ($istrash) {
336             $istrash = 0 if ($l =~ m|</datafield|);
337             $l = <MARC>;
338             next;
339         }
340         if ($l =~ m/<datafield tag="(.{3})"/) {
341             if ($trash->has($1) or ($c->{autoscrub} and $1 =~ /\D/))
342               { $istrash = 1; next }
343         }
344
345         push @record, $l;
346         $l = <MARC>;
347         $i++;
348     }
349
350     # add 903(?) with new record id
351     if ($c->{'renumber-from'}) {
352         $recmeta{nid} = $c->{'renumber-from'};
353         push @record, join('', ' <datafield tag="', $c->{'renumber-tag'},
354                            '" ind1=" " ind2=" "> <subfield code="',
355                            $c->{'renumber-subfield'},
356                            '">',
357                            $recmeta{nid},
358                            "</subfield></datafield>\n");
359         $c->{'renumber-from'}++;
360     }
361     $i++;
362
363     push @record, $l;
364     return 1;
365 }
366
367 sub write_record {
368     my ($FH) = @_;
369
370     if ($FH eq 'EX') {
371         $EXMARC = undef;
372         open $EXMARC, '>:utf8', $c->{exception}
373           or die "Can't open exception file $!\n";
374         $FH = $EXMARC;
375     }
376
377     print $FH '<!-- ', $recmeta{explanation}, " -->\n"
378       if(defined $recmeta{explanation});
379
380     # scrub newlines (unless told not to or writing exception record)
381     unless ($c->{nocollapse} or $FH eq $EXMARC)
382       { s/\n// for (@record) }
383
384     # actually write the record
385     print $FH @record,"\n";
386
387     # increment output record count (if not exception)
388     $c->{rocount}++ if ($FH eq $EXMARC);
389
390     # if we were dumping to exception file, nuke the record and set ptr
391     # to terminate processing loop
392     @record = ('a');
393     $ptr = 0;
394 }
395
396 sub print_fullcontext {
397     print $OUT "\r", ' ' x 72, "\n";
398     print $OUT $c->{editmsg},"\n";
399     print $OUT "\r    Tag:",$recmeta{tag}, " Ind1:'",
400       $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
401     print $OUT " @ ", $c->{ricount}, "/", $c->{totalrecs};
402     print_context();
403     return 0;
404 }
405
406 sub print_context {
407     my $upper = int($c->{window} / 2) + 1;
408     my $lower = int($c->{window} / 2) - 1;
409     my $start = ($ptr - $upper < 0) ? 0 : $ptr - $upper;
410     my $stop  = ($ptr + $lower > $#record) ? $#record : $ptr + $lower;
411     print $OUT "\n";
412     print $OUT '    |', $record[$_] for ($start .. $ptr - 1);
413     print $OUT '==> |', $record[$ptr];
414     print $OUT '    |', $record[$_] for ($ptr + 1 .. $stop);
415     print $OUT "\n";
416     return 0;
417 }
418
419 sub message {
420     my ($msg) = @_;
421     print $OUT "\r$msg at ",$c->{ricount},"/",$c->{totalrecs}, "\n";
422 }
423
424 #-----------------------------------------------------------------------------------
425 # command routines
426 #-----------------------------------------------------------------------------------
427
428 sub substitute {
429     my (@chunks) = @_;
430
431     my $ofrom = shift @chunks;
432     if ($ofrom =~ /^'/) {
433         until ($ofrom =~ /'$/ or !@chunks)
434           { $ofrom .= join(' ','',shift @chunks) }
435         $ofrom =~ s/^'//; $ofrom =~ s/'$//;
436     }
437     my $to = shift @chunks;
438     if ($to =~ /^'/) {
439         until ($to =~ /'$/ or !@chunks)
440           { $to .= join(' ','',shift @chunks) }
441         $to =~ s/^'//; $to =~ s/'$//;
442     }
443
444     my $from = '';
445     for my $char (split(//,$ofrom)) {
446         $char = "\\" . $char if ($char =~ /\W/);
447         $from = join('', $from, $char);
448     }
449
450     $recmeta{prevline} = $record[$ptr];
451     $record[$ptr] =~ s/$from/$to/;
452     $ofrom = undef; $to = undef; $from = undef;
453     print_context();
454     return 0;
455 }
456
457 sub merge_lines {
458     $recmeta{prevline} = $record[$ptr];
459     # remove <subfield stuff; extract (probably wrong) subfield code
460     $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
461     # and move to front of line
462     $record[$ptr] = join(' ', $1 , $record[$ptr]);
463     # tear off trailing subfield tag from preceeding line
464     $record[$ptr - 1] =~ s|</subfield>\n||;
465     # join current line onto preceeding line
466     $record[$ptr - 1] = join('', $record[$ptr - 1], $record[$ptr]);
467     # erase current line
468     my @a = @record[0 .. $ptr - 1];
469     my @b = @record[$ptr + 1 .. $#record];
470     @record = (@a, @b);
471     # move record pointer to previous line
472     prev_line();
473     print_context();
474     return 0;
475 }
476
477 sub flip_line {
478     unless ($recmeta{prevline})
479       { print $OUT "No previously edited line to flip\n"; return }
480     my $temp = $record[$ptr];
481     $record[$ptr] = $recmeta{prevline};
482     $recmeta{prevline} = $temp;
483     $temp = undef;
484     print_context();
485     return 0;
486 }
487
488 sub kill_line {
489     $recmeta{killline} = $record[$ptr];
490     my @a = @record[0 .. $ptr - 1];
491     my @b = @record[$ptr + 1 .. $#record];
492     @record = (@a, @b);
493     @a = undef; @b = undef;
494     print_context();
495     return 0;
496 }
497
498 sub yank_line {
499     unless ($recmeta{killline})
500       { print $OUT "No killed line to yank\n"; return }
501     my @a = @record[0 .. $ptr - 1];
502     my @b = @record[$ptr .. $#record];
503     @record = (@a, $c->{killline}, @b);
504     @a = undef; @b = undef;
505     print_context();
506     return 0;
507 }
508
509 sub insert_original {
510     $record[$ptr] = $recmeta{origline};
511     print_context();
512     return 0;
513 }
514
515 sub display_lines {
516     print $OUT "\nOrig. edit line  :", $recmeta{origline};
517     print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
518     print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
519     print $OUT "\n";
520     return 0;
521 }
522
523 sub dump_record {
524     my (@explanation) = @_;
525     $recmeta{explanation} = join(' ', 'DUMPING RECORD: Tag', $recmeta{tag}, @explanation);
526     message( $recmeta{explanation} );
527     write_record($EXMARC);
528     return 1;
529 }
530
531 sub next_line {
532     $ptr++ unless ($ptr == $#record);;
533     print_context();
534     return 0;
535 }
536
537 sub prev_line {
538     $ptr-- unless ($ptr == 0);
539     print_context();
540     return 0;
541 }
542
543 sub commit_edit { return 1 }
544
545 sub widen_window {
546     if ($c->{window} == 15)
547       { print $OUT "Window can't be bigger than 15 lines\n"; return }
548     $c->{window} += 2;
549     print_context;
550 }
551
552 sub narrow_window {
553     if ($c->{window} == 5)
554       { print $OUT "Window can't be smaller than 5 lines\n"; return }
555     $c->{window} -= 2;
556     print_context;
557 }
558
559 sub help {
560 print $OUT <<HELP;
561 Type a replacement for the indicated line, or enter a command.
562
563 DISPLAY COMMANDS             | LINE AUTO-EDIT COMMANDS
564 <  Expand context window     | k  Kill current line
565 >  Contract context window   | y  Yank last killed line
566 p  Move pointer to prev line | m  Merge current line into preceding line
567 n  Move pointer to next line | o  Insert original line
568 c  Print line context        | f  Flip current line and last edited line
569 d  Print current saved lines |
570 -----------------------------+-------------------------------------------
571 s  Subtitute; replace ARG1 in current line with ARG2. If either ARG
572    contains spaces, it must be single-quoted
573 t  Commit changes and resume automated operations
574 x  Dump record to exception file
575 q  Quit
576
577 HELP
578 return 0;
579 }
580
581 sub quit { exit }
582
583 #-----------------------------------------------------------------------
584
585 =head2 initialize
586
587 Performs boring script initialization. Handles argument parsing,
588 mostly.
589
590 =cut
591
592 sub initialize {
593     my ($c) = @_;
594     my @missing = ();
595
596     # set mode on existing filehandles
597     binmode(STDIN, ':utf8');
598
599     my $rc = GetOptions( $c,
600                          'autoscrub|a',
601                          'fullauto',
602                          'exception|x=s',
603                          'output|o=s',
604                          'marcfile|m=s',
605                          'prefix|p=s',
606                          'nocollapse|n',
607                          'renumber-from|rf=i',
608                          'renumber-tag|rt=i',
609                          'renumber-subfield|rs=s',
610                          'original-tag|ot=i',
611                          'original-subfield|os=s',
612                          'script',
613                          'no-strip9',
614                          'trashfile|t=s',
615                          'trashhelp',
616                          'help|h',
617                        );
618     show_help() unless $rc;
619     show_help() if ($c->{help});
620     show_trashhelp() if ($c->{trashhelp});
621
622     # defaults
623     my $pfx = defined($c->{prefix}) ? $c->{prefix} : "bibs";
624     $c->{ricount} = 0;
625     $c->{rocount} = 0;
626     $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
627     $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
628     $c->{window} = 9;
629     if ($c->{prefix}) {
630         $c->{output} = join('.',$c->{prefix},'clean','marc','xml')
631           unless $c->{output};
632         $c->{exception} = join('.',$c->{prefix},'exception','marc','xml')
633           unless $c->{exception};
634         $c->{marcfile} = $c->{prefix} . '.marc.xml'
635           unless $c->{marcfile};
636     }
637     show_help() unless ($c->{marcfile} and $c->{output});
638
639     if ($c->{trashfile}) {
640         $c->{trash} = Equinox::Migration::SimpleTagList->new(file => $c->{trashfile})
641     } else {
642         $c->{trash} = Equinox::Migration::SimpleTagList->new;
643     }
644     # autotrash 901, 903 unless no strip-nines
645     unless ($c->{'no-strip9'}) {
646         $c->{trash}->add_tag(901);
647         $c->{trash}->add_tag(903);
648     }
649     # remove original id sequence tag from trash hash if we know it
650     $c->{trash}->remove_tag($c->{'original-tag'})
651       if ( $c->{'original-tag'} and $c->{trash}->has($c->{'original-tag'}) );
652 }
653
654 sub show_help {
655     print <<HELP;
656 Usage is: marc_cleanup [OPTIONS] <filelist>
657 Options
658   --output     -o  Cleaned MARCXML output filename
659   --exception  -x  Exception (dumped records) MARCXML filename
660        or
661   --prefix=<PREFIX>    -p  Shared prefix for output/exception files. Will produce
662                            PREFIX.clean.marc.xml and PREFIX.exception.marc.xml
663
664   --marcfile  -m  Input filename. Defaults to PREFIX.marc.xml
665
666   --renumber-from     -rf  Begin renumbering id sequence with this number
667   --renumber-tag      -rt  Tag to use in renumbering (default: 903)
668   --renumber-subfield -rs  Subfield code to use in renumbering (default: a)
669   --original-tag      -ot  Original id tag; will be kept in output even if
670                            it appears in the trash file
671   --original-subfield -os  Original id subfield code. If this is specified
672                            and renumbering is in effect, an old-to-new mapping
673                            file (old2new.map) will be generated.
674
675   --autoscrub  -a  Automatically remove non-numeric tags in data
676   --nocollapse -n  Don't compress records to one line on output
677   --no-strip9      Don't autoremove 901/903 tags in data
678   --trashfile  -t  File containing trash tag data (see --trashhelp)
679
680   --fullauto       No manual edits. All problematic records dumped to
681                    exception file.
682
683 HELP
684 exit;
685 }
686
687 sub show_trashhelp {
688     print <<HELP;
689 See
690
691 http://intra.lan.hq.esilibrary.com/dokuwiki/doku.php?id=migration:tag_files
692
693 for tag file syntax information.
694 HELP
695 exit;
696 }