source: gsdl/trunk/perllib/plugins/ReadTextFile.pm@ 16555

Last change on this file since 16555 was 16555, checked in by ak19, 13 years ago

Instead of sub get_language_encoding applying function ensure_utf8 on a copy of the text string to find out if this string is utf8, it uses the new sub check_is_utf8 instead

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