newline at end of sample run
[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.003;
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... ";
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         # for each holdings tag in the record...
55         while ( defined $rec->{tmap}{ $c->{holdings} }[$k] ) {
56             my $holdidx = $rec->{tmap}{ $c->{holdings} }[$k];
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                 for my $sub ( sort keys %{$rec->{tags}[$idx]{uni}} ) {
84                     push @out, $rec->{tags}[$idx]{uni}{$sub};
85                     print HOLDINGS "l_", $m->name($rec->{tags}[$idx]{tag}, $sub), ", "
86                       unless $j;
87                 }
88             }
89
90             # and dump it
91             print HOLDINGS "\n" unless $j;
92             print HOLDINGS join("\t", @out);
93             print HOLDINGS "\n";
94             $j++;
95
96             @out = undef;
97         }
98         $i++;
99         print "\r$i";
100     }
101     print "\n";
102 }
103
104 #--------------------------
105
106 sub run_samples {
107     my ($c) = @_;
108     my $s;
109     print "Parsing records for sampling... ";
110     if ($c->{samplemap}) {
111         $s = Equinox::Migration::MARCXMLSampler->new( marcfile => $c->{marcfile},
112                                                       mapfile  => $c->{samplemap});
113     } elsif ($c->{samplestr}) {
114         $s = Equinox::Migration::MARCXMLSampler->new( marcfile  => $c->{marcfile},
115                                                       mapstring => $c->{samplestr});
116     } else {
117         $s = Equinox::Migration::MARCXMLSampler->new( marcfile => $c->{marcfile} );
118     }
119
120     dump_sample_overview($c, $s) if $c->{sample};
121     dump_sample_detail($c, $s) if ($c->{samplemap} or $c->{samplestr});
122 }
123
124 sub dump_sample_detail {
125     my ($c, $s) = @_;
126     my $tags = $s->{data}{samp};
127     my $count = $s->{data}{rcnt};
128     my $scnt  = $s->{data}{scnt};
129
130     open DETAIL, '>', ($c->{prefix} . "-HOLDINGS-DETAIL.txt");
131     select DETAIL;
132     for my $tag (sort keys %{ $tags }) {
133         print ">>>>> TAG $tag\n\n";
134         for my $subkey (sort keys %{ $tags->{$tag} }) {
135             my $sub = $tags->{$tag}{$subkey};
136             print "|| $subkey | ", $sub->{value}, " | ", 
137               $sub->{count}, "/", $sub->{tcnt}, " |  ||\n";
138         }
139         print "\n";
140     }
141     close DETAIL;
142     open SCOUNT, '>', ($c->{prefix} . "-HOLDINGS-SUBCOUNTS.txt");
143     select SCOUNT;
144     for my $tag (sort keys %{ $scnt }) {
145         print ">>>>> TAG $tag\n\n";
146         for my $len (sort keys %{ $scnt->{$tag} }) 
147           { print "|| $len | ", $scnt->{$tag}{$len}, " ||\n" }
148         print "\n";
149     }
150     select STDOUT;
151 }
152
153 sub dump_sample_overview {
154     my ($c, $s) = @_;
155     my $tags = $s->{data}{tags};
156     my $count = $s->{data}{rcnt};
157
158     my @tagsbyname  = sort keys %{$tags};
159     my @tagsbycount = reverse sort { $tags->{$a} <=> $tags->{$b} } keys %{$tags};
160
161     open SAMPLE, '>', ($c->{prefix} . "-HOLDINGS-OVERVIEW.txt");
162     select SAMPLE;
163     print "SAMPLE REPORT FOR ", $c->{prefix},": $count records\n\n";
164     print "FOUND TAGS (BY TAG)           FOUND TAGS (BY COUNT)\n";
165     print "------------------------      --------------------------\n";
166     for my $i (0 .. @tagsbyname - 1) {
167         print $tagsbyname[$i], (" " x (14 - length $tags->{ $tagsbyname[$i] })),
168           $tags->{ $tagsbyname[$i] };
169         print " (", sprintf("%03d", int($tags->{ $tagsbyname[$i] } / $count * 100)), "%)";
170         print "      ";
171         print $tagsbycount[$i], (" " x (16 - length $tags->{ $tagsbycount[$i] })),
172           $tags->{ $tagsbycount[$i] };
173         print " (", sprintf("%03d", int($tags->{ $tagsbycount[$i] } / $count * 100)), "%)\n";
174     }
175     select STDOUT;
176     print "\n";
177     close SAMPLE;
178 }
179
180 #--------------------------
181
182 sub initialize {
183     my $c = {};
184     my @missing = ();
185
186     # set mode on existing filehandles
187     binmode(STDIN, ':utf8');
188
189     my $rc = GetOptions( $c,
190                          'sample|s',
191                          'samplemap|sm=s',
192                          'samplestr|ss=s',
193                          'marcfile=s',
194                          'map|m=s',
195                          'holdings|h=i',
196                          'copyid|c=s',
197                          'prefix|p=s',
198                          'version|v',
199                          'help',
200                        );
201     show_help() unless $rc;
202     show_help() if ($c->{help});
203     show_help("Nothing to do!")
204       unless ($c->{map} or $c->{sample} or $c->{samplemap} or $c->{samplestr});
205     show_help("map, holdings, and copyid must be specified together!")
206       if ($c->{map} and !($c->{holdings} and $c->{copyid}));
207     show_version() if $c->{version};
208
209     if ($c->{prefix} and !$c->{marcfile}) {
210         $c->{marcfile} = $c->{prefix} . ".clean.marc.xml";
211     }
212
213     my @keys = keys %{$c};
214     for my $key ('prefix', 'marcfile')
215       { push @missing, $key unless $c->{$key} }
216     if (@missing) {
217         print "Required option: ", join(', ', @missing), " missing!\n";
218         show_help();
219     }
220
221     return $c;
222 }
223
224 sub show_help {
225     my ($msg) = @_;
226     print "\nERROR - $msg\n" if $msg;
227     print <<HELP;
228
229 Usage is: extract_holdings -p PREFIX -m MARCFILE [ARGUMENTS]
230
231 REQUIRED ARGUMENTS
232   --prefix   -p  Prefix string for output filenames
233   --marcfile     MARCXML to use as source data
234                  Defaults to 'PREFIX.clean.marc.xml'
235
236 SAMPLING ARGUMENTS
237   --sample    -s   Generate a report of all tags in the MARC data
238   --samplemap -sm  Specify a E::M::STL map file which will be used to generate
239                    subfield breakdown reports about specific tags in the MARC
240                    data
241   --samplestr -ss  As above, but with a one-liner map specified on the command
242                    line as a string (e.g. '-ss "852 999"')
243
244   If --samplemap and --samplestr are both specified, --samplemap wins.
245
246 HOLDINGS EXTRACTION ARGUMENTS
247   --map      -m   E::M::SM map file which will be used to extract holdings data
248                  from the input MARC file
249   --holdings -h  Specifies actual holdings tag
250   --copyid   -c  Specifies subfield of holdings with unique copy identifier
251
252   Both these must be given together.
253 HELP
254     exit;
255 }
256
257 sub show_version { print "extract_holdings v$VERSION\n"; exit }