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