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