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