root/gs2-extensions/ngramj/perllib/plugins/ReadTextFile.pm @ 25155

Revision 25155, 27.5 KB (checked in by papitha, 8 years ago)

Tidy up of code to give controlled output (verbosity>=2)

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