source: main/trunk/greenstone2/perllib/plugins/UnknownConverterPlugin.pm@ 31763

Last change on this file since 31763 was 31763, checked in by ak19, 7 years ago

Fixing somethings before attempting to refactor tmp_area_convert_file

File size: 18.4 KB
Line 
1###########################################################################
2#
3# UnknownConverterPlugin.pm -- plugin that runs the provided cmdline cmd
4# to launch an custom unknown external conversion application that will
5# convert from some custom unknown format to one of txt, html or xml.
6#
7# A component of the Greenstone digital library software
8# from the New Zealand Digital Library Project at the
9# University of Waikato, New Zealand.
10#
11# Copyright (C) 1999-2005 New Zealand Digital Library Project
12#
13# This program is free software; you can redistribute it and/or modify
14# it under the terms of the GNU General Public License as published by
15# the Free Software Foundation; either version 2 of the License, or
16# (at your option) any later version.
17#
18# This program is distributed in the hope that it will be useful,
19# but WITHOUT ANY WARRANTY; without even the implied warranty of
20# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21# GNU General Public License for more details.
22#
23# You should have received a copy of the GNU General Public License
24# along with this program; if not, write to the Free Software
25# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26#
27###########################################################################
28
29package UnknownConverterPlugin;
30
31use strict;
32no strict 'subs';
33no strict 'refs'; # allow filehandles to be variables and viceversa
34
35use ConvertBinaryFile;
36use UnknownPlugin;
37
38# TO DO:
39# - error messages and other display strings need to go into strings.properties
40# - Have a TEMPDIR placeholder in the command, which, if present, gets replaced with the usual tempdir location
41# of a collection, and in which case we have to clean up intermediate files generated in there at the end?
42# Add a check that the generated file or files generated in the output dir match the convert_to option selected
43# before trying to process them
44# Add option that says where output comes from: stdout of the process, file that gets generated, folder.
45# At present, a file or folder of files is assumed.
46# Need to look in there for files with extension process_ext.
47# Do we also need a html_multi option to convert_to? Support html_multi as output?
48# Then a folder of html files is generated per document?
49# OR Flag that indicates whether an html file + associated folder (such as of images) gets generated. And name of assoc folder. Such output gets generated for instance when a doc file is replaced by its html version.
50
51sub BEGIN {
52 @UnknownConverterPlugin::ISA = ('UnknownPlugin', 'ConvertBinaryFile');
53}
54
55my $convert_to_list =
56 [ { 'name' => "text",
57 'desc' => "{ConvertBinaryFile.convert_to.text}" },
58 { 'name' => "html",
59 'desc' => "{ConvertBinaryFile.convert_to.html}" },
60 { 'name' => "pagedimg_jpg",
61 'desc' => "{ConvertBinaryFile.convert_to.pagedimg_jpg}" },
62 { 'name' => "pagedimg_gif",
63 'desc' => "{ConvertBinaryFile.convert_to.pagedimg_gif}" },
64 { 'name' => "pagedimg_png",
65 'desc' => "{ConvertBinaryFile.convert_to.pagedimg_png}" }
66 ];
67
68my $arguments =
69 [ { 'name' => "exec_cmd",
70 'desc' => "{UnknownConverterPlugin.exec_cmd}",
71 'type' => "string",
72 'deft' => "",
73 'reqd' => "yes" },
74 { 'name' => "convert_to",
75 'desc' => "{ConvertBinaryFile.convert_to}",
76 'type' => "enum",
77 'reqd' => "yes",
78 'list' => $convert_to_list,
79 'deft' => "text" } ];
80
81my $options = { 'name' => "UnknownConverterPlugin",
82 'desc' => "{UnknownConverterPlugin.desc}",
83 'abstract' => "no",
84 'inherits' => "yes",
85 'args' => $arguments };
86
87
88sub new {
89 my ($class) = shift (@_);
90 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
91 push(@$pluginlist, $class);
92
93 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
94 push(@{$hashArgOptLists->{"OptList"}},$options);
95
96 my $unknown_converter_self = new UnknownPlugin($pluginlist, $inputargs, $hashArgOptLists);
97 my $cbf_self = new ConvertBinaryFile($pluginlist, $inputargs, $hashArgOptLists);
98
99 # Need to feed the superclass plugins to merge_inheritance() below in the order that the
100 # superclass plugins were declared in the ISA listing earlier in this file:
101 my $self = BaseImporter::merge_inheritance($unknown_converter_self, $cbf_self);
102
103 $self = bless $self, $class;
104
105my $outhandle = $self->{'outhandle'};
106 print STDERR "\n\n**** convert_to is |" . $self->{'convert_to'} . "|\n\n";
107 if(!defined $self->{'convert_to'}) {
108 $self->{'convert_to'} = "text"; # why do I have to set a value for convert_to here, when a default's already set at the start of this file???????
109 }
110
111 # Convert_To set up, including secondary_plugins for processing the text or html generated
112 # set convert_to_plugin and convert_to_ext
113 $self->set_standard_convert_settings();
114
115 my $secondary_plugin_name = $self->{'convert_to_plugin'};
116 my $secondary_plugin_options = $self->{'secondary_plugin_options'};
117
118 if (!defined $secondary_plugin_options->{$secondary_plugin_name}) {
119 $secondary_plugin_options->{$secondary_plugin_name} = [];
120 }
121 my $specific_options = $secondary_plugin_options->{$secondary_plugin_name};
122
123 # using defaults for secondary plugins, taken from RTFPlugin
124 push(@$specific_options, "-file_rename_method", "none");
125 push(@$specific_options, "-extract_language") if $self->{'extract_language'};
126 if ($secondary_plugin_name eq "TextPlugin") {
127 push(@$specific_options, "-input_encoding", "utf8");
128 }
129 elsif ($secondary_plugin_name eq "HTMLPlugin") {
130 push(@$specific_options, "-description_tags") if $self->{'description_tags'};
131 push(@$specific_options, "-processing_tmp_files");
132 }
133 elsif ($secondary_plugin_name eq "PagedImagePlugin") {
134 push(@$specific_options, "-screenviewsize", "1000");
135 push(@$specific_options, "-enable_cache");
136 push(@$specific_options, "-processing_tmp_files");
137 }
138
139 # bless again, copied from PDFPlugin, PowerPointPlugin
140 $self = bless $self, $class;
141 $self->load_secondary_plugins($class,$secondary_plugin_options,$hashArgOptLists);
142 return $self;
143}
144
145# Called by UnknownPlugin::process()
146# Overriding here to ensure that the NoText flag (metadata) and dummy text are not set,
147# since, unlike UnknownPlugin, this plugin has a chance of extracting text from the unknown file format
148sub add_dummy_text {
149 my $self = shift(@_);
150}
151
152# Are init, begin and deinit necessary (will they not get called automatically)?
153# Copied here from PDFPlugin, PowerPointPlugin
154# https://stackoverflow.com/questions/42885207/why-doesnt-class-supernew-call-the-constructors-of-all-parent-classes-when
155# "$class->SUPER::new always calls A::new because A comes before B in @ISA. See method resolution order in perlobj: ..."
156# https://stackoverflow.com/questions/15414696/when-using-multiple-inheritance-in-perl-is-there-a-way-to-indicate-which-super-f
157sub init {
158 my $self = shift (@_);
159
160 # ConvertBinaryFile init
161 $self->ConvertBinaryFile::init(@_);
162}
163
164sub begin {
165 my $self = shift (@_);
166
167 $self->ConvertBinaryFile::begin(@_);
168
169}
170
171sub deinit {
172 my $self = shift (@_);
173
174 $self->ConvertBinaryFile::deinit(@_);
175
176}
177
178# overridden to run the custom conversion command here in place of gsConvert.pl called by ConvertBinaryFile.pm
179sub tmp_area_convert_file {
180 # should we first hardlink the output files/folder to tmp area, so we won't be working across drives?
181
182 my $self = shift (@_);
183 my ($output_ext, $input_filename, $textref) = @_;
184
185 #### COPIED FROM ConvertBinaryFile::tmp_area_convert_file()
186 my $outhandle = $self->{'outhandle'};
187 my $convert_to = $self->{'convert_to'};
188 my $failhandle = $self->{'failhandle'};
189 my $convert_to_ext = $self->{'convert_to_ext'}; #set by ConvertBinaryFile::set_standard_convert_settings()
190
191
192 my $upgraded_input_filename = &util::upgrade_if_dos_filename($input_filename);
193
194 # derive tmp filename from input filename
195 my ($tailname, $dirname, $suffix)
196 = &File::Basename::fileparse($upgraded_input_filename, "\\.[^\\.]+\$");
197
198 # softlink to collection tmp dir
199 my $tmp_dirname = &util::get_timestamped_tmp_folder();
200 if (defined $tmp_dirname) {
201 $self->{'tmp_dir'} = $tmp_dirname;
202 } else {
203 $tmp_dirname = $dirname;
204 }
205
206# # convert to utf-8 otherwise we have problems with the doc.xml file later on
207# my $utf8_tailname = (&unicode::check_is_utf8($tailname)) ? $tailname : $self->filepath_to_utf8($tailname);
208
209 # make sure filename to be used can be stored OK in a UTF-8 compliant doc.xml file
210 my $utf8_tailname = &unicode::raw_filename_to_utf8_url_encoded($tailname);
211
212
213 # URLEncode this since htmls with images where the html filename is utf8 don't seem
214 # to work on Windows (IE or Firefox), as browsers are looking for filesystem-encoded
215 # files on the filesystem.
216 $utf8_tailname = &util::rename_file($utf8_tailname, $self->{'file_rename_method'}, "without_suffix");
217
218 my $lc_suffix = lc($suffix);
219 my $tmp_filename = &FileUtils::filenameConcatenate($tmp_dirname, "$utf8_tailname$lc_suffix");
220
221 # If gsdl is remote, we're given relative path to input file, of the form import/utf8_tailname.suffix
222 # But we can't softlink to relative paths. Therefore, we need to ensure that
223 # the input_filename is the absolute path, see http://perldoc.perl.org/File/Spec.html
224 my $ensure_path_absolute = 1; # true
225 &FileUtils::softLink($input_filename, $tmp_filename, $ensure_path_absolute);
226 my $verbosity = $self->{'verbosity'};
227 if ($verbosity > 0) {
228 print $outhandle "Converting $tailname$suffix to $convert_to format with extension $convert_to_ext\n";
229 }
230
231 my $errlog = &FileUtils::filenameConcatenate($tmp_dirname, "err.log");
232
233
234 my $output_type=$self->{'convert_to'};
235
236 # store the *actual* output type and return the output filename
237 # it's possible we requested conversion to html, but only to text succeeded
238 #$self->{'convert_to_ext'} = $output_type;
239 if ($output_type =~ /html/i) {
240 $self->{'converted_to'} = "HTML";
241 } elsif ($output_type =~ /te?xt/i) {
242 $self->{'converted_to'} = "Text";
243 } elsif ($output_type =~ /item/i || $output_type =~ /^pagedimg/){
244 $self->{'converted_to'} = "PagedImage";
245 }
246
247 my $output_filename = $tmp_filename;
248 my $output_dirname;
249 if ($output_type =~ /item/i || $output_type =~ /^pagedimg/) {
250 # running under windows
251 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
252 $output_dirname = $tmp_dirname . "\\$utf8_tailname\\";
253 } else {
254 $output_dirname = $tmp_dirname . "\/$utf8_tailname\/";
255 }
256 $output_filename = $output_dirname . $utf8_tailname . ".item";
257 } else {
258 $output_filename =~ s/$lc_suffix$/.$output_type/;
259 }
260
261 #### END COPIED FROM ConvertBinaryFile::tmp_area_convert_file()
262
263 # Execute the conversion command and get the type of the result,
264 # making sure the converter gives us the appropriate output type
265
266 # On Linux: if the program isn't installed, $? tends to come back with 127, in any case neither 0 nor 1.
267 # On Windows: echo %ERRORLEVEL% ends up as 9009 if the program is not installed.
268 # If running the command returns 0, let's assume success and so the act of running the command
269 # should produce either a text file or output to stdout.
270
271 my $plugin_name = $self->{'plugin_type'}; # inherited from BaseImporter
272
273 my $cmd = $self->{'exec_cmd'};
274 if(!$cmd) { # empty string for instance
275 print $outhandle "$plugin_name Conversion error: a command to execute is required, cmd provided is |$cmd|\n";
276 return "";
277 }
278
279 # HARDCODING CMD FOR NOW
280 #$cmd ="/Scratch/ak19/gs3-svn-15Nov2016/packages/jre/bin/java -cp \"/Scratch/ak19/gs3-svn-15Nov2016/gs2build/ext/pdf-box/lib/java/pdfbox-app.jar\" -Dline.separator=\"<br />\" org.apache.pdfbox.ExtractText -html \"/Scratch/ak19/tutorial_sample_files/pdfbox/A9-access-best-practices.pdf\" \"/Scratch/ak19/gs3-svn-15Nov2016/pdf-tmp/1.html\"";
281
282 #$cmd ="/Scratch/ak19/gs3-svn-15Nov2016/packages/jre/bin/java -cp \"/Scratch/ak19/gs3-svn-15Nov2016/gs2build/ext/pdf-box/lib/java/pdfbox-app.jar\" -Dline.separator=\"<br />\" org.apache.pdfbox.ExtractText -html %INPUT_FILE %OUTPUT";
283
284 # replace occurrences of placeholders in cmd string
285 #$cmd =~ s@\"@\\"@g;
286 $cmd =~ s@%INPUT_FILE@\"$input_filename\"@g;
287 if(defined $output_dirname) {
288 $cmd =~ s@%OUTPUT@\"$output_dirname\"@g;
289 } else {
290 $cmd =~ s@%OUTPUT@\"$output_filename\"@g;
291 }
292
293 # Some debugging
294 if ($self->{'verbosity'} > 2) {
295 print STDERR "$plugin_name: executing conversion cmd \n|$cmd|\n";
296 print STDERR " on infile |$input_filename|\n";
297 print STDERR " to produce expected $output_filename\n";
298 }
299
300 # Run the command at last
301 my $status = system($cmd);
302
303 if($status == 127 || $status == 9009) { # means the cmd isn't recognised on Unix and Windows, respectively
304 print $outhandle "$plugin_name Conversion error: cmd unrecognised, may not be installed (got $status when running $cmd)\n";
305 return "";
306 }
307
308 if($status != 0) {
309 print $outhandle "$plugin_name Conversion error: conversion failed with exit value $status\n";
310 return "";
311 }
312
313 # remove symbolic link to original file
314 &FileUtils::removeFiles($tmp_filename);
315
316
317 if(defined $output_dirname && ! -d $output_dirname) {
318 print $outhandle "$plugin_name Conversion error: Output directory $output_dirname doesn't exist\n";
319 return "";
320 }
321 elsif (! -f $output_filename) {
322 print $outhandle "$plugin_name Conversion error: Output file $output_filename doesn't exist\n";
323 return "";
324 }
325
326 # else, conversion success
327
328 # if multiple images were generated by running the conversion
329 if ($self->{'convert_to'} =~ /^pagedimg/) {
330 my $item_filename = $self->generate_item_file($output_filename);
331
332 if (!-e $item_filename) {
333 print $outhandle "$plugin_name Conversion error: Item file $item_filename was not generated\n";
334 return "";
335 }
336 $output_filename = $item_filename;
337 }
338
339 $self->{'output_dirname'} = $output_dirname;
340 $self->{'output_filename'} = $output_filename;
341
342 return $output_filename;
343}
344
345# Copied from PowerPointPlugin, with some modifications
346# override default read in some situations, as the conversion of ppt to html results in many files, and we want them all to be processed.
347sub read {
348 my $self = shift (@_);
349 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
350
351 # can we process this file??
352 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
353
354 return undef unless $self->can_process_this_file($filename_full_path);
355
356 my $is_output_dir = (defined $self->{'output_dirname'}) ? 1 : 0;
357
358 # we are only doing something special if we have a directory of html files
359 #if ($is_output_dir || $self->{'convert_to'} ne "html") {
360 if ($self->{'convert_to'} ne "html_multi") {
361 return $self->BaseImporter::read(@_); # no read in ConvertBinaryFile.pm
362 }
363 my $outhandle = $self->{'outhandle'};
364 print STDERR "<Processing n='$file' p='$self->{'plugin_type'}'>\n" if ($gli);
365 print $outhandle "$self->{'plugin_type'} processing $file\n"
366 if $self->{'verbosity'} > 1;
367
368 my $conv_filename = $self->tmp_area_convert_file("html", $filename_full_path); # uses our overridden version
369 if ("$conv_filename" eq "") {return -1;} # had an error, will be passed down pipeline
370 if (! -e "$conv_filename") {return -1;}
371
372 my ($tailname, $html_dirname, $suffix)
373 = &File::Basename::fileparse($conv_filename, "\\.[^\\.]+\$");
374
375 my $collect_file = &util::filename_within_collection($filename_full_path);
376 my $dirname_within_collection = &util::filename_within_collection($html_dirname);
377 my $secondary_plugin = $self->{'secondary_plugins'}->{"HTMLPlugin"};
378
379 my @dir;
380 if (!opendir (DIR, $html_dirname)) {
381 print $outhandle "PowerPointPlugin: Couldn't read directory $html_dirname\n";
382 # just process the original file
383 @dir = ("$tailname.$suffix");
384
385 } else {
386 @dir = readdir (DIR);
387 closedir (DIR);
388 }
389
390 foreach my $file (@dir) {
391 next unless $file =~ /\.html$/;
392
393 my ($rv, $doc_obj) =
394 $secondary_plugin->read_into_doc_obj ($pluginfo,"", &util::filename_cat($html_dirname,$file), $block_hash, {}, $processor, $maxdocs, $total_count, $gli);
395 if ((!defined $rv) || ($rv<1)) {
396 # wasn't processed
397 return $rv;
398 }
399
400 # next block copied from ConvertBinaryFile
401 # from here ...
402 # Override previous gsdlsourcefilename set by secondary plugin
403
404 $doc_obj->set_source_filename ($collect_file, $self->{'file_rename_method'});
405 ## set_source_filename does not set the doc_obj source_path which is used in archives dbs for incremental
406 # build. so set it manually.
407 $doc_obj->set_source_path($filename_full_path);
408 $doc_obj->set_converted_filename(&util::filename_cat($dirname_within_collection, $file));
409
410 my $plugin_filename_encoding = $self->{'filename_encoding'};
411 my $filename_encoding = $self->deduce_filename_encoding($file,$metadata,$plugin_filename_encoding);
412 $self->set_Source_metadata($doc_obj, $filename_full_path,$filename_encoding);
413
414 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
415 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "FileSize", (-s $filename_full_path));
416
417
418 my ($tailname, $dirname, $suffix)
419 = &File::Basename::fileparse($filename_full_path, "\\.[^\\.]+\$");
420 $doc_obj->set_utf8_metadata_element($doc_obj->get_top_section(), "FilenameRoot", $tailname);
421
422
423 my $topsection = $doc_obj->get_top_section();
424 $self->add_associated_files($doc_obj, $filename_full_path);
425
426 # extra_metadata is already called by sec plugin in process??
427 $self->extra_metadata($doc_obj, $topsection, $metadata); # do we need this here??
428 # do any automatic metadata extraction
429 $self->auto_extract_metadata ($doc_obj);
430
431 # have we found a Title??
432 $self->title_fallback($doc_obj,$topsection,$filename_no_path);
433
434 # use the one generated by HTMLPlugin, otherwise they all end up with same id.
435 #$self->add_OID($doc_obj);
436 # to here...
437
438 # process it
439 $processor->process($doc_obj);
440 undef $doc_obj;
441 }
442 $self->{'num_processed'} ++;
443
444 # deleted some commented out code here that exists in PowerPointPlugin
445
446 # for UnknownConverterPlugin, don't delete any temp files that the conversion may have created?
447 # as we don't know where it was created. No. Now creating in tmp.
448 $self->clean_up_after_doc_obj_processing();
449
450
451 # if process_status == 1, then the file has been processed.
452 return 1;
453
454}
455
456# use the read_into_doc_obj inherited from ConvertBinaryFile "to call secondary plugin stuff"
457sub read_into_doc_obj {
458 my $self = shift (@_);
459 $self->ConvertBinaryFile::read_into_doc_obj(@_);
460}
461
462sub process {
463 my $self = shift (@_);
464 $self->UnknownPlugin::process(@_);
465}
466
467
4681;
Note: See TracBrowser for help on using the repository browser.