root/gsdl/trunk/perllib/plugins/ReadTextFile.pm @ 16667

Revision 16667, 14.6 KB (checked in by kjdon, 11 years ago)

get_language_encoding was setting ->input_encoding, which means its wrong for all the next files. Changed this.

  • Property svn:executable set to *
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
32
33use multiread;
34use encodings;
35use unicode;
36use textcat;
37use doc;
38use ghtml;
39use gsprintf 'gsprintf';
40
41use AutoExtractMetadata;
42
43sub BEGIN {
44    @ReadTextFile::ISA = ( 'AutoExtractMetadata' );
45}
46
47my $encoding_plus_auto_list =
48    [ { 'name' => "auto",
49    'desc' => "{ReadTextFile.input_encoding.auto}" } ];
50push(@{$encoding_plus_auto_list},@{$BasePlugin::encoding_list});
51
52my $arguments =
53    [ { 'name' => "input_encoding",
54    'desc' => "{ReadTextFile.input_encoding}",
55    'type' => "enum",
56    'list' => $encoding_plus_auto_list,
57    'reqd' => "no" ,
58    'deft' => "auto" } ,
59      { 'name' => "default_encoding",
60    'desc' => "{ReadTextFile.default_encoding}",
61    'type' => "enum",
62    'list' => $BasePlugin::encoding_list,
63    'reqd' => "no",
64        'deft' => "utf8" },
65      { 'name' => "extract_language",
66    'desc' => "{ReadTextFile.extract_language}",
67    'type' => "flag",
68    'reqd' => "no" },
69      { 'name' => "default_language",
70    'desc' => "{ReadTextFile.default_language}",
71    'type' => "string",
72    'deft' => "en",
73    'reqd' => "no" }
74      ];
75
76
77my $options = { 'name'     => "ReadTextFile",
78        'desc'     => "{ReadTextFile.desc}",
79        'abstract' => "yes",
80        'inherits' => "no",
81        'args'     => $arguments };
82
83
84
85sub new {
86    my $class = shift (@_);
87    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
88    push(@$pluginlist, $class);
89
90    push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
91    push(@{$hashArgOptLists->{"OptList"}},$options);
92
93    my $self = new AutoExtractMetadata($pluginlist, $inputargs, $hashArgOptLists);
94
95    return bless $self, $class;
96   
97}
98
99
100
101# The ReadTextFile read_into_doc_obj() function. This function does all the
102# right things to make general options work for a given plugin.  It reads in
103# a file and sets up a slew of metadata all saved in doc_obj, which
104# it then returns as part of a tuple (process_status,doc_obj)
105#
106# Much of this functionality used to reside in read, but it was broken
107# down into a supporting routine to make the code more flexible. 
108#
109# recursive plugins (e.g. RecPlug) and specialized plugins like those
110# capable of processing many documents within a single file (e.g.
111# GMLPlug) will normally want to implement their own version of
112# read_into_doc_obj()
113#
114# Note that $base_dir might be "" and that $file might
115# include directories
116sub read_into_doc_obj {
117    my $self = shift (@_); 
118    my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
119
120    my $outhandle = $self->{'outhandle'};
121    # should we move this to read? What about secondary plugins?
122    print STDERR "<Processing n='$file' p='$self->{'plugin_type'}'>\n" if ($gli);
123    print $outhandle "$self->{'plugin_type'} processing $file\n"
124        if $self->{'verbosity'} > 1;
125
126    my ($filename_full_path, $filename_no_path) =  &util::get_full_filenames($base_dir, $file);
127
128    # Do encoding stuff
129    my ($language, $encoding) = $self->textcat_get_language_encoding ($filename_full_path);
130    if ($self->{'verbosity'} > 2) {
131    print $outhandle "ReadTextFile: reading $file as ($encoding,$language)\n";
132    }
133
134    # create a new document
135    my $doc_obj = new doc ($filename_full_path, "indexed_doc");
136    my $top_section = $doc_obj->get_top_section();
137
138    # this should look at the plugin option too...
139    $doc_obj->set_OIDtype ($processor->{'OIDtype'}, $processor->{'OIDmetadata'});   
140    $doc_obj->add_utf8_metadata($top_section, "Plugin", "$self->{'plugin_type'}");
141   $doc_obj->add_utf8_metadata($top_section, "FileSize", (-s $filename_full_path));
142    $self->set_Source_metadata($doc_obj, $filename_no_path, $encoding);
143
144    $doc_obj->add_utf8_metadata($top_section, "Language", $language);
145    $doc_obj->add_utf8_metadata($top_section, "Encoding", $encoding);
146   
147    # read in file ($text will be in utf8)
148    my $text = "";
149    $self->read_file ($filename_full_path, $encoding, $language, \$text);
150
151    if (!length ($text)) {
152    if ($gli) {
153        print STDERR "<ProcessingError n='$file' r='File contains no text'>\n";
154    }
155    gsprintf($outhandle, "$self->{'plugin_type'}: {ReadTextFile.file_has_no_text}\n", $filename_full_path) if $self->{'verbosity'};
156
157    my $failhandle = $self->{'failhandle'};
158    gsprintf($failhandle, "$file: " . ref($self) . ": {ReadTextFile.empty_file}\n");
159    # print $failhandle "$file: " . ref($self) . ": file contains no text\n";
160    $self->{'num_not_processed'} ++;
161
162    return (0,undef); # what should we return here?? error but don't want to pass it on
163    }
164   
165    # do plugin specific processing of doc_obj
166    unless (defined ($self->process (\$text, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
167    $text = '';
168    undef $text;
169    print STDERR "<ProcessingError n='$file'>\n" if ($gli);
170    return (-1,undef);
171    }
172    $text='';
173    undef $text;
174   
175    # include any metadata passed in from previous plugins
176    # note that this metadata is associated with the top level section
177    $self->add_associated_files($doc_obj, $filename_full_path);
178    $self->extra_metadata ($doc_obj, $top_section, $metadata);
179
180     # do any automatic metadata extraction
181    $self->auto_extract_metadata ($doc_obj);
182
183
184    # if we haven't found any Title so far, assign one
185    $self->title_fallback($doc_obj,$top_section,$filename_no_path);
186
187    $self->add_OID($doc_obj);
188   
189    return (1,$doc_obj);
190}
191
192# uses the multiread package to read in the entire file pointed to
193# by filename and loads the resulting text into $$textref. Input text
194# may be in any of the encodings handled by multiread, output text
195# will be in utf8
196sub read_file {
197    my $self = shift (@_);
198    my ($filename, $encoding, $language, $textref) = @_;
199
200    if (!-r $filename)
201    {
202    my $outhandle = $self->{'outhandle'};
203    gsprintf($outhandle, "{ReadTextFile.read_denied}\n", $filename) if $self->{'verbosity'};
204    # print $outhandle "Read permission denied for $filename\n" if $self->{'verbosity'};
205    return;
206    }
207    $$textref = "";
208    if (!open (FILE, $filename)) {
209    gsprintf(STDERR, "ReadTextFile::read_file {ReadTextFile.could_not_open_for_reading} ($!)\n", $filename);
210    die "\n";
211    }
212     
213    if ($encoding eq "ascii") {
214    undef $/;
215    $$textref = <FILE>;
216    $/ = "\n";
217    } else {
218    my $reader = new multiread();
219    $reader->set_handle ('ReadTextFile::FILE');
220    $reader->set_encoding ($encoding);
221    $reader->read_file ($textref);
222    }
223    close FILE;
224}
225
226
227sub textcat_get_language_encoding {
228    my $self = shift (@_);
229    my ($filename) = @_;
230
231   
232    my ($language, $encoding, $extracted_encoding);
233    if ($self->{'input_encoding'} eq "auto") {
234        # use textcat to automatically work out the input encoding and language
235        ($language, $encoding) = $self->get_language_encoding ($filename);
236    } elsif ($self->{'extract_language'}) {
237        # use textcat to get language metadata
238        ($language, $extracted_encoding) = $self->get_language_encoding ($filename);
239        $encoding = $self->{'input_encoding'};
240    # don't print this message for english... english in utf8 is identical
241    # to english in iso-8859-1 (except for some punctuation). We don't have
242    # a language model for en_utf8, so textcat always says iso-8859-1!
243        if ($extracted_encoding ne $encoding && $language ne "en"
244        && $self->{'verbosity'}) {
245        my $plugin_name = ref ($self);
246        my $outhandle = $self->{'outhandle'};
247        gsprintf($outhandle, "$plugin_name: {ReadTextFile.wrong_encoding}\n", $filename, $encoding, $extracted_encoding);
248        }
249    } else {
250        $language = $self->{'default_language'};
251        $encoding = $self->{'input_encoding'};
252    }
253
254    return ($language, $encoding);
255}
256
257# Uses textcat to work out the encoding and language of the text in
258# $filename. All html tags are removed before processing.
259# returns an array containing "language" and "encoding"
260sub get_language_encoding {
261    my $self = shift (@_);
262    my ($filename) = @_;
263    my $outhandle = $self->{'outhandle'};
264    my $unicode_format = "";
265    my $best_language = "";
266    my $best_encoding = "";
267   
268    # read in file
269    if (!open (FILE, $filename)) {
270    gsprintf(STDERR, "ReadTextFile::get_language_encoding {ReadTextFile.could_not_open_for_reading} ($!)\n", $filename);
271    # this is a pretty bad error, but try to continue anyway
272    return ($self->{'default_language'}, $self->{'input_encoding'});
273    }
274    undef $/;
275    my $text = <FILE>;
276    $/ = "\n";
277    close FILE;
278
279    # check if first few bytes have a Byte Order Marker
280    my $bom=substr($text,0,2); # check 16bit unicode
281    if ($bom eq "\xff\xfe") { # little endian 16bit unicode
282    $unicode_format="unicode";
283    } elsif ($bom eq "\xfe\xff") { # big endian 16bit unicode
284    $unicode_format="unicode";
285    } else {
286    $bom=substr($text,0,3); # check utf-8
287    if ($bom eq "\xef\xbb\xbf") { # utf-8 coded FEFF bom
288        $unicode_format="utf8";
289#   } elsif ($bom eq "\xef\xbf\xbe") { # utf-8 coded FFFE bom. Error!?
290#       $unicode_format="utf8";
291    }
292    }
293   
294    my $found_html_encoding = 0;
295    # handle html files specially
296    # XXX this doesn't match plugins derived from HTMLPlug (except ConvertTo)
297    if (ref($self) eq 'HTMLPlugin' ||
298    (exists $self->{'converted_to'} && $self->{'converted_to'} eq 'HTML')){
299
300    # remove <title>stuff</title> -- as titles tend often to be in English
301    # for foreign language documents
302    $text =~ s!<title>.*?</title>!!si;
303
304    # see if this html file specifies its encoding
305    if ($text =~ /^<\?xml.*encoding="(.+?)"/) {
306        $best_encoding = $1;
307    } elsif ($text =~ /<meta http-equiv.*content-type.*charset=(.+?)"/i) {#"
308        $best_encoding = $1;
309    }
310    if ($best_encoding) { # we extracted an encoding
311        $best_encoding =~ s/-+/_/g;
312        $best_encoding = lc($best_encoding); # lowercase
313        if ($best_encoding eq "utf_8") { $best_encoding = "utf8" }
314        $found_html_encoding = 1;
315        # We shouldn't be modifying this here!!
316        #$self->{'input_encoding'} = $best_encoding;
317    }
318       
319    # remove all HTML tags
320    $text =~ s/<[^>]*>//sg;
321    }
322
323    # get the language/encoding
324    $self->{'textcat'} = new textcat() if (!defined($self->{'textcat'}));
325    my $results = $self->{'textcat'}->classify(\$text);
326
327    # if textcat returns 3 or less possibilities we'll use the
328    # first one in the list - otherwise use the defaults
329    if (scalar @$results > 3) {
330    if ($unicode_format) { # in case the first had a BOM
331        $best_encoding=$unicode_format;
332    } else {
333        my %guessed_encodings = ();
334        foreach my $result (@$results) {
335        $result =~ /([^\-]+)$/;
336        my $enc=$1;
337        if (!defined($guessed_encodings{$enc})) {
338            $guessed_encodings{$enc}=0;
339        }
340        $guessed_encodings{$enc}++;
341        }
342
343        $guessed_encodings{""}=-1; # for default best_encoding of ""
344        foreach my $enc (keys %guessed_encodings) {
345        if ($guessed_encodings{$enc} >
346            $guessed_encodings{$best_encoding}){
347            $best_encoding=$enc;
348        }
349        }
350    }
351
352    if ($self->{'input_encoding'} ne 'auto') {
353        if ($self->{'extract_language'} && ($self->{'verbosity'}>2)) {
354        gsprintf($outhandle,
355             "ReadTextFile: {ReadTextFile.could_not_extract_language}\n",
356             $filename, $self->{'default_language'});
357        }       
358        $best_language = $self->{'default_language'};
359        if (!$found_html_encoding) {
360        $best_encoding = $self->{'input_encoding'};
361        }
362
363    } else {
364        if ($self->{'verbosity'}>2) {
365        gsprintf($outhandle,
366             "ReadTextFile: {ReadTextFile.could_not_extract_language}\n",
367             $filename, $self->{'default_language'});
368        }
369        $best_language = $self->{'default_language'};
370    }
371    } else { # <= 3 suggestions
372    my ($language, $encoding) = $results->[0] =~ /^([^-]*)(?:-(.*))?$/;
373    if (!defined $language) {
374        if ($self->{'verbosity'}>2) {
375        gsprintf($outhandle,
376            "ReadTextFile: {ReadTextFile.could_not_extract_language}\n",
377            $filename, $self->{'default_language'});
378        }
379        $language = $self->{'default_language'};
380    }
381    if (!defined $encoding) {
382        if ($self->{'verbosity'}>2) {
383        gsprintf($outhandle,
384            "ReadTextFile: {ReadTextFile.could_not_extract_encoding}\n",
385            $filename, $self->{'default_encoding'});
386        }
387        $encoding = $self->{'default_encoding'};
388    }
389    $best_language = $language;
390    if (! $best_encoding ) { # may already be set... eg from html meta tag
391        $best_encoding = $encoding;
392    }
393    }
394
395    if ($best_encoding =~ /^iso_8859/ && &unicode::check_is_utf8($text)) {
396    # the text is valid utf8, so assume that's the real encoding
397    # (since textcat is based on probabilities)
398    $best_encoding = 'utf8';
399    }
400
401    # check for equivalents where textcat doesn't have some encodings...
402    # eg MS versions of standard encodings
403    if ($best_encoding =~ /^iso_8859_(\d+)/) {
404    my $iso = $1; # which variant of the iso standard?
405    # iso-8859 sets don't use chars 0x80-0x9f, windows codepages do
406    if ($text =~ /[\x80-\x9f]/) {
407        # Western Europe
408        if ($iso == 1 or $iso == 15) { $best_encoding = 'windows_1252' }
409        elsif ($iso == 2) {$best_encoding = 'windows_1250'} # Central Europe
410        elsif ($iso == 5) {$best_encoding = 'windows_1251'} # Cyrillic
411        elsif ($iso == 6) {$best_encoding = 'windows_1256'} # Arabic
412        elsif ($iso == 7) {$best_encoding = 'windows_1253'} # Greek
413        elsif ($iso == 8) {$best_encoding = 'windows_1255'} # Hebrew
414        elsif ($iso == 9) {$best_encoding = 'windows_1254'} # Turkish
415    }
416    }
417
418    if ($best_encoding !~ /^(ascii|utf8|unicode)$/ &&
419    !defined $encodings::encodings->{$best_encoding}) {
420    if ($self->{'verbosity'}) {
421        gsprintf($outhandle, "ReadTextFile: {ReadTextFile.unsupported_encoding}\n",
422             $filename, $best_encoding, $self->{'default_encoding'});
423    }
424    $best_encoding = $self->{'default_encoding'};
425    }
426
427    return ($best_language, $best_encoding);
428}
429
430
431
432# Overridden by exploding plugins (eg. ISISPlug)
433sub clean_up_after_exploding
434{
435    my $self = shift(@_);
436}
437
438
4391;
Note: See TracBrowser for help on using the browser.