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