root/gsdl/trunk/bin/script/explode_metadata_database.pl @ 16790

Revision 16790, 14.5 KB (checked in by davidb, 12 years ago)

Support for exploding oai records. Added at the request of John Rose.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#!/usr/bin/perl -w
2
3
4BEGIN {
5    die "GSDLHOME not set\n" unless defined $ENV{'GSDLHOME'};
6    unshift (@INC, "$ENV{'GSDLHOME'}/perllib");
7    unshift (@INC, "$ENV{'GSDLHOME'}/perllib/plugins");
8}
9
10use strict;
11no strict 'subs'; # allow barewords (eg STDERR) as function arguments
12no strict 'refs'; # allow filehandles to be variables and vice versa
13
14use encodings;
15use printusage;
16use parse2;
17use FileHandle;
18
19use File::Spec;
20use File::Basename;
21
22my $unicode_list =
23    [ { 'name' => "auto",
24    'desc' => "{BasPlug.input_encoding.auto}" },
25      { 'name' => "ascii",
26    'desc' => "{BasPlug.input_encoding.ascii}" },
27      { 'name' => "utf8",
28    'desc' => "{BasPlug.input_encoding.utf8}" },
29      { 'name' => "unicode",
30    'desc' => "{BasPlug.input_encoding.unicode}" } ];
31
32my $e = $encodings::encodings;
33foreach my $enc (sort {$e->{$a}->{'name'} cmp $e->{$b}->{'name'}} keys (%$e))
34{
35    my $hashEncode =
36    {'name' => $enc,
37     'desc' => $e->{$enc}->{'name'}};
38   
39    push(@{$unicode_list},$hashEncode);
40}
41
42my $arguments =
43    [
44      { 'name' => "language",
45    'desc' => "{scripts.language}",
46    'type' => "string",
47    'reqd' => "no",
48        'hiddengli' => "yes" },
49      { 'name' => "plugin",
50    'desc' => "{explode.plugin}",
51    'type' => "string",
52    'reqd' => "yes",
53    'hiddengli' => "yes"},
54      { 'name' => "input_encoding",
55    'desc' => "{explode.encoding}",
56    'type' => "enum",
57    'deft' => "auto",
58    'list' => $unicode_list,
59    'reqd' => "no" },
60      { 'name' => "metadata_set",
61    'desc' => "{explode.metadata_set}",
62    'type' => "string",
63    'reqd' => "no" },
64      { 'name' => "document_field",
65    'desc' => "{explode.document_field}",
66    'type' => "string",
67    'reqd' => "no"},
68       { 'name' => "document_prefix",
69    'desc' => "{explode.document_prefix}",
70    'type' => "string",
71    'reqd' => "no"},
72      { 'name' => "document_suffix",
73    'desc' => "{explode.document_suffix}",
74    'type' => "string",
75    'reqd' => "no"},
76      { 'name' => "records_per_folder",
77    'desc' => "{explode.records_per_folder}",
78    'type' => "int",
79    'range' => "0,",
80    'deft' => "100",
81    'reqd' => "no" },
82      { 'name' => "verbosity",
83    'desc' => "{import.verbosity}",
84    'type' => "int",
85    'range' => "0,",
86    'deft' => "1",
87    'reqd' => "no",
88    'modegli' => "4" },
89      { 'name' => "xml",
90    'desc' => "",
91    'type' => "flag",
92    'reqd' => "no",
93    'hiddengli' => "yes" }
94      ];
95   
96my $options = { 'name' => "explode_metadata_database.pl",
97        'desc' => "{explode.desc}",
98        'args' => $arguments };
99
100
101
102sub main
103{
104    my ($language, $input_encoding, $metadata_set, $plugin,
105    $document_field, $document_prefix, $document_suffix, $records_per_folder, $verbosity);
106
107    my $xml = 0;
108
109    my $hashParsingResult = {};
110    # parse the options
111    my $intArgLeftinAfterParsing = parse2::parse(\@ARGV,$arguments,$hashParsingResult,"allow_extra_options");
112
113    # If parse returns -1 then something has gone wrong
114    if ($intArgLeftinAfterParsing == -1)
115    {
116    &PrintUsage::print_txt_usage($options, "{explode.params}");
117    die "\n";
118    }
119
120    foreach my $strVariable (keys %$hashParsingResult)
121    {
122    eval "\$$strVariable = \$hashParsingResult->{\"\$strVariable\"}";
123    }
124
125    # If $language has been specified, load the appropriate resource bundle
126    # (Otherwise, the default resource bundle will be loaded automatically)
127    if ($language && $language =~ /\S/) {
128    &gsprintf::load_language_specific_resource_bundle($language);
129    }
130
131    if ($xml) {
132        &PrintUsage::print_xml_usage($options);
133    print "\n";
134    return;
135    }
136
137   
138    # There should one arg left after parsing (the filename)
139    # Or the user may have specified -h, in which case we output the usage
140    if($intArgLeftinAfterParsing != 1 || (@ARGV && $ARGV[0] =~ /^\-+h/))
141    {
142    &PrintUsage::print_txt_usage($options, "{explode.params}");
143    die "\n";
144    }
145
146    # The metadata database filename is the first value that remains after the options have been parsed out
147    my $filename = $ARGV[0];
148    if (!defined $filename || $filename !~ /\w/) {
149    &PrintUsage::print_txt_usage($options, "{explode.params}");
150    print STDERR "You need to specify a filename";
151    die "\n";
152    }
153    # check that file exists
154    if (!-e $filename) {
155    print STDERR "File $filename doesn't exist...\n";
156    die "\n";
157    }
158    # check required options
159    if (!defined $plugin || $plugin !~ /\w/) {
160    &PrintUsage::print_txt_usage($options, "{explode.params}");
161    print STDERR "You need to specify a plugin";
162    die "\n";
163    }
164   
165    # check metadata set
166    if (defined $metadata_set && $metadata_set =~ /\w/) {
167    $metadata_set .= ".";
168    } else {
169    $metadata_set = "";
170    }
171
172    my $plugobj;
173    require "$plugin.pm";
174    eval ("\$plugobj = new $plugin()");
175    die "$@" if $@;
176
177    # ...and initialize it
178    $plugobj->init(1, "STDERR", "STDERR");
179   
180    if ($input_encoding eq "auto") {
181    ($language, $input_encoding) = $plugobj->textcat_get_language_encoding ($filename);
182    }
183
184    # Create a directory to store the document files...
185    my ($exploded_base_dir) = ($filename =~ /(.*)\.[^\.]+$/);
186
187    my $orig_base_dir = &File::Basename::dirname($filename);
188
189
190    my $split_exp = $plugobj->{'split_exp'};
191    if (defined $split_exp) {
192    # Read in file, and then split and process individual records
193
194    my $text = "";
195    # Use the plugin's read_file function to avoid duplicating code
196    $plugobj->read_file($filename, $input_encoding, undef, \$text);
197    # is there any text in the file??
198    die "\n" unless length($text);
199
200    # Split the text into records, using the plugin's split_exp
201
202    my @metadata_records = split(/$split_exp/, $text);
203    print STDERR "Number of records: " . scalar(@metadata_records) . "\n";
204   
205    # Write the metadata from each record to the metadata.xml file
206    my $record_number = 1;
207    foreach my $record_text (@metadata_records) {
208       
209        # Check if we need to start a new directory for these records
210        my $documents_directory;
211        check_need_new_directory($exploded_base_dir,$record_number,$records_per_folder,
212                     \@metadata_records,\$documents_directory);
213       
214        # Use the plugin's process function to avoid duplicating code
215        my $doc_obj = new doc($filename, "nonindexed_doc");
216        $plugobj->process(\$record_text, undef, undef, $filename, undef, $doc_obj, 0);
217       
218       
219        # Try to get a doc to attach the metadata to
220        # If no match found, create a dummy .nul file
221        attach_metadata_or_nul_doc($document_field, $doc_obj, $record_number,
222                       $documents_directory, $orig_base_dir,
223                       $document_prefix, $document_suffix, $metadata_set, $verbosity);
224               
225       
226        check_close_directory($record_number,$records_per_folder,\@metadata_records);
227       
228        $record_number = $record_number + 1;
229    }
230    }
231    else {
232    # Call metadata_read to sets up associated metadata
233
234    my $pluginfo = undef;
235    my $metadata = {};
236
237    my $processor = undef;
238    my $maxdocs = undef;
239    my $gli = undef;
240
241    my $extrametakeys = {};
242    my $extrametadata = {};
243
244
245    $plugobj->metadata_read($pluginfo, "", $filename, $metadata,
246                $extrametakeys, $extrametadata, $processor, $maxdocs, $gli);
247
248
249    my $documents_directory = need_new_directory($exploded_base_dir);
250
251    # Attach metadata to object
252    # => use the plugin's extra_metadata function to avoid duplicating code
253    my $doc_obj = new doc($filename, "nonindexed_doc");
254
255    $plugobj->extra_metadata ($doc_obj, $doc_obj->get_top_section(), $metadata);
256
257    # Try to get a doc to attach the metadata to
258    # If no match found, create a dummy .nul file
259    attach_metadata_or_make_nul_doc($document_field, $doc_obj, undef,
260                    $documents_directory, $orig_base_dir,
261                    $document_prefix, $document_suffix, $metadata_set, $verbosity);
262
263
264    close_directory();
265    }
266
267
268    # Explode means just that: the original file is deleted
269    &util::rm($filename);
270    $plugobj->clean_up_after_exploding();
271
272}
273
274
275sub need_new_directory
276{
277    my ($exploded_base_dir) = @_;
278   
279    my $documents_directory = $exploded_base_dir;
280
281    if (-d $documents_directory) {
282    die "Error: document directory $documents_directory already exists (bailing).\n";
283    }
284    &util::mk_dir($documents_directory);
285
286    my $documents_metadata_xml_file = &util::filename_cat($documents_directory, "metadata.xml");
287    if (-e $documents_metadata_xml_file) {
288    die "Error: documents metadata.xml file $documents_metadata_xml_file already exists (bailing).\n";
289    }
290
291    # Start the metadata.xml file
292    open(METADATA_XML_FILE, ">$documents_metadata_xml_file");
293    print METADATA_XML_FILE
294    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" .
295    "<!DOCTYPE DirectoryMetadata SYSTEM \"http://greenstone.org/dtd/DirectoryMetadata/1.0/DirectoryMetadata.dtd\">\n" .
296    "<DirectoryMetadata>\n";
297
298    return $documents_directory;
299}
300
301sub check_need_new_directory
302{
303    my ($exploded_base_dir,$record_number, $records_per_folder,$metadata_records,
304    $documents_dir_ref) = @_;
305   
306
307    # Check if we need to start a new directory for these records
308    if (($record_number % $records_per_folder) == 1) {
309    my $documents_directory = $exploded_base_dir;
310
311    if (scalar(@$metadata_records) > $records_per_folder) {
312        $documents_directory .= "." . sprintf("%8.8d", $record_number);
313    }
314
315    $$documents_dir_ref = need_new_directory($documents_directory);
316    }
317}
318
319
320
321
322
323sub attach_metadata_or_make_nul_doc
324{
325    my ($document_field, $doc_obj, $record_number,
326    $documents_directory, $orig_base_dir,
327    $document_prefix, $document_suffix, $metadata_set, $verbosity) = @_;
328
329    my $record_metadata = $doc_obj->get_all_metadata($doc_obj->get_top_section());
330    my $document_file;
331
332    # try to get a doc to attach the metadata to
333    if (defined $document_field) {
334    foreach my $pair (@$record_metadata) {
335        my ($field, $value) = (@$pair);
336
337        $value =~ s/\\\\/\\/g;
338       
339        # Does this metadata element specify a document to obtain?
340        if ($field eq $document_field) {
341        my $document_file_full = $document_prefix . $value . $document_suffix;
342
343        $document_file = &obtain_document($document_file_full, $documents_directory, $orig_base_dir, $verbosity);
344        &write_metadata_xml_file_entry(METADATA_XML_FILE, $document_file, $record_metadata, $metadata_set);
345        }
346    }
347    }
348   
349    # Create a dummy .nul file if we haven't obtained any documents for this record
350    if (not defined $document_file) {
351
352    if (defined ($record_number)) {
353        $document_file = sprintf("%8.8d", $record_number) . ".nul";
354    }
355    else {
356        $document_file = "doc.nul";
357    }
358
359    open(DUMMY_FILE, ">$documents_directory/$document_file");
360    close(DUMMY_FILE);
361    &write_metadata_xml_file_entry(METADATA_XML_FILE, $document_file, $record_metadata, $metadata_set);
362    }
363
364}
365
366sub close_directory
367{
368    # Finish and close the metadata.xml file
369    print METADATA_XML_FILE "\n</DirectoryMetadata>\n";
370    close(METADATA_XML_FILE);
371
372}
373
374
375sub check_close_directory
376{
377    my ($record_number,$records_per_folder,$metadata_records) = @_;
378
379    if (($record_number % $records_per_folder) == 0 || $record_number == scalar(@$metadata_records)) {
380    # Finish and close the metadata.xml file
381    close_directory();
382    }
383}
384       
385
386
387sub write_metadata_xml_file_entry
388{
389    my $metadata_xml_file = shift(@_);
390    my $file_name = shift(@_);
391    my $record_metadata = shift(@_);
392    my $meta_prefix = shift(@_);
393   
394    # Make $file_name XML-safe
395    $file_name =~ s/&/&amp;/g;
396    $file_name =~ s/</&lt;/g;
397    $file_name =~ s/>/&gt;/g;
398
399    # Convert $file_name into a regular expression that matches it
400    $file_name =~ s/\./\\\./g;
401    $file_name =~ s/\(/\\\(/g;
402    $file_name =~ s/\)/\\\)/g;
403    $file_name =~ s/\{/\\\{/g;
404    $file_name =~ s/\}/\\\}/g;
405    $file_name =~ s/\[/\\\[/g;
406    $file_name =~ s/\]/\\\]/g;
407   
408    print $metadata_xml_file
409    "\n" .
410        "  <FileSet>\n" .
411    "    <FileName>$file_name</FileName>\n" .
412    "    <Description>\n";
413
414    foreach my $pair (@$record_metadata) {
415    my ($field, $value) = (@$pair);
416
417    # We're only interested in metadata from the database
418    next if ($field eq "lastmodified");
419    next if ($field eq "gsdlsourcefilename");
420    next if ($field eq "gsdldoctype");
421    next if ($field eq "FileFormat");
422
423    # Ignore the ^all metadata, since it will be invalid if the source metadata is changed
424    next if ($field =~ /\^all$/);  # ISISPlug specific!
425
426    # Make $value XML-safe
427    $value =~ s/&/&amp;/g;  # May mess up existing entities!
428    $value =~ s/</&lt;/g;
429    $value =~ s/>/&gt;/g;
430
431    # we are not allowed & in xml except in entities.
432    # if there are undefined entities then parsing will also crap out.
433    # should we be checking for them too?
434    # this may not get all possibilities
435    # $value =~ s/&([^;\s]*(\s|$))/&amp;$1/g;
436
437    print $metadata_xml_file "      <Metadata mode=\"accumulate\" name=\"$meta_prefix$field\">$value</Metadata>\n";
438    }
439
440    print $metadata_xml_file
441    "    </Description>\n" .
442        "  </FileSet>\n";
443}
444
445sub obtain_document
446{
447    my ($document_file_full,$documents_directory,$orig_base_dir,$verbosity) = @_;
448   
449    print STDERR "Obtaining document file $document_file_full...\n" if ($verbosity > 1);
450
451    my $document_file_name;
452    my $local_document_file;
453
454    # Document specified is on the web
455    if ($document_file_full =~ /^https?:/ || $document_file_full =~ /^ftp:/) {
456    $document_file_full =~ /([^\/]+)$/;
457    $document_file_name = $1;
458    $local_document_file = &util::filename_cat($documents_directory, $document_file_name);
459
460    my $wget_options = "--quiet";
461    $wget_options = "--verbose" if ($verbosity > 2);
462    $wget_options .= " --timestamping";  # Only re-download files if they're newer
463    my $wget_command = "wget $wget_options \"$document_file_full\" --output-document \"$local_document_file\"";
464    `$wget_command`;
465
466    # Check the document was obtained successfully
467    if (!-e $local_document_file) {
468        print STDERR "WARNING: Could not obtain document file $document_file_full\n";
469    }
470    }
471    # Document specified is on the disk
472    else {
473    my $dir_sep = &util::get_os_dirsep();
474
475    $document_file_full =~ m/(.+$dir_sep)?(.*)$/;
476    $document_file_name = $2;
477
478
479    my $is_absolute = File::Spec->file_name_is_absolute($document_file_full);
480    print STDERR "doc file full = $document_file_full\n";
481
482    if (!$is_absolute) {
483        $document_file_full
484        = &util::filename_cat($orig_base_dir,$document_file_full);
485    }
486
487    $local_document_file = &util::filename_cat($documents_directory, $document_file_name);
488
489    &util::cp($document_file_full, $documents_directory);
490
491    # Check the document was obtained successfully
492    if (!-e $local_document_file) {
493        print STDERR "WARNING: Could not obtain document file $document_file_full\n";
494    }
495    else {
496        if ($document_file_full =~ m/^$orig_base_dir.*/) {
497        # file local to metadata record
498        # => copy has been made successfully, so remove original
499        &util::rm($document_file_full);
500        }
501    }
502    }
503
504    # If the document wasn't obtained successfully, create a .nul file for it
505    if (!-e $local_document_file) {
506    $document_file_name .= ".nul";
507    open(NULL_FILE, ">$local_document_file.nul");
508    close(NULL_FILE);
509    }
510
511    return $document_file_name;
512}
513
514&main(@ARGV);
515
Note: See TracBrowser for help on using the browser.