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