source: gsdl/trunk/bin/script/explode_metadata_database.pl@ 17217

Last change on this file since 17217 was 17217, checked in by kjdon, 16 years ago

added the block_hash arg to metadata_read

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