source: trunk/gsdl/bin/script/gsConvert.pl@ 2060

Last change on this file since 2060 was 2060, checked in by jrm21, 23 years ago

(system($cmd)>0) : system can return -1 if the cmd couldn't be

executed, as opposed to the cmd returning an error code. Changed > to !=

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 17.4 KB
Line 
1#!/usr/bin/perl -w
2
3###########################################################################
4#
5# gsConvert.pl -- convert documents to HTML or TEXT format
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 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
29# gsConvert.pl converts documents in a range of formats to HTML or TEXT
30# by exploiting third-party programs. These are usually found in the
31# $GSDLHOME/packages directory.
32#
33# Currently, we can convert Microsoft Word and Adobe PDF using specialised
34# conversion utilities. We can convery any file to text with a perl
35# implementation of the UNIX strings command.
36#
37# We try to convert Postscript files to text using "gs" which is often on
38# *nix machines. If it isn't (or we're running on Windoze), we do some feeble
39# text extraction on it using regexps.
40
41BEGIN {
42 die "GSDLHOME not set\n" unless defined $ENV{'GSDLHOME'};
43 unshift (@INC, "$ENV{'GSDLHOME'}/perllib");
44}
45
46use parsargv;
47use util;
48use Cwd;
49use File::Basename;
50
51
52sub print_usage
53{
54 print STDERR "\n";
55 print STDERR "gsConvert.pl: Converts documents in a range of formats to html\n";
56 print STDERR " or text using third-party programs.\n\n";
57 print STDERR " usage: $0 [options] filename\n";
58 print STDERR " options:\n\t-type\tdoc|pdf|ps\n\t-output\thtml|text\n";
59 print STDERR "\t-timeout\t<max cpu seconds>\n";
60 exit(1);
61}
62
63
64sub main
65{
66 my (@ARGV) = @_;
67 my ($input_type,$output_type,$verbose,$timeout);
68
69 $timeout = 0;
70 # read command-line arguments
71 if (!parsargv::parse(\@ARGV,
72 'type/(doc|pdf|ps)/', \$input_type,
73 'output/(html|text)/', \$output_type,
74 'timeout/\d+/0',\$timeout,
75 'verbose/\d+/0', \$verbose))
76 {
77 print_usage();
78 }
79
80 # Make sure the input file exists and can be opened for reading
81 if (scalar(@ARGV!=1)) {
82 print_usage();
83 }
84
85 my $input_filename = $ARGV[0];
86 if (!-r $input_filename) {
87 print STDERR "Error: unable to open $input_filename for reading\n";
88 exit(1);
89 }
90
91 # Deduce filenames
92 my ($tailname,$dirname,$suffix)
93 = File::Basename::fileparse($input_filename,'\..+');
94 my $output_filestem = &util::filename_cat($dirname,"$tailname");
95
96 if ($input_type eq "")
97 {
98 $input_type = substr($suffix,1,length($suffix)-1);
99 }
100
101 # Change to temporary working directory
102 my $stored_dir = cwd();
103 chdir ($dirname) || die "Unable to change to directory $dirname";
104
105 # Select convert utility
106 if (!defined $input_type) {
107 print STDERR "Error: No filename extension or input type defined\n";
108 exit(1);
109 }
110 elsif ($input_type eq "doc") {
111 print &convertDOC($input_filename, $output_filestem, $output_type);
112 print "\n";
113 }
114 elsif ($input_type eq "rtf") {
115 print &convertRTF($input_filename, $output_filestem, $output_type);
116 print "\n";
117 }
118 elsif ($input_type eq "pdf") {
119 print &convertPDF($dirname, $input_filename, $output_filestem, $output_type);
120 print "\n";
121 }
122 elsif ($input_type eq "ps") {
123 print &convertPS($input_filename, $output_filestem, $output_type);
124 print "\n";
125 }
126 else {
127 print STDERR "Error: Unable to convert type '$input_type'\n";
128 exit(1);
129 }
130
131 # restore to original working directory
132 chdir ($stored_dir) || die "Unable to return to directory $stored_dir";
133
134}
135
136&main(@ARGV);
137
138
139
140# Document-type conversion fucntions
141#
142# The following functions attempt to convert documents from their
143# input type to the specified output type. If no output type was
144# given, then they first attempt HTML, and then TEXT.
145#
146# Each returns the output type ("html" or "text") or "fail" if no
147# conversion is possible.
148
149# Convert a Microsoft word document
150
151sub convertDOC {
152 ($input_filename, $output_filestem, $output_type) = @_;
153
154 # Many .doc files are not in fact word documents!
155 my $realtype = &find_docfile_type($input_filename);
156
157 if ($realtype eq "word6" || $realtype eq "word7" || $realtype eq "word8") {
158 return &convertWord678($input_filename, $output_filestem, $output_type);
159 } elsif ($realtype eq "rtf") {
160 return &convertRTF($input_filename, $output_filestem, $output_type);
161 } else {
162 return &convertAnything($input_filename, $output_filestem, $output_type);
163 }
164}
165
166# Convert a Microsoft word 6/7/8 document
167
168sub convertWord678 {
169 ($input_filename, $output_filestem, $output_type) = @_;
170
171 my $success = 0;
172
173 # Attempt specialised conversion to HTML
174 if (!$output_type || ($output_type =~ /html/i)) {
175 $success = &doc_to_html($input_filename, $output_filestem);
176 if ($success) {
177 return "html";
178 }
179 }
180
181 return &convertAnything($input_filename, $output_filestem, $output_type);
182}
183
184
185# Convert a Rich Text Format (RTF) file
186
187sub convertRTF {
188 ($input_filename, $output_filestem, $output_type) = @_;
189
190 my $success = 0;
191
192 # Attempt specialised conversion to HTML
193 if (!$output_type || ($output_type =~ /html/i)) {
194 $success = &rtf_to_html($input_filename, $output_filestem);
195 if ($success) {
196 return "html";
197 }
198 }
199
200 return &convertAnything($input_filename, $output_filestem, $output_type);
201}
202
203
204# Convert an unidentified file
205
206sub convertAnything {
207 ($input_filename, $output_filestem, $output_type) = @_;
208
209 my $success = 0;
210
211 # Attempt simple conversion to HTML
212 if (!$output_type || ($output_type =~ /html/i)) {
213 $success = &any_to_html($input_filename, $output_filestem);
214 if ($success) {
215 return "html";
216 }
217 }
218
219 # Convert to text
220 if (!$output_type || ($output_type =~ /text/i)) {
221 $success = any_to_text($input_filename, $output_filestem);
222 if ($success) {
223 return "text";
224 }
225 }
226 return "fail";
227}
228
229
230
231# Convert an Adobe PDF document
232
233sub convertPDF {
234 ($dirname, $input_filename, $output_filestem, $output_type) = @_;
235
236 my $success = 0;
237
238 # Attempt conversion to HTML
239 if (!$output_type || ($output_type =~ /html/i)) {
240 $success = &pdf_to_html($dirname, $input_filename, $output_filestem);
241 if ($success) {
242 return "html";
243 }
244 }
245
246 # Attempt conversion to TEXT
247 if (!$output_type || ($output_type =~ /text/i)) {
248 $success = &pdf_to_text($input_filename, $output_filestem);
249 if ($success) {
250 return "text";
251 }
252 }
253
254 return "fail";
255
256}
257
258
259# Convert an Adobe PostScript document
260
261sub convertPS {
262 ($input_filename, $output_filestem, $output_type) = @_;
263
264 my $success = 0;
265
266 # Attempt conversion to TEXT
267 if (!$output_type || ($output_type =~ /text/i)) {
268 $success = &ps_to_text($input_filename, $output_filestem);
269 if ($success) {
270 return "text";
271 }
272 }
273
274 return "fail";
275
276}
277
278
279# Find the real type of a .doc file
280#
281# We seem to have a lot of files with a .doc extension that are .rtf
282# files or Word 5 files. This function attempts to tell the difference.
283
284sub find_docfile_type {
285 ($input_filename) = @_;
286
287 open(CHK, "<$input_filename");
288 binmode(CHK);
289 my $line = "";
290 my $first = 1;
291
292 while (<CHK>) {
293
294 $line = $_;
295
296 if ($first) {
297 # check to see if this is an rtf file
298 if ($line =~ /^\{\\rtf/) {
299 close(CHK);
300 return "rtf";
301 }
302 }
303
304 # is this is a word 6/7/8 document?
305 if ($line =~ /Word\.Document\.([678])/) {
306 close(CHK);
307 return "word$1";
308 }
309
310 $first = 0;
311
312 }
313
314 return "unknown";
315}
316
317
318
319# Specific type-to-type conversions
320#
321# Each of the following functions attempts to convert a document from
322# a specific format to another. If they succeed yhey return 1 and leave
323# the output document(s) in the appropriate place; if they fail they
324# return 0 and delete any working files.
325
326
327# Attempt to convert a word document to html with the wv program
328
329sub doc_to_html {
330 ($input_filename, $output_filestem) = @_;
331
332 my $wvWare = &util::filename_cat($ENV{'GSDLHOME'}, "bin",
333 $ENV{'GSDLOS'}, "wvWare");
334 $wvWare .= ".exe" if ($ENV{'GSDLOS'} =~ /^windows$/i);
335 return 0 unless (-e "$wvWare");
336
337 my $wv_conf = &util::filename_cat($ENV{'GSDLHOME'}, "packages",
338 "wv", "wvHtml.xml");
339
340 $cmd = "";
341 if ($timeout) {$cmd = "ulimit -t $timeout;";}
342 $cmd .= "$wvWare --charset utf-8 --config $wv_conf";
343 $cmd .= " \"$input_filename\" > \"$output_filestem.html\" 2>\"$output_filestem.err\"";
344
345 # execute the command
346 if (system($cmd)!=0)
347 {
348 print STDERR "Error executing wv converter: $!. Continuing...\n";
349 }
350
351 # Was the conversion successful?
352 if (-e "$output_filestem.html") {
353 open(TMP, "$output_filestem.html");
354 $line = <TMP>;
355 close(TMP);
356 if ($line && $line =~ /DOCTYPE HTML/) {
357 &util::rm("$output_filestem.err");
358 return 1;
359 } else {
360 # An error of some sort occurred
361 &util::rm("$output_filestem.html");
362 &util::rm("$output_filestem.err");
363 }
364 }
365
366 return 0;
367}
368
369
370# Attempt to convert an RTF document to html with rtftohtml
371#
372# rtf2html isn't distributed with Greenstone because it is not
373# distributed under teh GPL. If you know of a better solution,
374# please let me know.
375
376sub rtf_to_html {
377 ($input_filename, $output_filestem) = @_;
378
379 # formulate the command
380 my $r_cmd = &util::filename_cat($ENV{'GSDLHOME'}, "packages", "unix",
381 "rtf2html", "rtf2html", "rtf2html");
382 $r_cmd = "rtf2html" unless (-e "$r_cmd");
383 return 0 unless (-e "$r_cmd");
384 $cmd = "";
385 if ($timeout) {$cmd = "ulimit -t $timeout;";}
386 $cmd .= "$r_cmd";
387 $cmd .= " \"$input_filename\" > \"$output_filestem.html\" 2>\"$output_filestem.err\"";
388
389 # execute the command
390 if (system($cmd)!=0)
391 {
392 print STDERR "Error executing rtf converter: $!. Continuing...\n";
393 }
394
395 # Was the conversion successful?
396 if (-e "$output_filestem.html") {
397 open(TMP, "$output_filestem.html");
398 $line = <TMP>;
399 close(TMP);
400 if ($line && $line =~ /DOCTYPE HTML/) {
401 &util::rm("$output_filestem.err");
402 return 1;
403 } else {
404 # An error of some sort occurred
405 &util::rm("$output_filestem.html");
406 &util::rm("$output_filestem.err");
407 }
408 }
409 return 0;
410}
411
412
413# Convert a pdf file to html with the pdftohtml command
414
415sub pdf_to_html {
416 ($dirname, $input_filename, $output_filestem) = @_;
417
418 $cmd = "";
419 if ($timeout) {$cmd = "ulimit -t $timeout;";}
420 $cmd .= "pdftohtml.pl -F ";
421 $cmd .= " \"$input_filename\" \"$output_filestem\"";
422
423 if (system($cmd)!=0)
424 {
425 print STDERR "Error executing $cmd: $!\n";
426 return 0;
427 }
428
429 # make sure the converter made something
430 if (! -e "$output_filestem.html")
431 {
432 &util::rm("$output_filestem.out") if (-e "$output_filestem.out");
433 # print out the converters std err, if any
434 if (-e "$output_filestem.err") {
435 open (ERRLOG, "$output_filestem.err") || die "$!";
436 print STDERR "pdftohtml:\n";
437 while (<ERRLOG>) {
438 print STDERR "$_";
439 }
440 close ERRLOG;
441 }
442 return 0;
443 }
444
445 &util::rm("$output_filestem.out") if (-e "$output_filestem.out");
446 return 1;
447}
448
449# Convert a PDF file to text with the pdftotext command
450
451sub pdf_to_text {
452 ($dirname, $input_filename, $output_filestem) = @_;
453
454 $cmd = "pdftotext \"$input_filename\" > \"$output_filestem.text\"";
455 $cmd .= " 2> $output_filestem.err";
456
457 if (system($cmd)!=0)
458 {
459 print STDERR "Error executing $cmd: $!\n";
460 &util::rm("$output_filestem.text") if (-e "$output_filestem.text");
461 &util::rm("$output_filestem.err") if (-e "$output_filestem.err");
462 return 0;
463 }
464
465 # make sure the converter made something
466 if (! -e "$output_filestem.html")
467 {
468 &util::rm("$output_filestem.out") if (-e "$output_filestem.out");
469 # print out the converters std err, if any
470 if (-e "$output_filestem.err") {
471 open (ERRLOG, "$output_filestem.err") || die "$!";
472 print STDERR "pdftotext:\n";
473 while (<ERRLOG>) {
474 print STDERR "$_";
475 }
476 close ERRLOG;
477 }
478 return 0;
479 }
480
481 &util::rm("$output_filestem.err") if (-e "$output_filestem.err");
482 return 1;
483}
484
485# Convert a PostScript document to text
486# note - just using "ps2ascii" isn't good enough, as it
487# returns 0 for a postscript interpreter error. ps2ascii is just
488# a wrapper to "gs" anyway, so we use that cmd here.
489
490sub ps_to_text {
491 ($input_filename, $output_filestem) = @_;
492
493 my $cmd = "gs -q -dNODISPLAY -dNOBIND -dWRITESYSTEMDICT -dSIMPLE -c save ";
494 $cmd .= "-f ps2ascii.ps \"$input_filename\" -c quit > \"$output_filestem.text\"";
495 $cmd .= " 2> $output_filestem.err";
496 $!=0;
497 my $retcode=system($cmd);
498 $retcode = $? >> 8; # see man perlfunc - system for this...
499 # if system returns -1 | 127 (couldn't start program), look at $! for message
500 my $error="";
501 if ($retcode!=0) {if ($!) {$error=$!;} else {$error="couldn't run.\n";}}
502 elsif (! -e "$output_filestem.text") {
503 $error="did not create output file.\n";
504 }
505 else
506 { # make sure the interpreter didn't get an error. It is technically
507 # possible for the actual text to start with this, but....
508 open PSOUT, "$output_filestem.text";
509 if (<PSOUT> =~ /^Error: (.*)/) {
510 $error="interpreter error - \"$1\"";
511 }
512 close PSOUT;
513 }
514 if ($error ne "")
515 {
516 print STDERR "PSPLUG: WARNING: Error executing gs: $error\n";
517 &util::rm("$output_filestem.text") if (-e "$output_filestem.text");
518 &util::rm("$output_filestem.err") if (-e "$output_filestem.err");
519
520 # Fine then. We'll just do a lousy job by ourselves...
521 # Based on 5-line regexp sed script found at:
522 # http://snark.ptc.spbu.ru/mail-archives/lout/brown/msg00003.html
523 #
524 print STDERR "PSPlug: Stripping text from postscript\n";
525 my $errorcode=0;
526 open (IN, "$input_filename")
527 || ($errorcode=1, warn "Couldn't read file: $!");
528 open (OUT, ">$output_filestem.text")
529 || ($errorcode=1, warn "Couldn't write file: $!");
530 if ($errorcode) {print STDERR "errors\n";return 0;}
531
532 my $text=""; # this is for whole .ps file...
533 while (<IN>) {
534 $text.=$_;
535 }
536 close IN;
537
538 # if ps has Page data, then use it to delete all stuff before it.
539 $text =~ s/^.*?%%Page:.*?\n//s; # treat string as single line
540
541 # remove all leading non-data stuff
542 $text =~ s/^.*?\(//s;
543
544 # remove all newline chars for easier processing
545 $text =~ s/\n//g;
546
547 # Big assumption here - assume that if any co-ordinates are
548 # given, then we are at the end of a sentence.
549 $text =~ s/\)-?\d+\ -?\d+/\) \(\n\)/g;
550
551 # special characters--
552 $text =~ s/\(\|\)/\(\ - \)/g; # j -> em-dash?
553
554 # ? ps text formatting (eg italics?) ?
555 $text =~ s/Fn\(f\)/\(\{\)/g; # f -> {
556 $text =~ s/Fn\(g\)/\(\}\)/g; # g -> }
557 $text =~ s/Fn\(j\)/\(\|\)/g; # j -> |
558 # default - remove the rest
559 $text =~ s/\ ?F.\((.+?)\)/\($1\)/g;
560
561 # attempt to add whitespace between words...
562 # this is based purely on observation, and may be completely wrong...
563 $text =~ s/([^F])[defghijkuy]\(/$1 \( /g;
564 # eg I notice "b(" is sometimes NOT a space if preceded by a
565 # negative number.
566 $text =~ s/\)\d+ ?b\(/\) \( /g;
567
568 # change quoted braces to brackets
569 $text =~ s/([^\\])\\\(/$1\{/g;
570 $text =~ s/([^\\])\\\)/$1\}/g ;
571
572 # remove everything that is not between braces
573 $text =~ s/\)([^\(\)])+?\(//sg ;
574
575 # remove any Trailer eof stuff.
576 $text =~ s/\)[^\)]*$//sg;
577
578 ### ligatures have special characters...
579 $text =~ s/\\013/ff/g;
580 $text =~ s/\\014/fi/g;
581 $text =~ s/\\015/fl/g;
582 $text =~ s/\\016/ffi/g;
583 $text =~ s/\\214/fi/g;
584 $text =~ s/\\215/fl/g;
585 $text =~ s/\\017/\n\* /g; # asterisk?
586 $text =~ s/\\023/\023/g; # e acute ('e)
587 $text =~ s/\\177/\252/g; # u"
588# $text =~ s/ ?? /\344/g; # a"
589
590 print OUT "$text";
591 close OUT;
592 }
593 &util::rm("$output_filestem.err") if (-e "$output_filestem.err");
594 return 1;
595}
596
597
598# Convert any file to HTML with a crude perl implementation of the
599# UNIX strings command.
600
601sub any_to_html {
602 ($input_filename, $output_filestem) = @_;
603
604 # First generate a text file
605 return 0 unless (&any_to_text($input_filename, $output_filestem));
606
607 # create an HTML file from the text file
608 open(TEXT, "<$output_filestem.text");
609 open(HTML, ">$output_filestem.html");
610
611 print HTML '<html><head>
612<META HTTP-EQUIV="Content-Type" CONTENT="text/html">
613<META NAME="GENERATOR" CONTENT="Greenstone any_to_html">
614</head><body>';
615 print HTML "\n\n";
616
617 while (<TEXT>) {
618 print HTML "<p> ", $_;
619
620 }
621 print HTML "\n</body></html>\n";
622
623 &util::rm("$output_filestem.text") if (-e "$output_filestem.text");
624 return 1;
625}
626
627# Convert any file to TEXT with a crude perl implementation of the
628# UNIX strings command.
629
630sub any_to_text {
631 ($input_filename, $output_filestem) = @_;
632
633 open(IN, "<$input_filename");
634 binmode(IN);
635 open(OUT, ">$output_filestem.text");
636
637 my ($line);
638 my $dgcount = 0;
639 while (<IN>) {
640 $line = $_;
641
642 # delete anything that isn't a printable character
643 $line =~ s/[^\040-\176]+/\n/sg;
644
645 # delete any string less than 10 characters long
646 $line =~ s/^.{0,9}$/\n/mg;
647 while ($line =~ /^.{1,9}$/m) {
648 $line =~ s/^.{0,9}$/\n/mg;
649 $line =~ s/\n+/\n/sg;
650 }
651
652 # remove extraneous whitespace
653 $line =~ s/\n+/\n/gs;
654 $line =~ s/^\n//gs;
655
656 # output whatever is left
657 if ($line =~ /[^\n ]/) {
658 print OUT $line;
659 }
660 }
661 return 1;
662}
Note: See TracBrowser for help on using the repository browser.