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