source: gs2-extensions/ngramj/perllib/plugins/ReadTextFile.pm@ 25141

Last change on this file since 25141 was 25141, checked in by papitha, 10 years ago

NGRAMJ PERL MODULE ADDED /MAORI LANGUAGE GUESSING WORKING WELL!!

File size: 27.3 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 ngramj;
39use doc;
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 ];
77
78
79my $options = { 'name' => "ReadTextFile",
80 'desc' => "{ReadTextFile.desc}",
81 'abstract' => "yes",
82 'inherits' => "no",
83 'args' => $arguments };
84
85
86
87sub new {
88 my $class = shift (@_);
89 my ($pluginlist,$inputargs,$hashArgOptLists, $auxiliary) = @_;
90 push(@$pluginlist, $class);
91
92 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
93 push(@{$hashArgOptLists->{"OptList"}},$options);
94
95 my $self = new AutoExtractMetadata($pluginlist, $inputargs, $hashArgOptLists, $auxiliary);
96
97 return bless $self, $class;
98
99}
100
101
102
103# The ReadTextFile read_into_doc_obj() function. This function does all the
104# right things to make general options work for a given plugin. It reads in
105# a file and sets up a slew of metadata all saved in doc_obj, which
106# it then returns as part of a tuple (process_status,doc_obj)
107#
108# Much of this functionality used to reside in read, but it was broken
109# down into a supporting routine to make the code more flexible.
110#
111# recursive plugins (e.g. RecPlug) and specialized plugins like those
112# capable of processing many documents within a single file (e.g.
113# GMLPlug) will normally want to implement their own version of
114# read_into_doc_obj()
115#
116# Note that $base_dir might be "" and that $file might
117# include directories
118sub read_into_doc_obj {
119 my $self = shift (@_);
120 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
121
122 print STDERR "**** In Pei Jones Local version of ReadTextFile\n";
123
124 my $outhandle = $self->{'outhandle'};
125 # should we move this to read? What about secondary plugins?
126 print STDERR "<Processing n='$file' p='$self->{'plugin_type'}'>\n" if ($gli);
127 my $pp_file = &util::prettyprint_file($base_dir,$file,$gli);
128 print $outhandle "$self->{'plugin_type'} processing $pp_file\n"
129 if $self->{'verbosity'} > 1;
130
131 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
132
133 # Do encoding stuff
134 my ($language, $content_encoding) = $self->textcat_get_language_encoding ($filename_full_path);
135 if ($self->{'verbosity'} > 2) {
136 print $outhandle "ReadTextFile: reading $file as ($content_encoding,$language)\n";
137 }
138
139 # create a new document
140 my $doc_obj = new doc ($filename_full_path, "indexed_doc", $self->{'file_rename_method'});
141 my $top_section = $doc_obj->get_top_section();
142
143 # this should look at the plugin option too...
144 $doc_obj->add_utf8_metadata($top_section, "Plugin", "$self->{'plugin_type'}");
145 $doc_obj->add_utf8_metadata($top_section, "FileSize", (-s $filename_full_path));
146
147 my $plugin_filename_encoding = $self->{'filename_encoding'};
148 my $filename_encoding = $self->deduce_filename_encoding($file,$metadata,$plugin_filename_encoding);
149 $self->set_Source_metadata($doc_obj, $filename_full_path, $filename_encoding);
150
151 $doc_obj->add_utf8_metadata($top_section, "Language", $language);
152 $doc_obj->add_utf8_metadata($top_section, "Encoding", $content_encoding);
153
154 # read in file ($text will be in utf8)
155 my $text = "";
156 $self->read_file ($filename_full_path, $content_encoding, $language, \$text);
157
158 if (!length ($text)) {
159 if ($gli) {
160 print STDERR "<ProcessingError n='$file' r='File contains no text'>\n";
161 }
162 gsprintf($outhandle, "$self->{'plugin_type'}: {ReadTextFile.file_has_no_text}\n", $filename_full_path) if $self->{'verbosity'};
163
164 my $failhandle = $self->{'failhandle'};
165 gsprintf($failhandle, "$file: " . ref($self) . ": {ReadTextFile.empty_file}\n");
166 # print $failhandle "$file: " . ref($self) . ": file contains no text\n";
167 $self->{'num_not_processed'} ++;
168
169 return (0,undef); # what should we return here?? error but don't want to pass it on
170 }
171
172 # do plugin specific processing of doc_obj
173 unless (defined ($self->process (\$text, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
174 $text = '';
175 undef $text;
176 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
177 return (-1,undef);
178 }
179 $text='';
180 undef $text;
181
182 # include any metadata passed in from previous plugins
183 # note that this metadata is associated with the top level section
184 $self->add_associated_files($doc_obj, $filename_full_path);
185 $self->extra_metadata ($doc_obj, $top_section, $metadata);
186
187 # do any automatic metadata extraction
188 $self->auto_extract_metadata ($doc_obj);
189
190
191 # if we haven't found any Title so far, assign one
192 $self->title_fallback($doc_obj,$top_section,$filename_no_path);
193
194 $self->add_OID($doc_obj);
195
196 return (1,$doc_obj);
197}
198
199# uses the multiread package to read in the entire file pointed to
200# by filename and loads the resulting text into $$textref. Input text
201# may be in any of the encodings handled by multiread, output text
202# will be in utf8
203sub read_file {
204 my $self = shift (@_);
205 my ($filename, $encoding, $language, $textref) = @_;
206
207 if (!-r $filename)
208 {
209 my $outhandle = $self->{'outhandle'};
210 gsprintf($outhandle, "{ReadTextFile.read_denied}\n", $filename) if $self->{'verbosity'};
211 # print $outhandle "Read permission denied for $filename\n" if $self->{'verbosity'};
212 return;
213 }
214 $$textref = "";
215 if (!open (FILE, $filename)) {
216 gsprintf(STDERR, "ReadTextFile::read_file {ReadTextFile.could_not_open_for_reading} ($!)\n", $filename);
217 die "\n";
218 }
219
220 if ($encoding eq "ascii") {
221 # Replace file 'slurp' with faster implementation
222 sysread(FILE, $$textref, -s FILE);
223
224 # The old slow way of reading in a file
225 #undef $/;
226 #$$textref = <FILE>;
227 #$/ = "\n";
228 } else {
229 my $reader = new multiread();
230 $reader->set_handle ('ReadTextFile::FILE');
231 $reader->set_encoding ($encoding);
232 $reader->read_file ($textref);
233 }
234
235 # At this point $$textref is a binary byte string
236 # => turn it into a Unicode aware string, so full
237 # Unicode aware pattern matching can be used.
238 # For instance: 's/\x{0101}//g' or '[[:upper:]]'
239 #
240
241 $$textref = decode("utf8",$$textref);
242
243 close FILE;
244}
245
246
247# Not currently used
248sub UNUSED_read_file_usingPerlsEncodeModule {
249##sub read_file {
250 my $self = shift (@_);
251 my ($filename, $encoding, $language, $textref) = @_;
252
253 if (!-r $filename)
254 {
255 my $outhandle = $self->{'outhandle'};
256 gsprintf($outhandle, "{ReadTextFile.read_denied}\n", $filename) if $self->{'verbosity'};
257 # print $outhandle "Read permission denied for $filename\n" if $self->{'verbosity'};
258 return;
259 }
260 $$textref = "";
261 if (!open (FILE, $filename)) {
262 gsprintf(STDERR, "ReadTextFile::read_file {ReadTextFile.could_not_open_f
263or_reading} ($!)\n", $filename);
264 die "\n";
265 }
266
267 my $store_slash = $/;
268 undef $/;
269 my $text = <FILE>;
270 $/ = $store_slash;
271
272 $$textref = decode($encoding,$text);
273
274 close FILE;
275}
276
277
278sub read_file_no_decoding {
279 my $self = shift (@_);
280 my ($filename, $textref) = @_;
281
282 if (!-r $filename)
283 {
284 my $outhandle = $self->{'outhandle'};
285 gsprintf($outhandle, "{ReadTextFile.read_denied}\n", $filename) if $self->{'verbosity'};
286 # print $outhandle "Read permission denied for $filename\n" if $self->{'verbosity'};
287 return;
288 }
289 $$textref = "";
290 if (!open (FILE, $filename)) {
291 gsprintf(STDERR, "ReadTextFile::read_file {ReadTextFile.could_not_open_for_reading} ($!)\n", $filename);
292 die "\n";
293 }
294
295 my $reader = new multiread();
296 $reader->set_handle ('ReadTextFile::FILE');
297 $reader->read_file_no_decoding ($textref);
298
299 $self->{'reader'} = $reader;
300
301 close FILE;
302}
303
304
305sub decode_text {
306 my $self = shift (@_);
307 my ($raw_text, $encoding, $language, $textref) = @_;
308
309 my $reader = $self->{'reader'};
310 if (!defined $reader) {
311 gsprintf(STDERR, "ReadTextFile::decode_text needs to call ReadTextFile::read_file_no_decoding first\n");
312 }
313 else {
314 $reader->set_encoding($encoding);
315 $reader->decode_text($raw_text,$textref);
316
317 # At this point $$textref is a binary byte string
318 # => turn it into a Unicode aware string, so full
319 # Unicode aware pattern matching can be used.
320 # For instance: 's/\x{0101}//g' or '[[:upper:]]'
321
322 $$textref = decode("utf8",$$textref);
323 }
324}
325
326
327sub textcat_get_language_encoding {
328 my $self = shift (@_);
329 my ($filename) = @_;
330
331 $self->{'textcat'} = new ngramj() if (!defined($self->{'textcat'}));
332
333 my ($language, $encoding, $extracted_encoding);
334 if ($self->{'input_encoding'} eq "auto") {
335 # use textcat to automatically work out the input encoding and language
336 ($language, $encoding) = $self->get_language_encoding ($filename);
337 } elsif ($self->{'extract_language'}) {
338 # use textcat to get language metadata
339 ($language, $extracted_encoding) = $self->get_language_encoding ($filename);
340 $encoding = $self->{'input_encoding'};
341 # don't print this message for english... english in utf8 is identical
342 # to english in iso-8859-1 (except for some punctuation). We don't have
343 # a language model for en_utf8, so textcat always says iso-8859-1!
344 if ($extracted_encoding ne $encoding && $language ne "en" && $self->{'verbosity'}) {
345 my $plugin_name = ref ($self);
346 my $outhandle = $self->{'outhandle'};
347 gsprintf($outhandle, "$plugin_name: {ReadTextFile.wrong_encoding}\n", $filename, $encoding, $extracted_encoding);
348 }
349 } else {
350 $language = $self->{'default_language'};
351 $encoding = $self->{'input_encoding'};
352 }
353
354# print STDERR "**** language encoding of contents of file $filename:\n\t****$language $encoding\n";
355
356 return ($language, $encoding);
357}
358
359
360# Uses textcat to work out the encoding and language of the text in
361# $filename. All html tags are removed before processing.
362# returns an array containing "language" and "encoding"
363sub get_language_encoding {
364 my $self = shift (@_);
365 my ($filename) = @_;
366 my $outhandle = $self->{'outhandle'};
367 my $unicode_format = "";
368 my $best_language = "";
369 my $best_encoding = "";
370
371
372 # read in file
373 if (!open (FILE, $filename)) {
374 gsprintf(STDERR, "ReadTextFile::get_language_encoding {ReadTextFile.could_not_open_for_reading} ($!)\n", $filename);
375 # this is a pretty bad error, but try to continue anyway
376 return ($self->{'default_language'}, $self->{'input_encoding'});
377 }
378 undef $/;
379 my $text = <FILE>;
380 $/ = "\n";
381 close FILE;
382
383 # check if first few bytes have a Byte Order Marker
384 my $bom=substr($text,0,2); # check 16bit unicode
385 if ($bom eq "\xff\xfe") { # little endian 16bit unicode
386 $unicode_format="unicode";
387 } elsif ($bom eq "\xfe\xff") { # big endian 16bit unicode
388 $unicode_format="unicode";
389 } else {
390 $bom=substr($text,0,3); # check utf-8
391 if ($bom eq "\xef\xbb\xbf") { # utf-8 coded FEFF bom
392 $unicode_format="utf8";
393# } elsif ($bom eq "\xef\xbf\xbe") { # utf-8 coded FFFE bom. Error!?
394# $unicode_format="utf8";
395 }
396 }
397
398 my $found_html_encoding = 0;
399 # handle html files specially
400 # XXX this doesn't match plugins derived from HTMLPlug (except ConvertTo)
401 if (ref($self) eq 'HTMLPlugin' ||
402 (exists $self->{'converted_to'} && $self->{'converted_to'} eq 'HTML')){
403
404 # remove comments in head, including multiline ones, so that we don't match on
405 # inactive tags (those that are nested inside comments)
406 my ($head) = ($text =~ m/<head>(.*)<\/head>/si);
407 $head = "" unless defined $head; # some files are not proper HTML eg php files
408 $head =~ s/<!--.*?-->//sg;
409
410 # remove <title>stuff</title> -- as titles tend often to be in English
411 # for foreign language documents
412 $text =~ s!<title>.*?</title>!!si;
413
414 # see if this html file specifies its encoding
415 if ($text =~ /^<\?xml.*encoding="(.+?)"/) {
416 $best_encoding = $1;
417 }
418 # check the meta http-equiv charset tag
419 elsif ($head =~ m/<meta http-equiv.*content-type.*charset=(.+?)\"/si) {
420 $best_encoding = $1;
421 }
422 if ($best_encoding) { # we extracted an encoding
423 $best_encoding =~ s/-+/_/g;
424 $best_encoding = lc($best_encoding); # lowercase
425 if ($best_encoding eq "utf_8") { $best_encoding = "utf8" }
426 $found_html_encoding = 1;
427 # We shouldn't be modifying this here!!
428 #$self->{'input_encoding'} = $best_encoding;
429 }
430
431 # remove all HTML tags
432 $text =~ s/<[^>]*>//sg;
433 }
434
435 # don't need to do textcat if we know the encoding now AND don't need to extract language
436 if($found_html_encoding && !$self->{'extract_language'}) { # encoding specified in html file
437 $best_language = $self->{'default_language'};
438 }
439
440 else { # need to use textcat to get either the language, or get both language and encoding
441 $self->{'textcat'} = new textcat() if (!defined($self->{'textcat'}));
442
443 if($found_html_encoding) { # know encoding, find language by limiting search to known encoding
444 my $results = $self->{'textcat'}->classify_contents_for_encoding(\$text, $filename, $best_encoding);
445
446 my $language;
447 ($language) = $results->[0] =~ m/^([^-]*)(?:-(?:.*))?$/ if (scalar @$results > 0);
448
449 if (!defined $language || scalar @$results > 3) {
450 # if there were too many results even when restricting results by encoding,
451 # or if there were no results, use default language with the known encoding
452 $best_language = $self->use_default_language($filename);
453 }
454 else { # fewer than 3 results means textcat is more certain, use the first result
455 $best_language = $language;
456 }
457 }
458 else { # don't know encoding or language yet, therefore we use textcat
459 my $results = $self->{'textcat'}->classify_contents(\$text, $filename);
460
461 # if textcat returns 3 or less possibilities we'll use the first one in the list
462 if (scalar @$results <= 3) { # results will be > 0 when we don't constrain textcat by an encoding
463 my ($language, $encoding) = $results->[0] =~ m/^([^-]*)(?:-(.*))?$/;
464
465 $language = $self->use_default_language($filename) unless defined $language;
466 $encoding = $self->use_default_encoding($filename) unless defined $encoding;
467
468 $best_language = $language;
469 $best_encoding = $encoding;
470 }
471 else { # if (scalar @$results > 3) {
472 if ($unicode_format) { # in case the first had a BOM
473 $best_encoding=$unicode_format;
474 }
475 else {
476 # Find the most frequent encoding in the textcat results returned
477 # Returns "" if there's no encoding more frequent than another
478 $best_encoding = $self->{'textcat'}->most_frequent_encoding($results);
479 }
480
481 if ($best_encoding eq "") { # encoding still not set, use defaults
482 $best_language = $self->use_default_language($filename);
483 $best_encoding = $self->use_default_encoding($filename);
484 }
485 elsif (!$self->{'extract_language'}) { # know encoding but don't need to discover language
486 $best_language = $self->use_default_language($filename);
487 }
488 else { # textcat again using the most frequent encoding or the $unicode_format set above
489 $results = $self->{'textcat'}->classify_contents_for_encoding(\$text, $filename, $best_encoding);
490 my $language;
491 ($language) = $results->[0] =~ m/^([^-]*)(?:-(.*))?$/ if (scalar @$results > 0);
492 if (!defined $language || scalar @$results > 3) {
493 # if no result or too many results, use default language for the encoding previously found
494 $best_language = $self->use_default_language($filename);
495 }
496 else { # fewer than 3 results, use the language of the first result
497 $best_language = $language;
498 }
499 }
500 }
501 }
502 }
503
504 if($best_encoding eq "" || $best_language eq "") {
505 print STDERR "****Shouldn't happen: encoding and/or language still not set. Using defaults.\n";
506 $best_encoding = $self->use_default_encoding($filename) if $best_encoding eq "";
507 $best_language = $self->use_default_language($filename) if $best_language eq "";
508 }
509# print STDERR "****Content language: $best_language; Encoding: $best_encoding.\n";
510
511
512 if ($best_encoding =~ /^iso_8859/ && &unicode::check_is_utf8($text)) {
513 # the text is valid utf8, so assume that's the real encoding
514 # (since textcat is based on probabilities)
515 $best_encoding = 'utf8';
516 }
517
518 # check for equivalents where textcat doesn't have some encodings...
519 # eg MS versions of standard encodings
520 if ($best_encoding =~ /^iso_8859_(\d+)/) {
521 my $iso = $1; # which variant of the iso standard?
522 # iso-8859 sets don't use chars 0x80-0x9f, windows codepages do
523 if ($text =~ /[\x80-\x9f]/) {
524 # Western Europe
525 if ($iso == 1 or $iso == 15) { $best_encoding = 'windows_1252' }
526 elsif ($iso == 2) {$best_encoding = 'windows_1250'} # Central Europe
527 elsif ($iso == 5) {$best_encoding = 'windows_1251'} # Cyrillic
528 elsif ($iso == 6) {$best_encoding = 'windows_1256'} # Arabic
529 elsif ($iso == 7) {$best_encoding = 'windows_1253'} # Greek
530 elsif ($iso == 8) {$best_encoding = 'windows_1255'} # Hebrew
531 elsif ($iso == 9) {$best_encoding = 'windows_1254'} # Turkish
532 }
533 }
534
535 if ($best_encoding !~ /^(ascii|utf8|unicode)$/ &&
536 !defined $encodings::encodings->{$best_encoding}) {
537 if ($self->{'verbosity'}) {
538 gsprintf($outhandle, "ReadTextFile: {ReadTextFile.unsupported_encoding}\n",
539 $filename, $best_encoding, $self->{'default_encoding'});
540 }
541 $best_encoding = $self->{'default_encoding'};
542 }
543
544 return ($best_language, $best_encoding);
545}
546
547
548
549# Uses java ngram solution to work out the language of the text in
550# $filename. Fall back on textcat to to the character encoding
551# All html tags are removed before processing.
552# returns an array containing "language" and "encoding"
553sub get_language_encoding {
554 my $self = shift (@_);
555 my ($filename) = @_;
556 my $outhandle = $self->{'outhandle'};
557 my $unicode_format = "";
558 my $best_language = "";
559 my $best_encoding = "";
560
561
562 # read in file
563 if (!open (FILE, $filename)) {
564 gsprintf(STDERR, "ReadTextFile::java_ngram_get_language_encoding {ReadTextFile.could_not_open_for_reading} ($!)\n", $filename);
565 # this is a pretty bad error, but try to continue anyway
566 return ($self->{'default_language'}, $self->{'input_encoding'});
567 }
568 undef $/;
569 my $text = <FILE>;
570 $/ = "\n";
571 close FILE;
572
573 # check if first few bytes have a Byte Order Marker
574 my $bom=substr($text,0,2); # check 16bit unicode
575 if ($bom eq "\xff\xfe") { # little endian 16bit unicode
576 $unicode_format="unicode";
577 } elsif ($bom eq "\xfe\xff") { # big endian 16bit unicode
578 $unicode_format="unicode";
579 } else {
580 $bom=substr($text,0,3); # check utf-8
581 if ($bom eq "\xef\xbb\xbf") { # utf-8 coded FEFF bom
582 $unicode_format="utf8";
583# } elsif ($bom eq "\xef\xbf\xbe") { # utf-8 coded FFFE bom. Error!?
584# $unicode_format="utf8";
585 }
586 }
587
588 my $found_html_encoding = 0;
589 # handle html files specially
590 # XXX this doesn't match plugins derived from HTMLPlug (except ConvertTo)
591 if (ref($self) eq 'HTMLPlugin' ||
592 (exists $self->{'converted_to'} && $self->{'converted_to'} eq 'HTML')){
593
594 # remove comments in head, including multiline ones, so that we don't match on
595 # inactive tags (those that are nested inside comments)
596 my ($head) = ($text =~ m/<head>(.*)<\/head>/si);
597 $head = "" unless defined $head; # some files are not proper HTML eg php files
598 $head =~ s/<!--.*?-->//sg;
599
600 # remove <title>stuff</title> -- as titles tend often to be in English
601 # for foreign language documents
602 $text =~ s!<title>.*?</title>!!si;
603
604 # see if this html file specifies its encoding
605 if ($text =~ /^<\?xml.*encoding="(.+?)"/) {
606 $best_encoding = $1;
607 }
608 # check the meta http-equiv charset tag
609 elsif ($head =~ m/<meta http-equiv.*content-type.*charset=(.+?)\"/si) {
610 $best_encoding = $1;
611 }
612 if ($best_encoding) { # we extracted an encoding
613 $best_encoding =~ s/-+/_/g;
614 $best_encoding = lc($best_encoding); # lowercase
615 if ($best_encoding eq "utf_8") { $best_encoding = "utf8" }
616 $found_html_encoding = 1;
617 # We shouldn't be modifying this here!!
618 #$self->{'input_encoding'} = $best_encoding;
619 }
620
621 # remove all HTML tags
622 $text =~ s/<[^>]*>//sg;
623 }
624
625 # don't need to do textcat if we know the encoding now AND don't need to extract language
626 if($found_html_encoding && !$self->{'extract_language'}) { # encoding specified in html file
627 $best_language = $self->{'default_language'};
628 }
629
630 else { # need to use textcat to get either the language, or get both language and encoding
631 $self->{'ngramj'} = new ngramj() if (!defined($self->{'ngramj'}));
632
633 if($found_html_encoding) { # know encoding, find language by limiting search to known encoding
634 my $results = $self->{'ngramj'}->classify_contents_for_encoding(\$text, $filename, $best_encoding);
635
636 my $language;
637 ($language) = $results->[0] =~ m/^([^-]*)(?:-(?:.*))?$/ if (scalar @$results > 0);
638
639 if (!defined $language || scalar @$results > 3) {
640 # if there were too many results even when restricting results by encoding,
641 # or if there were no results, use default language with the known encoding
642 $best_language = $self->use_default_language($filename);
643 }
644 else { # fewer than 3 results means textcat is more certain, use the first result
645 $best_language = $language;
646 }
647 }
648 else { # don't know encoding or language yet, therefore we use textcat
649 my $results = $self->{'ngramj'}->classify_contents(\$text, $filename);
650
651 # if textcat returns 3 or less possibilities we'll use the first one in the list
652 if (scalar @$results <= 3) { # results will be > 0 when we don't constrain textcat by an encoding
653 my ($language, $encoding) = $results->[0] =~ m/^([^-]*)(?:-(.*))?$/;
654
655 $language = $self->use_default_language($filename) unless defined $language;
656 $encoding = $self->use_default_encoding($filename) unless defined $encoding;
657
658 $best_language = $language;
659 $best_encoding = $encoding;
660 }
661 else { # if (scalar @$results > 3) {
662 if ($unicode_format) { # in case the first had a BOM
663 $best_encoding=$unicode_format;
664 }
665 else {
666 # Find the most frequent encoding in the textcat results returned
667 # Returns "" if there's no encoding more frequent than another
668 $best_encoding = $self->{'textcat'}->most_frequent_encoding($results);
669 }
670
671 if ($best_encoding eq "") { # encoding still not set, use defaults
672 $best_language = $self->use_default_language($filename);
673 $best_encoding = $self->use_default_encoding($filename);
674 }
675 elsif (!$self->{'extract_language'}) { # know encoding but don't need to discover language
676 $best_language = $self->use_default_language($filename);
677 }
678 else { # textcat again using the most frequent encoding or the $unicode_format set above
679 $results = $self->{'textcat'}->classify_contents_for_encoding(\$text, $filename, $best_encoding);
680 my $language;
681 ($language) = $results->[0] =~ m/^([^-]*)(?:-(.*))?$/ if (scalar @$results > 0);
682 if (!defined $language || scalar @$results > 3) {
683 # if no result or too many results, use default language for the encoding previously found
684 $best_language = $self->use_default_language($filename);
685 }
686 else { # fewer than 3 results, use the language of the first result
687 $best_language = $language;
688 }
689 }
690 }
691 }
692 }
693
694 if($best_encoding eq "" || $best_language eq "") {
695 print STDERR "****Shouldn't happen: encoding and/or language still not set. Using defaults.\n";
696 $best_encoding = $self->use_default_encoding($filename) if $best_encoding eq "";
697 $best_language = $self->use_default_language($filename) if $best_language eq "";
698 }
699# print STDERR "****Content language: $best_language; Encoding: $best_encoding.\n";
700
701
702 if ($best_encoding =~ /^iso_8859/ && &unicode::check_is_utf8($text)) {
703 # the text is valid utf8, so assume that's the real encoding
704 # (since textcat is based on probabilities)
705 $best_encoding = 'utf8';
706 }
707
708 # check for equivalents where textcat doesn't have some encodings...
709 # eg MS versions of standard encodings
710 if ($best_encoding =~ /^iso_8859_(\d+)/) {
711 my $iso = $1; # which variant of the iso standard?
712 # iso-8859 sets don't use chars 0x80-0x9f, windows codepages do
713 if ($text =~ /[\x80-\x9f]/) {
714 # Western Europe
715 if ($iso == 1 or $iso == 15) { $best_encoding = 'windows_1252' }
716 elsif ($iso == 2) {$best_encoding = 'windows_1250'} # Central Europe
717 elsif ($iso == 5) {$best_encoding = 'windows_1251'} # Cyrillic
718 elsif ($iso == 6) {$best_encoding = 'windows_1256'} # Arabic
719 elsif ($iso == 7) {$best_encoding = 'windows_1253'} # Greek
720 elsif ($iso == 8) {$best_encoding = 'windows_1255'} # Hebrew
721 elsif ($iso == 9) {$best_encoding = 'windows_1254'} # Turkish
722 }
723 }
724
725 if ($best_encoding !~ /^(ascii|utf8|unicode)$/ &&
726 !defined $encodings::encodings->{$best_encoding}) {
727 if ($self->{'verbosity'}) {
728 gsprintf($outhandle, "ReadTextFile: {ReadTextFile.unsupported_encoding}\n",
729 $filename, $best_encoding, $self->{'default_encoding'});
730 }
731 $best_encoding = $self->{'default_encoding'};
732 }
733
734 return ($best_language, $best_encoding);
735}
736
737
738
739
740sub use_default_language {
741 my $self = shift (@_);
742 my ($filename) = @_;
743
744 if ($self->{'verbosity'}>2) {
745 gsprintf($self->{'outhandle'},
746 "ReadTextFile: {ReadTextFile.could_not_extract_language}\n",
747 $filename, $self->{'default_language'});
748 }
749 return $self->{'default_language'};
750}
751
752sub use_default_encoding {
753 my $self = shift (@_);
754 my ($filename) = @_;
755
756 if ($self->{'verbosity'}>2) {
757 gsprintf($self->{'outhandle'},
758 "ReadTextFile: {ReadTextFile.could_not_extract_encoding}\n",
759 $filename, $self->{'default_encoding'});
760 }
761 return $self->{'default_encoding'};
762}
763
764# Overridden by exploding plugins (eg. ISISPlug)
765sub clean_up_after_exploding
766{
767 my $self = shift(@_);
768}
769
770
7711;
Note: See TracBrowser for help on using the repository browser.