utility script to prepare a file of MARCXML records for fingerprinter
[migration-tools.git] / extract_holdings
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 use strict;
20 use warnings;
21
22 use Getopt::Long;
23 use Equinox::Migration::MapDrivenMARCXMLProc 1.005;
24 use Equinox::Migration::MARCXMLSampler;
25
26 my $VERSION = '1.001';
27
28 =pod
29
30 TODO
31
32   * Have detail mode report on number of subfields per datafield
33
34 =cut
35
36 my $c = initialize();
37 $| = 1;
38
39 # run samples if we've been asked for them
40 run_samples($c) if ($c->{sample} or $c->{samplemap} or $c->{samplestr});
41 extract_holdings($c) if ($c->{map});
42 print "\n";
43
44 #--------------------------
45
46 sub extract_holdings {
47     my ($c) = @_;
48     print "Parsing records for extraction:\n";
49     my $m = Equinox::Migration::MapDrivenMARCXMLProc->new( marcfile => $c->{marcfile},
50                                                            mapfile  => $c->{map},
51                                                            verbose  => 1,
52                                                          );
53
54     print "Writing holdings to output file(s)...\n";
55     # open main holdings file
56     open HOLDINGS, '>', ($c->{prefix} . "-HOLDINGS.pg");
57     # create multi files
58     my $multis = $m->get_multis;
59     my %MULTIFILE = ();
60     for my $t ( keys %{$multis} ) {
61         for my $s ( keys %{$multis->{$t}}) 
62           { open my $fh, ">", ($c->{prefix} . "-HOLDINGS-MULT-$t$s.pg"); $MULTIFILE{"$t$s"} = $fh }
63     }
64
65     my $i = 0; # record counter
66     my $j = 0; # holdings counter
67
68     while (  $m->{data}{recs}[$i] ) {
69         print HOLDINGS "BEGIN;\n\negid, hseq, " unless $j;
70         my $rec = $m->{data}{recs}[$i];
71         my $k = 0; # holding-within-record pointer
72
73         for my $holdidx ( @{ $rec->{tmap}{ $c->{holdings} } } ) {
74             # for each holdings tag in the record...
75             my $tagid = $rec->{tags}[$holdidx]{tag};
76             $k++;
77
78             my @out = ();            # clear the output buffer
79             push @out, $rec->{egid}; # slug in the egid first thing
80             push @out, $j;           # holding seq goes next
81
82             # grab the unary mappings and slug 'em in
83             for my $sub ( sort keys %{$rec->{tags}[$holdidx]{uni}} ) {
84                 push @out, $rec->{tags}[$holdidx]{uni}{$sub};
85                 print HOLDINGS "l_", $m->name($tagid, $sub),", " unless $j;
86             }
87
88             # handle holdings multis
89             for my $sub ( sort keys %{$multis->{$tagid}} ) {
90                 for my $value ( @{$rec->{tags}[$holdidx]{multi}{$sub}} ) {
91                   my $fh = $MULTIFILE{"$tagid$sub"};
92                   print $fh join("\t", $rec->{egid}, $j, $value), "\n";
93               }
94             }
95
96
97             # now get everything else in the mapping
98             for my $othertag ( sort keys %{$rec->{tmap}} ) {
99                 next if $othertag eq $c->{holdings};  # ignoring the holdings, o'course
100                 my $test_idx = $rec->{tmap}{$othertag}[0]; # get index into tags struct
101                 unless (defined $test_idx) {
102                     push @out, '';
103                     next;
104                 }
105                 # handle only first other tag unless it is known to be multi
106                 my $limit = 0;
107                 if (exists($multis->{$othertag})) {
108                     $limit = $#{ $rec->{tmap}{$othertag} };
109                 }
110                 foreach my $idx (0..$limit) {
111                     my $tag_idx = $rec->{tmap}{$othertag}[$idx];
112                     for my $sub ( sort keys %{$rec->{tags}[$tag_idx]{uni}} ) {
113                         if ($m->first_only($rec->{tags}[$tag_idx]{tag}, $sub)) {
114                             push @out, ($k == 1) ? $rec->{tags}[$tag_idx]{uni}{$sub} : '';
115                         } else {
116                             push @out, $rec->{tags}[$tag_idx]{uni}{$sub};
117                         }
118                         print HOLDINGS "l_", $m->name($rec->{tags}[$tag_idx]{tag}, $sub), ", " unless $j;
119                     }
120                     next unless exists($multis->{$othertag});
121                     for my $sub ( sort keys %{$multis->{$othertag}} ) {
122                         next if $m->first_only($rec->{tags}[$tag_idx]{tag}, $sub) and ($k > 1);
123                         for my $value ( @{$rec->{tags}[$tag_idx]{multi}{$sub}} ) {
124                             my $fh = $MULTIFILE{"$othertag$sub"};
125                             print $fh normalize_output(join("\t", $rec->{egid}, $j, $value)), "\n";
126                         }
127                     }
128                 }
129             }
130
131             # and dump it
132             print HOLDINGS "\n" unless $j;
133             print HOLDINGS normalize_output(join("\t", @out));
134             print HOLDINGS "\n";
135             $j++;
136         }
137         $i++;
138         print "\r$i $j";
139     }
140     print "\n";
141 }
142
143 #--------------------------
144
145 sub run_samples {
146     my ($c) = @_;
147     my $s;
148     print "Parsing records for sampling... ";
149     if ($c->{samplemap}) {
150         $s = Equinox::Migration::MARCXMLSampler->new( marcfile => $c->{marcfile},
151                                                       mapfile  => $c->{samplemap});
152     } elsif ($c->{samplestr}) {
153         $s = Equinox::Migration::MARCXMLSampler->new( marcfile  => $c->{marcfile},
154                                                       mapstring => $c->{samplestr});
155     } else {
156         $s = Equinox::Migration::MARCXMLSampler->new( marcfile => $c->{marcfile} );
157     }
158
159     dump_sample_overview($c, $s) if $c->{sample};
160     dump_sample_detail($c, $s) if ($c->{samplemap} or $c->{samplestr});
161 }
162
163 sub dump_sample_detail {
164     my ($c, $s) = @_;
165     my $tags = $s->{data}{samp};
166     my $count = $s->{data}{rcnt};
167     my $scnt  = $s->{data}{scnt};
168
169     open DETAIL, '>', ($c->{prefix} . "-HOLDINGS-DETAIL.txt");
170     select DETAIL;
171     for my $tag (sort keys %{ $tags }) {
172         print ">>>>> TAG $tag\n\n";
173         for my $subkey (sort keys %{ $tags->{$tag} }) {
174             my $sub = $tags->{$tag}{$subkey};
175             print "|| $subkey | ", $sub->{value}, " | ", 
176               $sub->{count}, "/", $sub->{tcnt}, " | ", ($sub->{count} > $sub->{tcnt}) ? "MULTI" : "", " ||\n";
177         }
178         print "\n";
179     }
180     close DETAIL;
181     open SCOUNT, '>', ($c->{prefix} . "-HOLDINGS-SUBCOUNTS.txt");
182     select SCOUNT;
183     for my $tag (sort keys %{ $scnt }) {
184         print ">>>>> TAG $tag\n\n";
185         for my $len (sort keys %{ $scnt->{$tag} }) 
186           { print "|| $len | ", $scnt->{$tag}{$len}, " ||\n" }
187         print "\n";
188     }
189     select STDOUT;
190     print "Saved results as ", ($c->{prefix} . "-HOLDINGS-DETAIL.txt"), " and ",
191         ($c->{prefix} . "-HOLDINGS-SUBCOUNTS.txt"), "\n";
192 }
193
194 sub dump_sample_overview {
195     my ($c, $s) = @_;
196     my $tags = $s->{data}{tags};
197     my $count = $s->{data}{rcnt};
198
199     my @tagsbyname  = sort keys %{$tags};
200     my @tagsbycount = reverse sort { $tags->{$a} <=> $tags->{$b} } keys %{$tags};
201
202     open SAMPLE, '>', ($c->{prefix} . "-HOLDINGS-OVERVIEW.txt");
203     select SAMPLE;
204     print "SAMPLE REPORT FOR ", $c->{prefix},": $count records\n\n";
205     print "FOUND TAGS (BY TAG)           FOUND TAGS (BY COUNT)\n";
206     print "------------------------      --------------------------\n";
207     for my $i (0 .. @tagsbyname - 1) {
208         print $tagsbyname[$i], (" " x (14 - length $tags->{ $tagsbyname[$i] })),
209           $tags->{ $tagsbyname[$i] };
210         print " (", sprintf("%03d", int($tags->{ $tagsbyname[$i] } / $count * 100)), "%)";
211         print "      ";
212         print $tagsbycount[$i], (" " x (16 - length $tags->{ $tagsbycount[$i] })),
213           $tags->{ $tagsbycount[$i] };
214         print " (", sprintf("%03d", int($tags->{ $tagsbycount[$i] } / $count * 100)), "%)\n";
215     }
216     select STDOUT;
217     print "Saved results as ", ($c->{prefix} . "-HOLDINGS-OVERVIEW.txt"), "\n";
218     close SAMPLE;
219 }
220
221 #--------------------------
222
223 sub initialize {
224     my $c = {};
225     my @missing = ();
226
227     # set mode on existing filehandles
228     binmode(STDIN, ':utf8');
229
230     my $rc = GetOptions( $c,
231                          'sample|s',
232                          'samplemap|sm=s',
233                          'samplestr|ss=s',
234                          'marcfile=s',
235                          'map|m=s',
236                          'holdings|h=i',
237                          'copyid|c=s',
238                          'prefix|p=s',
239                          'disable-pg-normalization',
240                          'version|v',
241                          'help',
242                        );
243     show_help() unless $rc;
244     show_help() if ($c->{help});
245     show_help("Nothing to do!")
246       unless ($c->{map} or $c->{sample} or $c->{samplemap} or $c->{samplestr});
247     show_help("map, holdings, and copyid must be specified together!")
248       if ($c->{map} and !($c->{holdings} and $c->{copyid}));
249     show_version() if $c->{version};
250
251     if ($c->{prefix} and !$c->{marcfile}) {
252         $c->{marcfile} = $c->{prefix} . ".clean.marc.xml";
253     }
254
255     my @keys = keys %{$c};
256     for my $key ('prefix', 'marcfile')
257       { push @missing, $key unless $c->{$key} }
258     if (@missing) {
259         print "Required option: ", join(', ', @missing), " missing!\n";
260         show_help();
261     }
262
263     return $c;
264 }
265
266 sub normalize_output {
267     my $str = shift;
268     $str =~ s!\\!\\\\!g unless $c->{'disable-pg-normalization'};
269     return $str;
270 }
271
272 sub show_help {
273     my ($msg) = @_;
274     print "\nERROR - $msg\n" if $msg;
275     print <<HELP;
276
277 Usage is: extract_holdings --prefix PREFIX --marcfile MARCFILE [ARGUMENTS]
278
279 REQUIRED ARGUMENTS
280   --prefix   -p  Prefix string for output filenames
281   --marcfile     MARCXML to use as source data
282                  Defaults to 'PREFIX.clean.marc.xml'
283
284 SAMPLING ARGUMENTS
285   --sample    -s   Generate a report of all tags in the MARC data
286   --samplemap -sm  Specify a Equinox::Migration::SimpleTagList map file which
287                    will be used to generate subfield breakdown reports about
288                    specific tags in the MARC data
289   --samplestr -ss  As above, but with a one-liner map specified on the command
290                    line as a string (e.g. '-ss "852 999"')
291
292   If --samplemap and --samplestr are both specified, --samplemap wins.
293
294 HOLDINGS EXTRACTION ARGUMENTS
295   --map      -m  Equinox::Migration::SubfieldMapper map file which will be
296                  used to extract holdings data from the input MARC file
297   --holdings -h  Specifies actual holdings tag
298   --copyid   -c  Specifies subfield of holdings with unique copy identifier
299   --disable-pg-normalization  By default, output is normalized so that a Postgres
300                               copy or \\copy can import the data without choking on
301                               backslashes; use this command-line option if
302                               output is not meant to be consumed by psql.
303
304   All three of these must be given together.
305 HELP
306     exit;
307 }
308
309 sub show_version { print "extract_holdings v$VERSION\n"; exit }