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