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

Last change on this file since 19626 was 19626, checked in by ak19, 12 years ago

Katherine fixed it so that exploding now works on Windows: parameter document file full was in Linux filepath format and is now first converted to Windows.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 18.2 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' => "collection",
85 'desc' => "{explode.collection}",
86 'type' => "string",
87 'reqd' => "no",
88 'hiddengli' => "yes"},
89 { 'name' => "use_collection_plugin_options",
90 'desc' => "{explode.use_collection_plugin_options}",
91 'type' => "flag",
92 'reqd' => "no",
93 'hiddengli' => "yes"},
94 { 'name' => "plugin_options",
95 'desc' => "{explode.plugin_options}",
96 'type' => "string",
97 'reqd' => "no",
98 'hiddengli' => "yes"},
99 { 'name' => "verbosity",
100 'desc' => "{import.verbosity}",
101 'type' => "int",
102 'range' => "0,",
103 'deft' => "1",
104 'reqd' => "no",
105 'modegli' => "3" },
106 { 'name' => "xml",
107 'desc' => "",
108 'type' => "flag",
109 'reqd' => "no",
110 'hiddengli' => "yes" }
111 ];
112
113my $options = { 'name' => "explode_metadata_database.pl",
114 'desc' => "{explode.desc}",
115 'args' => $arguments };
116
117
118
119sub main
120{
121 my ($language, $input_encoding, $metadata_set, $plugin,
122 $document_field, $document_prefix, $document_suffix, $records_per_folder, $plugin_options, $collection, $use_collection_plugin_options, $verbosity);
123
124 my $xml = 0;
125
126 my $hashParsingResult = {};
127 # parse the options
128 my $intArgLeftinAfterParsing = parse2::parse(\@ARGV,$arguments,$hashParsingResult,"allow_extra_options");
129
130 # If parse returns -1 then something has gone wrong
131 if ($intArgLeftinAfterParsing == -1)
132 {
133 &PrintUsage::print_txt_usage($options, "{explode.params}");
134 die "\n";
135 }
136
137 foreach my $strVariable (keys %$hashParsingResult)
138 {
139 eval "\$$strVariable = \$hashParsingResult->{\"\$strVariable\"}";
140 }
141
142 # If $language has been specified, load the appropriate resource bundle
143 # (Otherwise, the default resource bundle will be loaded automatically)
144 if ($language && $language =~ /\S/) {
145 &gsprintf::load_language_specific_resource_bundle($language);
146 }
147
148 if ($xml) {
149 &PrintUsage::print_xml_usage($options);
150 print "\n";
151 return;
152 }
153
154
155 # There should one arg left after parsing (the filename)
156 # Or the user may have specified -h, in which case we output the usage
157 if($intArgLeftinAfterParsing != 1 || (@ARGV && $ARGV[0] =~ /^\-+h/))
158 {
159 &PrintUsage::print_txt_usage($options, "{explode.params}");
160 die "\n";
161 }
162
163 # The metadata database filename is the first value that remains after the options have been parsed out
164 my $filename = $ARGV[0];
165 if (!defined $filename || $filename !~ /\w/) {
166 &PrintUsage::print_txt_usage($options, "{explode.params}");
167 print STDERR "You need to specify a filename";
168 die "\n";
169 }
170 # check that file exists
171 if (!-e $filename) {
172 print STDERR "File $filename doesn't exist...\n";
173 die "\n";
174 }
175 # check required options
176 if (!defined $plugin || $plugin !~ /\w/) {
177 &PrintUsage::print_txt_usage($options, "{explode.params}");
178 print STDERR "You need to specify a plugin";
179 die "\n";
180 }
181
182 # check metadata set
183 if (defined $metadata_set && $metadata_set =~ /\w/) {
184 $metadata_set .= ".";
185 } else {
186 $metadata_set = "";
187 }
188 if (defined $collection && $collection =~ /\w/) {
189 if (($collection = &colcfg::use_collection("", $collection, "")) eq "") {
190 print STDERR "Collection $collection does not exist\n";
191 die "\n";
192 }
193 } else {
194 undef $collection;
195 }
196
197 if ($use_collection_plugin_options) {
198 if (defined $plugin_options && $plugin_options =~ /\w/) {
199 print STDERR "Error: you cannot have -use_collection_plugin_options and -plugin_options set at the same time\n";
200 die "\n";
201 }
202 if (not defined $collection) {
203 print STDERR "Error: you must specify a collection using -collection to use -use_collection_plugin_options\n";
204 die "\n";
205 }
206 }
207 my $plugobj;
208 require "$plugin.pm";
209
210 my $plugin_options_string = "";
211 if ($use_collection_plugin_options) {
212 # read in the collect.cfg file
213 # Read in the collection configuration file.
214 my ($configfilename, $gs_mode) = &colcfg::get_collect_cfg_name(STDERR);
215 my $collectcfg;
216 if ($gs_mode eq "gs2") {
217 $collectcfg = &colcfg::read_collect_cfg ($configfilename);
218 } elsif ($gs_mode eq "gs3") {
219 $collectcfg = &colcfg::read_collection_cfg_xml ($configfilename);
220 }
221 $plugin_options_string = &get_plugin_options($collectcfg, $plugin);
222 }
223 elsif (defined $plugin_options && $plugin_options =~ /\w/) {
224 my @options = split(/\s/, $plugin_options);
225 map { $_ = "\"$_\"" unless $_ =~ /^\"/; } @options;
226 $plugin_options_string= join (",", @options);
227 }
228
229 if ($plugin_options_string eq "") {
230 eval ("\$plugobj = new $plugin()");
231 die "$@" if $@;
232 } else {
233 eval ("\$plugobj = new $plugin([], [$plugin_options_string])");
234 die "$@" if $@;
235 }
236
237 # ...and initialize it
238 $plugobj->init($verbosity, "STDERR", "STDERR");
239
240 if ($input_encoding eq "auto") {
241 ($language, $input_encoding) = $plugobj->textcat_get_language_encoding ($filename);
242 }
243
244 # Create a directory to store the document files...
245 my ($exploded_base_dir) = ($filename =~ /(.*)\.[^\.]+$/);
246
247 my $orig_base_dir = &File::Basename::dirname($filename);
248
249
250 my $split_exp = $plugobj->{'split_exp'};
251 if (defined $split_exp) {
252 # Read in file, and then split and process individual records
253
254 my $text = "";
255 # Use the plugin's read_file function to avoid duplicating code
256 $plugobj->read_file($filename, $input_encoding, undef, \$text);
257 # is there any text in the file??
258 die "\n" unless length($text);
259
260 # Split the text into records, using the plugin's split_exp
261
262 my @metadata_records = split(/$split_exp/, $text);
263 my $total_num_records = scalar(@metadata_records);
264 print STDERR "Number of records: $total_num_records\n";
265
266 # Write the metadata from each record to the metadata.xml file
267 my $record_number = 1;
268 my $documents_directory;
269 foreach my $record_text (@metadata_records) {
270
271 # Check if we need to start a new directory for these records
272 check_need_new_directory($exploded_base_dir,$record_number,
273 $records_per_folder,$total_num_records,
274 \$documents_directory);
275 # Use the plugin's process function to avoid duplicating code
276 my $doc_obj = new doc($filename, "nonindexed_doc", $plugobj->get_file_rename_method());
277 $plugobj->process(\$record_text, undef, undef, $filename, undef, $doc_obj, 0);
278
279
280 # Try to get a doc to attach the metadata to
281 # If no match found, create a dummy .nul file
282 attach_metadata_or_make_nul_doc($document_field, $doc_obj, $record_number,
283 $documents_directory, $orig_base_dir,
284 $document_prefix, $document_suffix, $metadata_set, $verbosity);
285
286
287 check_close_directory($record_number,$records_per_folder,$total_num_records);
288
289 $record_number = $record_number + 1;
290 }
291 }
292 else {
293 # Call metadata_read to set up associated metadata
294
295 my $pluginfo = undef;
296 my $block_hash = {};
297
298 my $processor = undef;
299 my $maxdocs = undef;
300 my $gli = undef;
301
302 my $extrametakeys = [];
303 my $extrametadata = {};
304 my $extrametafile = {};
305
306 $plugobj->metadata_read($pluginfo, "", $filename, $block_hash,
307 $extrametakeys, $extrametadata, $extrametafile,
308 $processor, $maxdocs, $gli);
309
310 my $total_num_records = scalar (@$extrametakeys);
311 print STDERR "Number of records: $total_num_records\n";
312 my $record_number = 1;
313 my $documents_directory;
314 foreach my $record (@$extrametakeys) {
315 &check_need_new_directory($exploded_base_dir, $record_number, $records_per_folder, $total_num_records, \$documents_directory);
316
317 # Attach metadata to object
318 # => use the plugin's extra_metadata function to avoid duplicating code
319 my $doc_obj = new doc($filename, "nonindexed_doc", $plugobj->get_file_rename_method());
320 # all the metadata has been extracted into extrametadata
321 $plugobj->extra_metadata ($doc_obj, $doc_obj->get_top_section(), $extrametadata->{$record});
322
323 # Try to get a doc to attach the metadata to
324 # If no match found, create a dummy .nul file
325 attach_metadata_or_make_nul_doc($document_field, $doc_obj, $record_number, $documents_directory, $orig_base_dir, $document_prefix, $document_suffix, $metadata_set, $verbosity);
326
327 &check_close_directory($record_number,$records_per_folder,$total_num_records);
328
329 $record_number = $record_number + 1;
330
331 }
332 }
333
334 # Explode means just that: the original file is deleted
335 &util::rm($filename);
336 $plugobj->clean_up_after_exploding();
337
338}
339
340
341sub need_new_directory
342{
343 my ($exploded_base_dir) = @_;
344
345 my $documents_directory = $exploded_base_dir;
346
347 if (-d $documents_directory) {
348 die "Error: document directory $documents_directory already exists (bailing).\n";
349 }
350 &util::mk_dir($documents_directory);
351
352 my $documents_metadata_xml_file = &util::filename_cat($documents_directory, "metadata.xml");
353 if (-e $documents_metadata_xml_file) {
354 die "Error: documents metadata.xml file $documents_metadata_xml_file already exists (bailing).\n";
355 }
356
357 # Start the metadata.xml file
358 open(METADATA_XML_FILE, ">$documents_metadata_xml_file");
359 print METADATA_XML_FILE
360 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" .
361 "<!DOCTYPE DirectoryMetadata SYSTEM \"http://greenstone.org/dtd/DirectoryMetadata/1.0/DirectoryMetadata.dtd\">\n" .
362 "<DirectoryMetadata>\n";
363
364 return $documents_directory;
365}
366
367sub check_need_new_directory
368{
369 my ($exploded_base_dir,$record_number, $records_per_folder,
370 $total_num_records, $documents_dir_ref) = @_;
371
372
373 # Check if we need to start a new directory for these records
374 if (($record_number % $records_per_folder) == 1) {
375 my $documents_directory = $exploded_base_dir;
376
377 if ($total_num_records > $records_per_folder) {
378 $documents_directory .= "." . sprintf("%8.8d", $record_number);
379 }
380
381 $$documents_dir_ref = need_new_directory($documents_directory);
382 }
383}
384
385
386
387
388
389sub attach_metadata_or_make_nul_doc
390{
391 my ($document_field, $doc_obj, $record_number,
392 $documents_directory, $orig_base_dir,
393 $document_prefix, $document_suffix, $metadata_set, $verbosity) = @_;
394
395 my $record_metadata = $doc_obj->get_all_metadata($doc_obj->get_top_section());
396 my $document_file;
397
398 # try to get a doc to attach the metadata to
399 if (defined $document_field) {
400 foreach my $pair (@$record_metadata) {
401 my ($field, $value) = (@$pair);
402
403 $value =~ s/\\\\/\\/g;
404
405 # Does this metadata element specify a document to obtain?
406 if ($field eq $document_field) {
407 my $document_file_full = $document_prefix . $value . $document_suffix;
408
409 # this either downloads/copies the document, or creates a nul file for it.
410 $document_file = &obtain_document($document_file_full, $documents_directory, $orig_base_dir, $verbosity);
411 &write_metadata_xml_file_entry(METADATA_XML_FILE, $document_file, $record_metadata, $metadata_set);
412 }
413 }
414 }
415
416 # Create a dummy .nul file if we haven't obtained a document (or null file) for this record
417 if (not defined $document_file) {
418
419 if (defined ($record_number)) {
420 $document_file = sprintf("%8.8d", $record_number) . ".nul";
421 }
422 else {
423 $document_file = "doc.nul";
424 }
425 open(DUMMY_FILE, ">$documents_directory/$document_file");
426 close(DUMMY_FILE);
427 &write_metadata_xml_file_entry(METADATA_XML_FILE, $document_file, $record_metadata, $metadata_set);
428 }
429
430}
431
432sub close_directory
433{
434 # Finish and close the metadata.xml file
435 print METADATA_XML_FILE "\n</DirectoryMetadata>\n";
436 close(METADATA_XML_FILE);
437
438}
439
440
441sub check_close_directory
442{
443 my ($record_number,$records_per_folder,$total_num_records) = @_;
444
445 if (($record_number % $records_per_folder) == 0 || $record_number == $total_num_records) {
446 # Finish and close the metadata.xml file
447 close_directory();
448 }
449}
450
451
452
453sub write_metadata_xml_file_entry
454{
455 my $metadata_xml_file = shift(@_);
456 my $file_name = shift(@_);
457 my $record_metadata = shift(@_);
458 my $meta_prefix = shift(@_);
459
460 # Make $file_name XML-safe
461 $file_name =~ s/&/&amp;/g;
462 $file_name =~ s/</&lt;/g;
463 $file_name =~ s/>/&gt;/g;
464
465 # Convert $file_name into a regular expression that matches it
466 $file_name =~ s/\./\\\./g;
467 $file_name =~ s/\(/\\\(/g;
468 $file_name =~ s/\)/\\\)/g;
469 $file_name =~ s/\{/\\\{/g;
470 $file_name =~ s/\}/\\\}/g;
471 $file_name =~ s/\[/\\\[/g;
472 $file_name =~ s/\]/\\\]/g;
473
474 print $metadata_xml_file
475 "\n" .
476 " <FileSet>\n" .
477 " <FileName>$file_name</FileName>\n" .
478 " <Description>\n";
479
480 foreach my $pair (@$record_metadata) {
481 my ($field, $value) = (@$pair);
482
483 # We're only interested in metadata from the database
484 next if ($field eq "lastmodified");
485 next if ($field eq "gsdlsourcefilename");
486 next if ($field eq "gsdldoctype");
487 next if ($field eq "FileFormat");
488
489 # Ignore the ^all metadata, since it will be invalid if the source metadata is changed
490 next if ($field =~ /\^all$/); # ISISPlug specific!
491
492 # Square brackets in metadata values need to be escaped so they don't confuse Greenstone/GLI
493 $value =~ s/\[/&\#091;/g;
494 $value =~ s/\]/&\#093;/g;
495
496 # Make $value XML-safe
497 $value =~ s/&/&amp;/g; # May mess up existing entities!
498 $value =~ s/</&lt;/g;
499 $value =~ s/>/&gt;/g;
500
501 # we are not allowed & in xml except in entities.
502 # if there are undefined entities then parsing will also crap out.
503 # should we be checking for them too?
504 # this may not get all possibilities
505 # $value =~ s/&([^;\s]*(\s|$))/&amp;$1/g;
506
507 # do we already have a namespace specified?
508 my $full_field = $field;
509 if ($meta_prefix ne "") {
510 $full_field =~ s/^\w+\.//;
511 $full_field = $meta_prefix.$full_field;
512 }
513
514 print $metadata_xml_file " <Metadata mode=\"accumulate\" name=\"$full_field\">$value</Metadata>\n";
515 }
516
517 print $metadata_xml_file
518 " </Description>\n" .
519 " </FileSet>\n";
520}
521
522sub obtain_document
523{
524 my ($document_file_full,$documents_directory,$orig_base_dir,$verbosity) = @_;
525
526 print STDERR "Obtaining document file $document_file_full...\n" if ($verbosity > 1);
527
528 my $document_file_name;
529 my $local_document_file;
530
531 # Document specified is on the web
532 if ($document_file_full =~ /^https?:/ || $document_file_full =~ /^ftp:/) {
533 $document_file_full =~ /([^\/]+)$/;
534 $document_file_name = $1;
535 $local_document_file = &util::filename_cat($documents_directory, $document_file_name);
536
537 my $wget_options = "--quiet";
538 $wget_options = "--verbose" if ($verbosity > 2);
539 $wget_options .= " --timestamping"; # Only re-download files if they're newer
540 my $wget_command = "wget $wget_options \"$document_file_full\" --output-document \"$local_document_file\"";
541 `$wget_command`;
542
543 # Check the document was obtained successfully
544 if (!-e $local_document_file) {
545 print STDERR "WARNING: Could not obtain document file $document_file_full\n";
546 }
547 }
548 # Document specified is on the disk
549 else {
550 # convert the dirseps in filepath to correct dir sep for OS
551 $document_file_full = &util::filename_cat($document_file_full);
552 my $dir_sep = &util::get_os_dirsep();
553
554 $document_file_full =~ m/(.+$dir_sep)?(.*)$/;
555 $document_file_name = $2;
556
557
558 my $is_absolute = File::Spec->file_name_is_absolute($document_file_full);
559 print STDERR "doc file full = $document_file_full\n";
560
561 if (!$is_absolute) {
562 $document_file_full
563 = &util::filename_cat($orig_base_dir,$document_file_full);
564 }
565
566 $local_document_file = &util::filename_cat($documents_directory, $document_file_name);
567
568 if (-e $document_file_full) {
569 &util::cp($document_file_full, $documents_directory);
570 }
571
572 # Check the document was obtained successfully
573 if (!-e $local_document_file) {
574 print STDERR "WARNING: Could not obtain document file $document_file_full\n";
575 }
576 else {
577 $orig_base_dir =~ s/\\/\\\\/g; # escape windows style slashes for the regex below
578 if ($document_file_full =~ m/^$orig_base_dir.*/) {
579 # file local to metadata record
580 # => copy has been made successfully, so remove original
581 &util::rm($document_file_full);
582 }
583 }
584 }
585
586 # If the document wasn't obtained successfully, create a .nul file for it
587 if (!-e $local_document_file) {
588 $document_file_name .= ".nul";
589 open(NULL_FILE, ">$local_document_file.nul");
590 close(NULL_FILE);
591 print STDERR "Creating a nul document $document_file_name\n";
592 }
593
594 return $document_file_name;
595}
596
597sub get_plugin_options {
598 my ($collectcfg, $plugin) = @_;
599
600 my $plugin_list = $collectcfg ->{'plugin'};
601
602 foreach my $pluginoptions (@$plugin_list) {
603 my $pluginname = shift @$pluginoptions;
604 next unless $pluginname eq $plugin;
605 map { $_ = "\"$_\""; } @$pluginoptions;
606 my $options = join (",", @$pluginoptions);
607 return $options;
608 }
609 return "";
610}
611
612&main(@ARGV);
613
Note: See TracBrowser for help on using the repository browser.