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