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

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

Tidied up a bit, error in args passed to pdf_to_text, etc.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 17.5 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($dirname, $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 $!=0;
423 if (system($cmd)!=0)
424 {
425 print STDERR "Error executing $cmd";
426 if ($!) {print STDERR ": $!";}
427 print STDERR "\n";
428 return 0;
429 }
430
431 # make sure the converter made something
432 if (! -e "$output_filestem.html")
433 {
434 &util::rm("$output_filestem.out") if (-e "$output_filestem.out");
435 # print out the converters std err, if any
436 if (-e "$output_filestem.err") {
437 open (ERRLOG, "$output_filestem.err") || die "$!";
438 print STDERR "pdftohtml:\n";
439 while (<ERRLOG>) {
440 print STDERR "$_";
441 }
442 close ERRLOG;
443 }
444 return 0;
445 }
446
447 &util::rm("$output_filestem.out") if (-e "$output_filestem.out");
448 return 1;
449}
450
451# Convert a PDF file to text with the pdftotext command
452
453sub pdf_to_text {
454 ($dirname, $input_filename, $output_filestem) = @_;
455
456 my $cmd = "pdftotext \"$input_filename\" > \"$output_filestem.text\"";
457 $cmd .= " 2> \"$output_filestem.err\"";
458
459 if (system($cmd)!=0)
460 {
461 print STDERR "Error executing $cmd: $!\n";
462 &util::rm("$output_filestem.text") if (-e "$output_filestem.text");
463 &util::rm("$output_filestem.err") if (-e "$output_filestem.err");
464 return 0;
465 }
466
467 # make sure the converter made something
468 if (! -e "$output_filestem.html")
469 {
470 &util::rm("$output_filestem.out") if (-e "$output_filestem.out");
471 # print out the converters std err, if any
472 if (-e "$output_filestem.err") {
473 open (ERRLOG, "$output_filestem.err") || die "$!";
474 print STDERR "pdftotext:\n";
475 while (<ERRLOG>) {
476 print STDERR "$_";
477 }
478 close ERRLOG;
479 }
480 return 0;
481 }
482
483 &util::rm("$output_filestem.err") if (-e "$output_filestem.err");
484 return 1;
485}
486
487# Convert a PostScript document to text
488# note - just using "ps2ascii" isn't good enough, as it
489# returns 0 for a postscript interpreter error. ps2ascii is just
490# a wrapper to "gs" anyway, so we use that cmd here.
491
492sub ps_to_text {
493 ($input_filename, $output_filestem) = @_;
494
495 my $cmd = "gs -q -dNODISPLAY -dNOBIND -dWRITESYSTEMDICT -dSIMPLE -c save ";
496 $cmd .= "-f ps2ascii.ps \"$input_filename\" -c quit > \"$output_filestem.text\"";
497 $cmd .= " 2> $output_filestem.err";
498 $!=0;
499 my $retcode=system($cmd);
500 $retcode = $? >> 8; # see man perlfunc - system for this...
501 # if system returns -1 | 127 (couldn't start program), look at $! for message
502 my $error="";
503 if ($retcode!=0) {if ($!) {$error=$!;} else {$error="couldn't run.\n";}}
504 elsif (! -e "$output_filestem.text") {
505 $error="did not create output file.\n";
506 }
507 else
508 { # make sure the interpreter didn't get an error. It is technically
509 # possible for the actual text to start with this, but....
510 open PSOUT, "$output_filestem.text";
511 if (<PSOUT> =~ /^Error: (.*)/) {
512 $error="interpreter error - \"$1\"";
513 }
514 close PSOUT;
515 }
516 if ($error ne "")
517 {
518 print STDERR "PSPLUG: WARNING: Error executing gs: $error\n";
519 &util::rm("$output_filestem.text") if (-e "$output_filestem.text");
520 &util::rm("$output_filestem.err") if (-e "$output_filestem.err");
521
522 # Fine then. We'll just do a lousy job by ourselves...
523 # Based on 5-line regexp sed script found at:
524 # http://snark.ptc.spbu.ru/mail-archives/lout/brown/msg00003.html
525 #
526 print STDERR "PSPlug: Stripping text from postscript\n";
527 my $errorcode=0;
528 open (IN, "$input_filename")
529 || ($errorcode=1, warn "Couldn't read file: $!");
530 open (OUT, ">$output_filestem.text")
531 || ($errorcode=1, warn "Couldn't write file: $!");
532 if ($errorcode) {print STDERR "errors\n";return 0;}
533
534 my $text=""; # this is for whole .ps file...
535 while (<IN>) {
536 $text.=$_;
537 }
538 close IN;
539
540 # if ps has Page data, then use it to delete all stuff before it.
541 $text =~ s/^.*?%%Page:.*?\n//s; # treat string as single line
542
543 # remove all leading non-data stuff
544 $text =~ s/^.*?\(//s;
545
546 # remove all newline chars for easier processing
547 $text =~ s/\n//g;
548
549 # Big assumption here - assume that if any co-ordinates are
550 # given, then we are at the end of a sentence.
551 $text =~ s/\)-?\d+\ -?\d+/\) \(\n\)/g;
552
553 # special characters--
554 $text =~ s/\(\|\)/\(\ - \)/g; # j -> em-dash?
555
556 # ? ps text formatting (eg italics?) ?
557 $text =~ s/Fn\(f\)/\(\{\)/g; # f -> {
558 $text =~ s/Fn\(g\)/\(\}\)/g; # g -> }
559 $text =~ s/Fn\(j\)/\(\|\)/g; # j -> |
560 # default - remove the rest
561 $text =~ s/\ ?F.\((.+?)\)/\($1\)/g;
562
563 # attempt to add whitespace between words...
564 # this is based purely on observation, and may be completely wrong...
565 $text =~ s/([^F])[defghijkuy]\(/$1 \( /g;
566 # eg I notice "b(" is sometimes NOT a space if preceded by a
567 # negative number.
568 $text =~ s/\)\d+ ?b\(/\) \( /g;
569
570 # change quoted braces to brackets
571 $text =~ s/([^\\])\\\(/$1\{/g;
572 $text =~ s/([^\\])\\\)/$1\}/g ;
573
574 # remove everything that is not between braces
575 $text =~ s/\)([^\(\)])+?\(//sg ;
576
577 # remove any Trailer eof stuff.
578 $text =~ s/\)[^\)]*$//sg;
579
580 ### ligatures have special characters...
581 $text =~ s/\\013/ff/g;
582 $text =~ s/\\014/fi/g;
583 $text =~ s/\\015/fl/g;
584 $text =~ s/\\016/ffi/g;
585 $text =~ s/\\214/fi/g;
586 $text =~ s/\\215/fl/g;
587 $text =~ s/\\017/\n\* /g; # asterisk?
588 $text =~ s/\\023/\023/g; # e acute ('e)
589 $text =~ s/\\177/\252/g; # u"
590# $text =~ s/ ?? /\344/g; # a"
591
592 print OUT "$text";
593 close OUT;
594 }
595 &util::rm("$output_filestem.err") if (-e "$output_filestem.err");
596 return 1;
597}
598
599
600# Convert any file to HTML with a crude perl implementation of the
601# UNIX strings command.
602
603sub any_to_html {
604 ($input_filename, $output_filestem) = @_;
605
606 # First generate a text file
607 return 0 unless (&any_to_text($input_filename, $output_filestem));
608
609 # create an HTML file from the text file
610 open(TEXT, "<$output_filestem.text");
611 open(HTML, ">$output_filestem.html");
612
613 print HTML '<html><head>
614<META HTTP-EQUIV="Content-Type" CONTENT="text/html">
615<META NAME="GENERATOR" CONTENT="Greenstone any_to_html">
616</head><body>';
617 print HTML "\n\n";
618
619 while (<TEXT>) {
620 print HTML "<p> ", $_;
621
622 }
623 print HTML "\n</body></html>\n";
624
625 &util::rm("$output_filestem.text") if (-e "$output_filestem.text");
626 return 1;
627}
628
629# Convert any file to TEXT with a crude perl implementation of the
630# UNIX strings command.
631
632sub any_to_text {
633 ($input_filename, $output_filestem) = @_;
634
635 open(IN, "<$input_filename");
636 binmode(IN);
637 open(OUT, ">$output_filestem.text");
638
639 my ($line);
640 my $dgcount = 0;
641 while (<IN>) {
642 $line = $_;
643
644 # delete anything that isn't a printable character
645 $line =~ s/[^\040-\176]+/\n/sg;
646
647 # delete any string less than 10 characters long
648 $line =~ s/^.{0,9}$/\n/mg;
649 while ($line =~ /^.{1,9}$/m) {
650 $line =~ s/^.{0,9}$/\n/mg;
651 $line =~ s/\n+/\n/sg;
652 }
653
654 # remove extraneous whitespace
655 $line =~ s/\n+/\n/gs;
656 $line =~ s/^\n//gs;
657
658 # output whatever is left
659 if ($line =~ /[^\n ]/) {
660 print OUT $line;
661 }
662 }
663 return 1;
664}
Note: See TracBrowser for help on using the repository browser.