source: gs2-extensions/parallel-building/trunk/src/perllib/plugins/ReadTextFile.pm@ 27377

Last change on this file since 27377 was 27377, checked in by jmt12, 11 years ago

Updating calls to intermediate util functions to the new FileUtils functions

  • Property svn:executable set to *
File size: 20.1 KB
Line 
1###########################################################################
2#
3# ReadTxtFile.pm -- base class for import plugins that have plain text files
4# A component of the Greenstone digital library software
5# from the New Zealand Digital Library Project at the
6# University of Waikato, New Zealand.
7#
8# Copyright (C) 1999-2005 New Zealand Digital Library Project
9#
10# This program is free software; you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23#
24###########################################################################
25
26package ReadTextFile;
27
28use strict;
29no strict 'subs';
30no strict 'refs'; # allow filehandles to be variables and viceversa
31
32use Encode;
33
34use multiread;
35use encodings;
36use unicode;
37use textcat;
38use doc;
39use ghtml;
40use gsprintf 'gsprintf';
41use util;
42use FileUtils;
43
44use AutoExtractMetadata;
45
46sub BEGIN {
47 @ReadTextFile::ISA = ( 'AutoExtractMetadata' );
48}
49
50my $encoding_plus_auto_list =
51 [ { 'name' => "auto",
52 'desc' => "{ReadTextFile.input_encoding.auto}" } ];
53push(@{$encoding_plus_auto_list},@{$BasePlugin::encoding_list});
54
55my $arguments =
56 [ { 'name' => "input_encoding",
57 'desc' => "{ReadTextFile.input_encoding}",
58 'type' => "enum",
59 'list' => $encoding_plus_auto_list,
60 'reqd' => "no" ,
61 'deft' => "auto" } ,
62 { 'name' => "default_encoding",
63 'desc' => "{ReadTextFile.default_encoding}",
64 'type' => "enum",
65 'list' => $BasePlugin::encoding_list,
66 'reqd' => "no",
67 'deft' => "utf8" },
68 { 'name' => "extract_language",
69 'desc' => "{ReadTextFile.extract_language}",
70 'type' => "flag",
71 'reqd' => "no" },
72 { 'name' => "default_language",
73 'desc' => "{ReadTextFile.default_language}",
74 'type' => "string",
75 'deft' => "en",
76 'reqd' => "no" }
77 ];
78
79
80my $options = { 'name' => "ReadTextFile",
81 'desc' => "{ReadTextFile.desc}",
82 'abstract' => "yes",
83 'inherits' => "no",
84 'args' => $arguments };
85
86
87
88sub new {
89 my $class = shift (@_);
90 my ($pluginlist,$inputargs,$hashArgOptLists, $auxiliary) = @_;
91 push(@$pluginlist, $class);
92
93 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
94 push(@{$hashArgOptLists->{"OptList"}},$options);
95
96 my $self = new AutoExtractMetadata($pluginlist, $inputargs, $hashArgOptLists, $auxiliary);
97
98 return bless $self, $class;
99
100}
101
102
103
104# The ReadTextFile read_into_doc_obj() function. This function does all the
105# right things to make general options work for a given plugin. It reads in
106# a file and sets up a slew of metadata all saved in doc_obj, which
107# it then returns as part of a tuple (process_status,doc_obj)
108#
109# Much of this functionality used to reside in read, but it was broken
110# down into a supporting routine to make the code more flexible.
111#
112# recursive plugins (e.g. RecPlug) and specialized plugins like those
113# capable of processing many documents within a single file (e.g.
114# GMLPlug) will normally want to implement their own version of
115# read_into_doc_obj()
116#
117# Note that $base_dir might be "" and that $file might
118# include directories
119sub read_into_doc_obj {
120 my $self = shift (@_);
121 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
122
123 my $outhandle = $self->{'outhandle'};
124 # should we move this to read? What about secondary plugins?
125 print STDERR "<Processing n='$file' p='$self->{'plugin_type'}'>\n" if ($gli);
126 my $pp_file = &util::prettyprint_file($base_dir,$file,$gli);
127 print $outhandle "$self->{'plugin_type'} processing $pp_file\n"
128 if $self->{'verbosity'} > 1;
129
130 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
131
132 # Do encoding stuff
133 my ($language, $content_encoding) = $self->textcat_get_language_encoding ($filename_full_path);
134 if ($self->{'verbosity'} > 2) {
135 print $outhandle "ReadTextFile: reading $file as ($content_encoding,$language)\n";
136 }
137
138 # create a new document
139 my $doc_obj = new doc ($filename_full_path, "indexed_doc", $self->{'file_rename_method'});
140 my $top_section = $doc_obj->get_top_section();
141
142 # this should look at the plugin option too...
143 $doc_obj->add_utf8_metadata($top_section, "Plugin", "$self->{'plugin_type'}");
144 $doc_obj->add_utf8_metadata($top_section, "FileSize", &FileUtils::fileSize($filename_full_path));
145
146 my $plugin_filename_encoding = $self->{'filename_encoding'};
147 my $filename_encoding = $self->deduce_filename_encoding($file,$metadata,$plugin_filename_encoding);
148 $self->set_Source_metadata($doc_obj, $filename_full_path, $filename_encoding);
149
150 $doc_obj->add_utf8_metadata($top_section, "Language", $language);
151 $doc_obj->add_utf8_metadata($top_section, "Encoding", $content_encoding);
152
153 # read in file ($text will be in utf8)
154 my $text = "";
155 $self->read_file ($filename_full_path, $content_encoding, $language, \$text);
156
157 if (!length ($text)) {
158 if ($gli) {
159 print STDERR "<ProcessingError n='$file' r='File contains no text'>\n";
160 }
161 gsprintf($outhandle, "$self->{'plugin_type'}: {ReadTextFile.file_has_no_text}\n", $filename_full_path) if $self->{'verbosity'};
162
163 my $failhandle = $self->{'failhandle'};
164 gsprintf($failhandle, "$file: " . ref($self) . ": {ReadTextFile.empty_file}\n");
165 # print $failhandle "$file: " . ref($self) . ": file contains no text\n";
166 $self->{'num_not_processed'} ++;
167
168 return (0,undef); # what should we return here?? error but don't want to pass it on
169 }
170
171 # do plugin specific processing of doc_obj
172 unless (defined ($self->process (\$text, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
173 $text = '';
174 undef $text;
175 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
176 return (-1,undef);
177 }
178 $text='';
179 undef $text;
180
181 # include any metadata passed in from previous plugins
182 # note that this metadata is associated with the top level section
183 $self->add_associated_files($doc_obj, $filename_full_path);
184 $self->extra_metadata ($doc_obj, $top_section, $metadata);
185
186 # do any automatic metadata extraction
187 $self->auto_extract_metadata ($doc_obj);
188
189
190 # if we haven't found any Title so far, assign one
191 $self->title_fallback($doc_obj,$top_section,$filename_no_path);
192
193 $self->add_OID($doc_obj);
194
195 return (1,$doc_obj);
196}
197
198# uses the multiread package to read in the entire file pointed to
199# by filename and loads the resulting text into $$textref. Input text
200# may be in any of the encodings handled by multiread, output text
201# will be in utf8
202sub read_file {
203 my $self = shift (@_);
204 my ($filename, $encoding, $language, $textref) = @_;
205
206 if (!&FileUtils::canRead($filename))
207 {
208 my $outhandle = $self->{'outhandle'};
209 gsprintf($outhandle, "{ReadTextFile.read_denied}\n", $filename) if $self->{'verbosity'};
210 # print $outhandle "Read permission denied for $filename\n" if $self->{'verbosity'};
211 return;
212 }
213
214 $$textref = "";
215 # use the util::file_* functions to provide some extra smarts to the open
216 # command in order to support protocols like http: or hdfs:
217 my $fh;
218 if (!&FileUtils::openFileHandle($filename, '<', \$fh))
219 {
220 gsprintf(STDERR, "ReadTextFile::read_file {ReadTextFile.could_not_open_for_reading} ($!)\n", $filename);
221 die "\n";
222 }
223
224 if ($encoding eq "ascii")
225 {
226 # fast file 'slurp' implementation
227 sysread($fh, $$textref, &FileUtils::fileSize($filename));
228 # the old slow way of reading in a file
229 #undef $/;
230 #$$textref = <FILE>;
231 #$/ = "\n";
232 }
233 else
234 {
235 my $reader = new multiread();
236 $reader->set_handle ($fh);
237 $reader->set_encoding ($encoding);
238 $reader->read_file ($textref);
239 }
240
241 # At this point $$textref is a binary byte string
242 # => turn it into a Unicode aware string, so full
243 # Unicode aware pattern matching can be used.
244 # For instance: 's/\x{0101}//g' or '[[:upper:]]'
245 #
246 $$textref = decode("utf8", $$textref);
247
248 &FileUtils::closeFileHandle($filename, \$fh);
249}
250
251
252# Not currently used
253sub UNUSED_read_file_usingPerlsEncodeModule {
254##sub read_file {
255 my $self = shift (@_);
256 my ($filename, $encoding, $language, $textref) = @_;
257
258 if (!-r $filename)
259 {
260 my $outhandle = $self->{'outhandle'};
261 gsprintf($outhandle, "{ReadTextFile.read_denied}\n", $filename) if $self->{'verbosity'};
262 # print $outhandle "Read permission denied for $filename\n" if $self->{'verbosity'};
263 return;
264 }
265 $$textref = "";
266 if (!open (FILE, $filename)) {
267 gsprintf(STDERR, "ReadTextFile::read_file {ReadTextFile.could_not_open_f
268or_reading} ($!)\n", $filename);
269 die "\n";
270 }
271
272 my $store_slash = $/;
273 undef $/;
274 my $text = <FILE>;
275 $/ = $store_slash;
276
277 $$textref = decode($encoding,$text);
278
279 close FILE;
280}
281
282
283sub read_file_no_decoding {
284 my $self = shift (@_);
285 my ($filename, $textref) = @_;
286
287 if (!-r $filename)
288 {
289 my $outhandle = $self->{'outhandle'};
290 gsprintf($outhandle, "{ReadTextFile.read_denied}\n", $filename) if $self->{'verbosity'};
291 # print $outhandle "Read permission denied for $filename\n" if $self->{'verbosity'};
292 return;
293 }
294 $$textref = "";
295 if (!open (FILE, $filename)) {
296 gsprintf(STDERR, "ReadTextFile::read_file {ReadTextFile.could_not_open_for_reading} ($!)\n", $filename);
297 die "\n";
298 }
299
300 my $reader = new multiread();
301 $reader->set_handle ('ReadTextFile::FILE');
302 $reader->read_file_no_decoding ($textref);
303
304 $self->{'reader'} = $reader;
305
306 close FILE;
307}
308
309
310sub decode_text {
311 my $self = shift (@_);
312 my ($raw_text, $encoding, $language, $textref) = @_;
313
314 my $reader = $self->{'reader'};
315 if (!defined $reader) {
316 gsprintf(STDERR, "ReadTextFile::decode_text needs to call ReadTextFile::read_file_no_decoding first\n");
317 }
318 else {
319 $reader->set_encoding($encoding);
320 $reader->decode_text($raw_text,$textref);
321
322 # At this point $$textref is a binary byte string
323 # => turn it into a Unicode aware string, so full
324 # Unicode aware pattern matching can be used.
325 # For instance: 's/\x{0101}//g' or '[[:upper:]]'
326
327 $$textref = decode("utf8",$$textref);
328 }
329}
330
331
332sub textcat_get_language_encoding {
333 my $self = shift (@_);
334 my ($filename) = @_;
335
336 my ($language, $encoding, $extracted_encoding);
337 if ($self->{'input_encoding'} eq "auto") {
338 # use textcat to automatically work out the input encoding and language
339 ($language, $encoding) = $self->get_language_encoding ($filename);
340 } elsif ($self->{'extract_language'}) {
341 # use textcat to get language metadata
342 ($language, $extracted_encoding) = $self->get_language_encoding ($filename);
343 $encoding = $self->{'input_encoding'};
344 # don't print this message for english... english in utf8 is identical
345 # to english in iso-8859-1 (except for some punctuation). We don't have
346 # a language model for en_utf8, so textcat always says iso-8859-1!
347 if ($extracted_encoding ne $encoding && $language ne "en" && $self->{'verbosity'}) {
348 my $plugin_name = ref ($self);
349 my $outhandle = $self->{'outhandle'};
350 gsprintf($outhandle, "$plugin_name: {ReadTextFile.wrong_encoding}\n", $filename, $encoding, $extracted_encoding);
351 }
352 } else {
353 $language = $self->{'default_language'};
354 $encoding = $self->{'input_encoding'};
355 }
356
357# print STDERR "**** language encoding of contents of file $filename:\n\t****$language $encoding\n";
358
359 return ($language, $encoding);
360}
361
362
363# Uses textcat to work out the encoding and language of the text in
364# $filename. All html tags are removed before processing.
365# returns an array containing "language" and "encoding"
366sub get_language_encoding {
367 my $self = shift (@_);
368 my ($filename) = @_;
369 my $outhandle = $self->{'outhandle'};
370 my $unicode_format = "";
371 my $best_language = "";
372 my $best_encoding = "";
373
374 # read in file
375 my $fh;
376 if (!&FileUtils::openFileHandle($filename, '<', \$fh))
377 {
378 gsprintf(STDERR, "ReadTextFile::get_language_encoding {ReadTextFile.could_not_open_for_reading} ($!)\n", $filename);
379 # this is a pretty bad error, but try to continue anyway
380 return ($self->{'default_language'}, $self->{'input_encoding'});
381 }
382 my $text;
383 sysread($fh, $text, &FileUtils::fileSize($filename));
384 #undef $/;
385 #my $text = <FILE>;
386 #$/ = "\n";
387 close $fh;
388
389 # check if first few bytes have a Byte Order Marker
390 my $bom=substr($text,0,2); # check 16bit unicode
391 if ($bom eq "\xff\xfe") { # little endian 16bit unicode
392 $unicode_format="unicode";
393 } elsif ($bom eq "\xfe\xff") { # big endian 16bit unicode
394 $unicode_format="unicode";
395 } else {
396 $bom=substr($text,0,3); # check utf-8
397 if ($bom eq "\xef\xbb\xbf") { # utf-8 coded FEFF bom
398 $unicode_format="utf8";
399# } elsif ($bom eq "\xef\xbf\xbe") { # utf-8 coded FFFE bom. Error!?
400# $unicode_format="utf8";
401 }
402 }
403
404 my $found_html_encoding = 0;
405 # handle html files specially
406 # XXX this doesn't match plugins derived from HTMLPlug (except ConvertTo)
407 if (ref($self) eq 'HTMLPlugin' ||
408 (exists $self->{'converted_to'} && $self->{'converted_to'} eq 'HTML')){
409
410 # remove comments in head, including multiline ones, so that we don't match on
411 # inactive tags (those that are nested inside comments)
412 my ($head) = ($text =~ m/<head>(.*)<\/head>/si);
413 $head = "" unless defined $head; # some files are not proper HTML eg php files
414 $head =~ s/<!--.*?-->//sg;
415
416 # remove <title>stuff</title> -- as titles tend often to be in English
417 # for foreign language documents
418 $text =~ s!<title>.*?</title>!!si;
419
420 # see if this html file specifies its encoding
421 if ($text =~ /^<\?xml.*encoding="(.+?)"/) {
422 $best_encoding = $1;
423 }
424 # check the meta http-equiv charset tag
425 elsif ($head =~ m/<meta http-equiv.*content-type.*charset=(.+?)\"/si) {
426 $best_encoding = $1;
427 }
428 if ($best_encoding) { # we extracted an encoding
429 $best_encoding =~ s/-+/_/g;
430 $best_encoding = lc($best_encoding); # lowercase
431 if ($best_encoding eq "utf_8") { $best_encoding = "utf8" }
432 $found_html_encoding = 1;
433 # We shouldn't be modifying this here!!
434 #$self->{'input_encoding'} = $best_encoding;
435 }
436
437 # remove all HTML tags
438 $text =~ s/<[^>]*>//sg;
439 }
440
441 # don't need to do textcat if we know the encoding now AND don't need to extract language
442 if($found_html_encoding && !$self->{'extract_language'}) { # encoding specified in html file
443 $best_language = $self->{'default_language'};
444 }
445
446 else { # need to use textcat to get either the language, or get both language and encoding
447 $self->{'textcat'} = new textcat() if (!defined($self->{'textcat'}));
448
449 if($found_html_encoding) { # know encoding, find language by limiting search to known encoding
450 my $results = $self->{'textcat'}->classify_contents_for_encoding(\$text, $filename, $best_encoding);
451
452 my $language;
453 ($language) = $results->[0] =~ m/^([^-]*)(?:-(?:.*))?$/ if (scalar @$results > 0);
454
455 if (!defined $language || scalar @$results > 3) {
456 # if there were too many results even when restricting results by encoding,
457 # or if there were no results, use default language with the known encoding
458 $best_language = $self->use_default_language($filename);
459 }
460 else { # fewer than 3 results means textcat is more certain, use the first result
461 $best_language = $language;
462 }
463 }
464 else { # don't know encoding or language yet, therefore we use textcat
465 my $results = $self->{'textcat'}->classify_contents(\$text, $filename);
466
467 # if textcat returns 3 or less possibilities we'll use the first one in the list
468 if (scalar @$results <= 3) { # results will be > 0 when we don't constrain textcat by an encoding
469 my ($language, $encoding) = $results->[0] =~ m/^([^-]*)(?:-(.*))?$/;
470
471 $language = $self->use_default_language($filename) unless defined $language;
472 $encoding = $self->use_default_encoding($filename) unless defined $encoding;
473
474 $best_language = $language;
475 $best_encoding = $encoding;
476 }
477 else { # if (scalar @$results > 3) {
478 if ($unicode_format) { # in case the first had a BOM
479 $best_encoding=$unicode_format;
480 }
481 else {
482 # Find the most frequent encoding in the textcat results returned
483 # Returns "" if there's no encoding more frequent than another
484 $best_encoding = $self->{'textcat'}->most_frequent_encoding($results);
485 }
486
487 if ($best_encoding eq "") { # encoding still not set, use defaults
488 $best_language = $self->use_default_language($filename);
489 $best_encoding = $self->use_default_encoding($filename);
490 }
491 elsif (!$self->{'extract_language'}) { # know encoding but don't need to discover language
492 $best_language = $self->use_default_language($filename);
493 }
494 else { # textcat again using the most frequent encoding or the $unicode_format set above
495 $results = $self->{'textcat'}->classify_contents_for_encoding(\$text, $filename, $best_encoding);
496 my $language;
497 ($language) = $results->[0] =~ m/^([^-]*)(?:-(.*))?$/ if (scalar @$results > 0);
498 if (!defined $language || scalar @$results > 3) {
499 # if no result or too many results, use default language for the encoding previously found
500 $best_language = $self->use_default_language($filename);
501 }
502 else { # fewer than 3 results, use the language of the first result
503 $best_language = $language;
504 }
505 }
506 }
507 }
508 }
509
510 if($best_encoding eq "" || $best_language eq "") {
511 print STDERR "****Shouldn't happen: encoding and/or language still not set. Using defaults.\n";
512 $best_encoding = $self->use_default_encoding($filename) if $best_encoding eq "";
513 $best_language = $self->use_default_language($filename) if $best_language eq "";
514 }
515# print STDERR "****Content language: $best_language; Encoding: $best_encoding.\n";
516
517
518 if ($best_encoding =~ /^iso_8859/ && &unicode::check_is_utf8($text)) {
519 # the text is valid utf8, so assume that's the real encoding
520 # (since textcat is based on probabilities)
521 $best_encoding = 'utf8';
522 }
523
524 # check for equivalents where textcat doesn't have some encodings...
525 # eg MS versions of standard encodings
526 if ($best_encoding =~ /^iso_8859_(\d+)/) {
527 my $iso = $1; # which variant of the iso standard?
528 # iso-8859 sets don't use chars 0x80-0x9f, windows codepages do
529 if ($text =~ /[\x80-\x9f]/) {
530 # Western Europe
531 if ($iso == 1 or $iso == 15) { $best_encoding = 'windows_1252' }
532 elsif ($iso == 2) {$best_encoding = 'windows_1250'} # Central Europe
533 elsif ($iso == 5) {$best_encoding = 'windows_1251'} # Cyrillic
534 elsif ($iso == 6) {$best_encoding = 'windows_1256'} # Arabic
535 elsif ($iso == 7) {$best_encoding = 'windows_1253'} # Greek
536 elsif ($iso == 8) {$best_encoding = 'windows_1255'} # Hebrew
537 elsif ($iso == 9) {$best_encoding = 'windows_1254'} # Turkish
538 }
539 }
540
541 if ($best_encoding !~ /^(ascii|utf8|unicode)$/ &&
542 !defined $encodings::encodings->{$best_encoding}) {
543 if ($self->{'verbosity'}) {
544 gsprintf($outhandle, "ReadTextFile: {ReadTextFile.unsupported_encoding}\n",
545 $filename, $best_encoding, $self->{'default_encoding'});
546 }
547 $best_encoding = $self->{'default_encoding'};
548 }
549
550 return ($best_language, $best_encoding);
551}
552
553
554sub use_default_language {
555 my $self = shift (@_);
556 my ($filename) = @_;
557
558 if ($self->{'verbosity'}>2) {
559 gsprintf($self->{'outhandle'},
560 "ReadTextFile: {ReadTextFile.could_not_extract_language}\n",
561 $filename, $self->{'default_language'});
562 }
563 return $self->{'default_language'};
564}
565
566sub use_default_encoding {
567 my $self = shift (@_);
568 my ($filename) = @_;
569
570 if ($self->{'verbosity'}>2) {
571 gsprintf($self->{'outhandle'},
572 "ReadTextFile: {ReadTextFile.could_not_extract_encoding}\n",
573 $filename, $self->{'default_encoding'});
574 }
575 return $self->{'default_encoding'};
576}
577
578# Overridden by exploding plugins (eg. ISISPlug)
579sub clean_up_after_exploding
580{
581 my $self = shift(@_);
582}
583
584
5851;
Note: See TracBrowser for help on using the repository browser.