source: main/trunk/greenstone2/perllib/plugins/ConvertBinaryFile.pm@ 32280

Last change on this file since 32280 was 32280, checked in by ak19, 6 years ago

Implementing PDFv2paged_text (with pdfbox)

  • Property svn:keywords set to Author Date Id Revision
File size: 20.3 KB
Line 
1###########################################################################
2#
3# ConvertBinaryFile.pm -- plugin that facilitates conversion of binary files
4# through gsConvert.pl
5#
6# A component of the Greenstone digital library software
7# from the New Zealand Digital Library Project at the
8# University of Waikato, New Zealand.
9#
10# Copyright (C) 1999 New Zealand Digital Library Project
11#
12# This program is free software; you can redistribute it and/or modify
13# it under the terms of the GNU General Public License as published by
14# the Free Software Foundation; either version 2 of the License, or
15# (at your option) any later version.
16#
17# This program is distributed in the hope that it will be useful,
18# but WITHOUT ANY WARRANTY; without even the implied warranty of
19# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20# GNU General Public License for more details.
21#
22# You should have received a copy of the GNU General Public License
23# along with this program; if not, write to the Free Software
24# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25#
26###########################################################################
27
28# This plugin is inherited by such plugins as WordPlugin, PowerPointPlugin,
29# PostScriptPlugin,
30# RTFPlugin and PDFPlugin. It facilitates the conversion of these document types
31# to either HTML, Text or a series of images. It works by dynamically loading
32# an appropriate secondary plugin (HTMLPlug, StructuredHTMLPlug,
33# PagedImagePlugin or TextPlugin) based on the plugin argument 'convert_to'.
34
35package ConvertBinaryFile;
36
37use AutoExtractMetadata;
38use ghtml;
39use HTMLPlugin;
40use TextPlugin;
41use PagedImagePlugin;
42
43use strict;
44no strict 'refs'; # allow filehandles to be variables and viceversa
45no strict 'subs';
46use util;
47use FileUtils;
48
49
50sub BEGIN {
51 @ConvertBinaryFile::ISA = ('AutoExtractMetadata');
52}
53
54my $convert_to_list =
55 [ { 'name' => "auto",
56 'desc' => "{ConvertBinaryFile.convert_to.auto}" },
57 { 'name' => "html",
58 'desc' => "{ConvertBinaryFile.convert_to.html}" },
59 { 'name' => "text",
60 'desc' => "{ConvertBinaryFile.convert_to.text}" }
61 ];
62
63my $arguments =
64 [ { 'name' => "convert_to",
65 'desc' => "{ConvertBinaryFile.convert_to}",
66 'type' => "enum",
67 'reqd' => "yes",
68 'list' => $convert_to_list,
69 'deft' => "auto" },
70 { 'name' => "keep_original_filename",
71 'desc' => "{ConvertBinaryFile.keep_original_filename}",
72 'type' => "flag" },
73 { 'name' => "title_sub",
74 'desc' => "{HTMLPlugin.title_sub}",
75 'type' => "string",
76 #'type' => "regexp",
77 'deft' => "" },
78 { 'name' => "apply_fribidi",
79 'desc' => "{ConvertBinaryFile.apply_fribidi}",
80 'type' => "flag",
81 'reqd' => "no" },
82 { 'name' => "use_strings",
83 'desc' => "{ConvertBinaryFile.use_strings}",
84 'type' => "flag",
85 'reqd' => "no" },
86 ];
87
88my $options = { 'name' => "ConvertBinaryFile",
89 'desc' => "{ConvertBinaryFile.desc}",
90 'abstract' => "yes",
91 'inherits' => "yes",
92 'args' => $arguments };
93
94
95sub load_secondary_plugins
96{
97 my $self = shift (@_);
98 my ($class,$input_args,$hashArgOptLists) = @_;
99
100 my @convert_to_list = split(",",$self->{'convert_to_plugin'});
101 my $secondary_plugins = {};
102 # find the plugin
103
104 foreach my $convert_to (@convert_to_list) {
105 # load in "convert_to" plugin package
106 my $plugin_class = $convert_to;
107 my $plugin_package = $plugin_class.".pm";
108
109 my $colplugname = undef;
110 if (defined $ENV{'GSDLCOLLECTDIR'}) {
111 $colplugname = &FileUtils::filenameConcatenate($ENV{'GSDLCOLLECTDIR'},
112 "perllib","plugins",
113 $plugin_package);
114 }
115
116 my $mainplugname = &FileUtils::filenameConcatenate($ENV{'GSDLHOME'},
117 "perllib","plugins",
118 $plugin_package);
119
120 if ((defined $colplugname) && (-e $colplugname)) { require $colplugname;}
121 elsif (-e $mainplugname) { require $mainplugname; }
122 else {
123 &gsprintf(STDERR, "{plugin.could_not_find_plugin}\n",
124 $plugin_class);
125 die "\n";
126 }
127
128 # call its constructor with extra options that we've worked out!
129 my $arglist = $input_args->{$plugin_class};
130
131 my ($secondary_plugin);
132 eval("\$secondary_plugin = new $plugin_class([],\$arglist)");
133 die "$@" if $@;
134 $secondary_plugins->{$plugin_class} = $secondary_plugin;
135 }
136 $self->{'secondary_plugins'} = $secondary_plugins;
137}
138
139sub new {
140 my ($class) = shift (@_);
141 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
142 push(@$pluginlist, $class);
143 my $classPluginName = (defined $pluginlist->[0]) ? $pluginlist->[0] : $class;
144 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
145 push(@{$hashArgOptLists->{"OptList"}},$options);
146
147 my $self = new AutoExtractMetadata($pluginlist, $inputargs, $hashArgOptLists);
148
149 return bless $self, $class;
150}
151
152# should be called by subclasses after checking and setting
153# $self->{'convert_to'}
154sub set_standard_convert_settings {
155 my $self =shift (@_);
156
157 my $convert_to = $self->{'convert_to'};
158 if ($convert_to eq "auto") {
159 $convert_to = "html";
160 $self->{'convert_to'} = "html";
161 }
162
163 if ($convert_to =~ /^html/ || $convert_to =~ /pretty_html$/) { # may be html or html_multi, or )paged_)pretty_html with the new Xpdf's own pdftohtml
164 $self->{'convert_to_plugin'} = "HTMLPlugin";
165 $self->{'convert_to_ext'} = "html";
166 } elsif ($convert_to eq "text") {
167 $self->{'convert_to_plugin'} = "TextPlugin";
168 $self->{'convert_to_ext'} = "txt";
169 } elsif ($convert_to eq "structuredhtml") {
170 $self->{'convert_to_plugin'} = "StructuredHTMLPlugin";
171 $self->{'convert_to_ext'} = "html";
172 } elsif ($convert_to =~ /^pagedimg/ || $convert_to eq "paged_text") {
173 $self->{'convert_to_plugin'} = "PagedImagePlugin";
174 if($convert_to eq "paged_text") {
175 $self->{'convert_to_ext'} = "txt";
176 } else {
177 my ($convert_to_ext) = $convert_to =~ /pagedimg(?:txt)?\_(jpg|gif|png)/i; # the ?: prefix avoids capturing or else discards the optional 'txt' in 'pagedimgtxt',
178 # so that we can consider the actual portion we want to capture: the img type
179 $convert_to_ext = 'jpg' unless defined $convert_to_ext;
180 $self->{'convert_to_ext'} = $convert_to_ext;
181 }
182 }
183}
184sub init {
185 my $self = shift (@_);
186 my ($verbosity, $outhandle, $failhandle) = @_;
187
188 $self->SUPER::init($verbosity,$outhandle,$failhandle);
189
190 my $secondary_plugins = $self->{'secondary_plugins'};
191
192 foreach my $plug_name (keys %$secondary_plugins) {
193 my $plugin = $secondary_plugins->{$plug_name};
194 $plugin->init($verbosity,$outhandle,$failhandle);
195 }
196}
197
198sub deinit {
199 # called only once, after all plugin passes have been done
200
201 my ($self) = @_;
202
203 my $secondary_plugins = $self->{'secondary_plugins'};
204
205 foreach my $plug_name (keys %$secondary_plugins) {
206 my $plugin = $secondary_plugins->{$plug_name};
207 $plugin->deinit();
208 }
209}
210
211sub convert_post_process
212{
213 # by default do no post processing
214 return;
215}
216
217
218# Run conversion utility on the input file.
219#
220# The conversion takes place in a collection specific 'tmp' directory so
221# that we don't accidentally damage the input.
222#
223# The desired output type is indicated by $output_ext. This is usually
224# something like "html" or "word", but can be "best" (or the empty string)
225# to indicate that the conversion utility should do the best it can.
226sub tmp_area_convert_file {
227 my $self = shift (@_);
228 my ($output_ext, $input_filename, $textref) = @_;
229
230 my $outhandle = $self->{'outhandle'};
231 my $convert_to = $self->{'convert_to'};
232 my $failhandle = $self->{'failhandle'};
233 my $convert_to_ext = $self->{'convert_to_ext'};
234
235
236 my $upgraded_input_filename = &util::upgrade_if_dos_filename($input_filename);
237
238 # derive tmp filename from input filename
239 my ($tailname, $dirname, $suffix)
240 = &File::Basename::fileparse($upgraded_input_filename, "\\.[^\\.]+\$");
241
242 # softlink to collection tmp dir
243 my $tmp_dirname = &util::get_timestamped_tmp_folder();
244 if (defined $tmp_dirname) {
245 $self->{'tmp_dir'} = $tmp_dirname;
246 } else {
247 $tmp_dirname = $dirname;
248 }
249
250# # convert to utf-8 otherwise we have problems with the doc.xml file later on
251# my $utf8_tailname = (&unicode::check_is_utf8($tailname)) ? $tailname : $self->filepath_to_utf8($tailname);
252
253 # make sure filename to be used can be stored OK in a UTF-8 compliant doc.xml file
254 my $utf8_tailname = &unicode::raw_filename_to_utf8_url_encoded($tailname);
255
256
257 # URLEncode this since htmls with images where the html filename is utf8 don't seem
258 # to work on Windows (IE or Firefox), as browsers are looking for filesystem-encoded
259 # files on the filesystem.
260 $utf8_tailname = &util::rename_file($utf8_tailname, $self->{'file_rename_method'}, "without_suffix");
261
262 my $lc_suffix = lc($suffix);
263 my $tmp_filename = &FileUtils::filenameConcatenate($tmp_dirname, "$utf8_tailname$lc_suffix");
264
265 # If gsdl is remote, we're given relative path to input file, of the form import/utf8_tailname.suffix
266 # But we can't softlink to relative paths. Therefore, we need to ensure that
267 # the input_filename is the absolute path, see http://perldoc.perl.org/File/Spec.html
268 my $ensure_path_absolute = 1; # true
269 &FileUtils::softLink($input_filename, $tmp_filename, $ensure_path_absolute);
270
271 my $output_filename = $self->run_conversion_command($tmp_dirname, $tmp_filename,
272 $utf8_tailname, $lc_suffix, $tailname, $suffix);
273
274 return $output_filename;
275}
276
277# The latter half of tmp_area_convert_file: runs the conversion command and returns the output file name
278# Split from tmp_area_convert_file because UnknownConverterPlugin can then inherit all of
279# tmp_area_convert_file and only needs to override this part:
280sub run_conversion_command {
281 my $self = shift (@_);
282 my ($tmp_dirname, $tmp_filename, $utf8_tailname, $lc_suffix, $tailname, $suffix) = @_;
283
284 my $outhandle = $self->{'outhandle'};
285 my $convert_to = $self->{'convert_to'};
286 my $failhandle = $self->{'failhandle'};
287
288 my $verbosity = $self->{'verbosity'};
289 if ($verbosity > 0) {
290 print $outhandle "Converting $tailname$suffix to $convert_to format\n";
291 }
292
293 my $errlog = &FileUtils::filenameConcatenate($tmp_dirname, "err.log");
294
295 # Execute the conversion command and get the type of the result,
296 # making sure the converter gives us the appropriate output type
297 my $output_type=$self->{'convert_to'};
298# if ($convert_to =~ m/PagedImage/i) {
299# $output_type = lc($convert_to)."_".lc($convert_to_ext);
300# } else {
301# $output_type = lc($convert_to);
302# }
303
304 my $cmd = "\"".&util::get_perl_exec()."\" -S gsConvert.pl -verbose $verbosity ";
305 if (defined $self->{'convert_options'}) {
306 $cmd .= $self->{'convert_options'} . " ";
307 }
308 if ($self->{'use_strings'}) {
309 $cmd .= "-use_strings ";
310 }
311 $cmd .= "-errlog \"$errlog\" -output $output_type \"$tmp_filename\"";
312 print STDERR "calling cmd $cmd\n";
313 $output_type = `$cmd`;
314
315 # remove symbolic link to original file
316 &FileUtils::removeFiles($tmp_filename);
317
318 # Check STDERR here
319 chomp $output_type;
320 if ($output_type eq "fail") {
321 print $outhandle "Could not convert $tailname$suffix to $convert_to format\n";
322 print $failhandle "$tailname$suffix: " . ref($self) . " failed to convert to $convert_to\n";
323 # The following meant that if a conversion failed, the document would be counted twice - do we need it for anything?
324 #$self->{'num_not_processed'} ++;
325 if (-s "$errlog") {
326 open(ERRLOG, "$errlog");
327 while (<ERRLOG>) {
328 print $outhandle "$_";
329 }
330 print $outhandle "\n";
331 close ERRLOG;
332 }
333 &FileUtils::removeFiles("$errlog") if (-e "$errlog");
334 return "";
335 }
336
337 # store the *actual* output type and return the output filename
338 # it's possible we requested conversion to html, but only to text succeeded
339 #$self->{'convert_to_ext'} = $output_type;
340 if ($output_type =~ /html/i) {
341 $self->{'converted_to'} = "HTML";
342 } elsif ($output_type =~ /te?xt/i) {
343 $self->{'converted_to'} = "Text";
344 } elsif ($output_type =~ /item/i){
345 $self->{'converted_to'} = "PagedImage";
346 }
347
348 my $output_filename = $tmp_filename;
349 if ($output_type =~ /item/i) {
350 # running under windows
351 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
352 $output_filename = $tmp_dirname . "\\$utf8_tailname\\" . $utf8_tailname . ".$output_type";
353 } else {
354 $output_filename = $tmp_dirname . "\/$utf8_tailname\/" . $utf8_tailname . ".$output_type";
355 }
356 } else {
357 $output_filename =~ s/$lc_suffix$/.$output_type/;
358 }
359
360 return $output_filename;
361}
362
363
364# Override BasPlug read_into_doc_obj - we need to call secondary plugin stuff
365sub read_into_doc_obj {
366 my $self = shift (@_);
367 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
368
369 my $outhandle = $self->{'outhandle'};
370
371 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
372
373 my $output_ext = $self->{'convert_to_ext'};
374 my $conv_filename = "";
375 $conv_filename = $self->tmp_area_convert_file($output_ext, $filename_full_path);
376
377 if ("$conv_filename" eq "") {return -1;} # had an error, will be passed down pipeline
378
379 my $output_type=$self->{'convert_to'};
380 if (!&FileUtils::fileExists($conv_filename)) {return -1;}
381 $self->{'conv_filename'} = $conv_filename;
382 $self->convert_post_process($conv_filename);
383
384 # Check if, after post-processing, the final expected output file has changed
385 # And if it has, check that the final output file now exists after post processing
386 if(defined $self->{'conv_filename_after_post_process'}) {
387 $conv_filename = $self->{'conv_filename_after_post_process'};
388 if (!&FileUtils::fileExists($conv_filename)) {return -1;}
389 }
390
391 # Run the "fribidi" (http://fribidi.org) Unicode Bidirectional Algorithm program over the converted file
392 # Added for fixing up Persian PDFs after being processed by pdftohtml, but may be useful in other cases too
393 if ($self->{'apply_fribidi'} && $self->{'converted_to'} =~ /(HTML|Text)/) {
394 my $fribidi_command = "fribidi \"$conv_filename\" >\"${conv_filename}.tmp\"";
395 if (system($fribidi_command) != 0) {
396 print STDERR "ERROR: Cannot run fribidi on \"$conv_filename\".\n";
397 }
398 else {
399 &FileUtils::moveFiles("${conv_filename}.tmp", $conv_filename);
400 }
401 }
402
403 my $secondary_plugins = $self->{'secondary_plugins'};
404 my $num_secondary_plugins = scalar(keys %$secondary_plugins);
405
406 if ($num_secondary_plugins == 0) {
407 print $outhandle "Warning: No secondary plugin to use in conversion. Skipping $file\n";
408 return 0; # effectively block it
409 }
410
411 my @plugin_names = keys %$secondary_plugins;
412 my $plugin_name = shift @plugin_names;
413
414 if ($num_secondary_plugins > 1) {
415 print $outhandle "Warning: Multiple secondary plugins not supported yet! Choosing $plugin_name\n.";
416 }
417
418 my $secondary_plugin = $secondary_plugins->{$plugin_name};
419
420 # note: metadata is not carried on to the next level
421## **** I just replaced $metadata with {} in following
422 my ($rv,$doc_obj)
423 = $secondary_plugin->read_into_doc_obj ($pluginfo,"", $conv_filename, $block_hash, {}, $processor, $maxdocs, $total_count, $gli);
424
425 if ((!defined $rv) || ($rv<1)) {
426 # wasn't processed
427 return $rv;
428 }
429
430 # Override previous gsdlsourcefilename set by secondary plugin
431 my $collect_file = &util::filename_within_collection($filename_full_path);
432 my $collect_conv_file = &util::filename_within_collection($conv_filename);
433 $doc_obj->set_source_filename ($collect_file, $self->{'file_rename_method'});
434 ## set_source_filename does not set the doc_obj source_path which is used in archives dbs for incremental
435 # build. so set it manually.
436 $doc_obj->set_source_path($filename_full_path);
437 $doc_obj->set_converted_filename($collect_conv_file);
438
439 my $plugin_filename_encoding = $self->{'filename_encoding'};
440 my $filename_encoding = $self->deduce_filename_encoding($file,$metadata,$plugin_filename_encoding);
441 $self->set_Source_metadata($doc_obj, $filename_full_path, $filename_encoding);
442
443 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
444 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "FileSize", (-s $filename_full_path));
445
446 # ****
447 my ($tailname, $dirname, $suffix)
448 = &File::Basename::fileparse($filename_full_path, "\\.[^\\.]+\$");
449 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "FilenameRoot", $tailname);
450
451 # do plugin specific processing of doc_obj
452 unless (defined ($self->process($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
453 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
454 return -1;
455 }
456
457 my $topsection = $doc_obj->get_top_section();
458 $self->add_associated_files($doc_obj, $filename_full_path);
459
460 # extra_metadata is already called by sec plugin in process??
461 $self->extra_metadata($doc_obj, $topsection, $metadata); # do we need this here??
462 # do any automatic metadata extraction
463 $self->auto_extract_metadata ($doc_obj);
464
465 # have we found a Title??
466 $self->title_fallback($doc_obj,$topsection,$filename_no_path);
467
468 # force a new OID - this will use OIDtype option set for this plugin.
469 $self->add_OID($doc_obj, 1);
470
471 return (1, $doc_obj);
472
473}
474
475sub process {
476 my $self = shift (@_);
477 my ($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
478
479 return $self->process_type($base_dir, $file, $doc_obj);
480}
481
482# do plugin specific processing of doc_obj for doc_ext type
483sub process_type {
484 my $self = shift (@_);
485 my ($base_dir, $file, $doc_obj) = @_;
486
487 # need to check that not empty
488 my ($doc_ext) = $file =~ /\.(\w+)$/;
489 $doc_ext = lc($doc_ext);
490 my $file_type = "unknown";
491 $file_type = $self->{'file_type'} if defined $self->{'file_type'};
492
493 # associate original file with doc object
494 my $cursection = $doc_obj->get_top_section();
495 my $filename = &FileUtils::filenameConcatenate($base_dir, $file);
496 my $assocfilename = "doc.$doc_ext";
497 if ($self->{'keep_original_filename'} == 1) {
498 # this should be the same filename that was used for the Source and SourceFile metadata,
499 # as we will use SourceFile in the srclink (below)
500 $assocfilename = $doc_obj->get_assocfile_from_sourcefile();
501 }
502
503 $doc_obj->associate_file($filename, $assocfilename, undef, $cursection);
504
505 # We use set instead of add here because we only want one value
506 $doc_obj->set_utf8_metadata_element($cursection, "FileFormat", $file_type);
507 my $srclink_filename = "doc.$doc_ext";
508 if ($self->{'keep_original_filename'} == 1) {
509 $srclink_filename = $doc_obj->get_sourcefile();
510 }
511 # srclink_file is now deprecated because of the "_" in the metadataname. Use srclinkFile
512 $doc_obj->add_utf8_metadata ($cursection, "srcicon", "_icon".$doc_ext."_");
513 $doc_obj->add_utf8_metadata ($cursection, "srclink_file", $srclink_filename);
514 $doc_obj->add_utf8_metadata ($cursection, "srclinkFile", $srclink_filename);
515 return 1;
516}
517
518sub clean_up_after_doc_obj_processing {
519 my $self = shift(@_);
520
521 my $tmp_dir = $self->{'tmp_dir'};
522 if (defined $tmp_dir && -d $tmp_dir) {
523 ##print STDERR "**** Suppressing clean up of tmp dir\n";
524 &FileUtils::removeFilesRecursive($tmp_dir);
525 $self->{'tmp_dir'} = undef;
526 }
527
528
529}
530
531# This sub is shared across PowerPointPlugin and UnknownConverterPlugin,
532# so it's been copied into here from the former.
533sub generate_item_file {
534 my $self = shift(@_);
535 my ($input_filename) = @_;
536 my $outhandle = $self->{'outhandle'};
537 my ($tailname, $dirname, $suffix)
538 = &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");
539
540 my $plugin_name = $self->{'plugin_type'}; # inherited from BaseImporter
541
542 # find all the files in the directory
543 if (!opendir (DIR, $dirname)) {
544 print $outhandle "$plugin_name: Couldn't read directory $dirname\n";
545 return $input_filename;
546 }
547
548 my @dir = readdir (DIR);
549 closedir (DIR);
550
551 # start the item file
552 my $itemfile_name = &util::filename_cat($dirname, "$tailname.item");
553
554 # encoding specification????
555 if (!open (ITEMFILE, ">$itemfile_name")) {
556 print $outhandle "$plugin_name: Couldn't open $itemfile_name for writing\n";
557 }
558 print ITEMFILE "<GeneratedBy>$plugin_name\n";
559 # print the first page
560 my @sorted_dir = sort alphanum_sort @dir;
561 for (my $i = 0; $i < scalar(@sorted_dir); $i++) {
562 my $file = $sorted_dir[$i];
563 if ($file =~ /^img(\d+)\.jpg$/) {
564 my $num = $1;
565 $self->tidy_up_html(&util::filename_cat($dirname, "text$num.html"));
566 print ITEMFILE "$num:img$num.jpg:text$num.html:\n";
567 }
568 }
569 close ITEMFILE;
570 return $itemfile_name;
571
572}
573
5741;
575
576
577
578
579
580
581
Note: See TracBrowser for help on using the repository browser.