tweaks
[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         my $k = 0; # holding-within-record pointer
53
54         # for each holdings tag in the record...
55         while ( $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),"\t" 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 "l_", $m->name($rec->{tags}[$idx]{tag}, $sub), "\t" 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     my @keys = keys %{$c};
209     for my $key ('prefix', 'marcfile')
210       { push @missing, $key unless $c->{$key} }
211     if (@missing) {
212         print "Required option: ", join(', ', @missing), " missing!\n";
213         show_help();
214     }
215
216     return $c;
217 }
218
219 sub show_help {
220     my ($msg) = @_;
221     print "\nERROR - $msg\n" if $msg;
222     print <<HELP;
223
224 Usage is: extract_holdings -p PREFIX -m MARCFILE [ARGUMENTS]
225
226 REQUIRED ARGUMENTS
227   --prefix   -p  Prefix string for output filenames
228   --marcfile -m  MARCXML to use as source data
229
230 SAMPLING ARGUMENTS
231   --sample    -s   Generate a report of all tags in the MARC data
232   --samplemap -sm  Specify a E::M::STL map file which will be used to generate
233                    subfield breakdown reports about specific tags in the MARC
234                    data
235   --samplestr -ss  As above, but with a one-liner map specified on the command
236                    line as a string (e.g. '-ss "852 999"')
237
238   If --samplemap and --samplestr are both specified, --samplemap wins.
239
240 HOLDINGS EXTRACTION ARGUMENTS
241   --map          E::M::SM map file which will be used to extract holdings data
242                  from the input MARC file
243   --holdings -h  Specifies actual holdings tag
244   --copyid   -c  Specifies subfield of holdings with unique copy identifier
245
246   Both these must be given together.
247 HELP
248     exit;
249 }
250
251 sub show_version { print "extract_holdings v$VERSION\n"; exit }