source: trunk/gsdl/perllib/plugins/BasPlug.pm@ 1903

Last change on this file since 1903 was 1903, checked in by sjboddie, 23 years ago

We now use textcats best guess if it returns 3 or less possibilities
(previously we used the default unless textcat returned only one
possibility).

  • Property svn:keywords set to Author Date Id Revision
File size: 21.9 KB
Line 
1###########################################################################
2#
3# BasPlug.pm -- base class for all the import plugins
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 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 BasPlug;
27
28use parsargv;
29use multiread;
30use encodings;
31use cnseg;
32use acronym;
33use textcat;
34use doc;
35use diagnostics;
36use DateExtract;
37
38sub print_general_usage {
39 my ($plugin_name) = @_;
40
41 print STDERR "\n usage: plugin $plugin_name [options]\n\n";
42
43 print STDERR " -process_exp A perl regular expression to match against filenames.\n";
44 print STDERR " Matching filenames will be processed by this plugin.\n";
45 print STDERR " Each plugin has its own default process_exp. e.g HTMLPlug\n";
46 print STDERR " defaults to '(?i)\.html?\$' i.e. all documents ending in\n";
47 print STDERR " .htm or .html (case-insensitive).\n\n";
48
49 print STDERR " -block_exp Files matching this regular expression will be blocked from\n";
50 print STDERR " being passed to any further plugins in the list. This has no\n";
51 print STDERR " real effect other than to prevent lots of warning messages\n";
52 print STDERR " about input files you don't care about. Each plugin may or may\n";
53 print STDERR " not have a default block_exp. e.g. by default HTMLPlug blocks\n";
54 print STDERR " any files with .gif, .jpg, .jpeg, .png, .rtf or .css\n";
55 print STDERR " file extensions.\n\n";
56
57
58 print STDERR " -input_encoding The encoding of the source documents. Documents will be\n";
59 print STDERR " converted from these encodings and stored internally as\n";
60 print STDERR " utf8. The default input_encoding is 'auto'. Accepted values\n";
61 print STDERR " are:\n";
62
63 print STDERR " auto: Use text categorization algorithm to automatically\n";
64 print STDERR " identify the encoding of each source document. This\n";
65 print STDERR " will be slower than explicitly setting the encoding\n";
66 print STDERR " but will work where more than one encoding is used\n";
67 print STDERR " within the same collection.\n";
68
69 print STDERR " ascii: Plain 7 bit ascii. This may be a little faster than\n";
70 print STDERR " using iso_8859_1. Beware of using 'ascii' on a collection\n";
71 print STDERR " of documents that may contain characters outside of plain\n";
72 print STDERR " 7 bit ascii though (e.g. German or French documents\n";
73 print STDERR " containing accents), use iso_8859_1 instead.\n";
74
75 print STDERR " utf8: either utf8 or unicode -- automatically detected\n";
76 print STDERR " unicode: just unicode\n";
77
78 my $e = $encodings::encodings;
79 foreach my $enc (sort {$e->{$a}->{'name'} cmp $e->{$b}->{'name'}} keys (%$e)) {
80 print STDERR " $enc: $e->{$enc}->{'name'}\n";
81 }
82
83 print STDERR " -default_encoding If -input_encoding is set to 'auto' and the text categorization\n";
84 print STDERR " algorithm fails to extract the encoding or extracts an encoding\n";
85 print STDERR " that is not supported by Greenstone, this encoding will be used\n";
86 print STDERR " instead. The default is iso_8859_1\n\n";
87
88 print STDERR " -extract_language Identify the language of each document and set 'Language' metadata. Note\n";
89 print STDERR " that this will be done automatically if -input_encoding is 'auto'.\n";
90 print STDERR " -default_language If Greenstone fails to work out what language a document is the\n";
91 print STDERR " 'Language' metadata element will be set to this value. The default\n";
92 print STDERR " is 'en' (ISO 639 language symbols should be used - en = English).\n";
93 print STDERR " Note that if -input_encoding is not set to 'auto' and -extract_language\n";
94 print STDERR " is not set, all documents will have their 'Language' metadata set to\n";
95 print STDERR " this value.\n\n";
96
97 print STDERR " -extract_acronyms Extract acronyms from within text and set as metadata\n";
98
99 print STDERR " -markup_acronyms Add acronym metadata into document text\n\n";
100
101 print STDERR " -first Comma seperated list of first sizes to extract from the text\n";
102 print STDERR " into a metadata field. The fields are called 'FirstNNN'.\n\n";
103
104 print STDERR " -extract_email Extract email addresses as metadata\n\n";
105
106 print STDERR " -extract_date Extract dates pertaining to the content of documents about history\n";
107 print STDERR " -maximum_date The maximum historical date to be used as metadata (in a Common Era\n";
108 print STDERR " date such as 1950)\n";
109 print STDERR " -maximum_century The maximum named century to be extracted as historical metadata\n";
110 print STDERR " (e.g. 14 will extract all references up to the 14th century)\n";
111 print STDERR " -no_bibliography Do not try and block bibliographic dates when extracting historical dates.\n\n";
112}
113
114# print_usage should be overridden for any sub-classes having
115# their own plugin specific options
116sub print_usage {
117 print STDERR "\nThis plugin has no plugin specific options\n\n";
118}
119
120sub new {
121 my $class = shift (@_);
122 my $plugin_name = shift (@_);
123 my $self = {};
124
125 my $enc = "^(";
126 map {$enc .= "$_|";} keys %$encodings::encodings;
127 my $denc = $enc . "ascii|utf8|unicode)\$";
128 $enc .= "ascii|utf8|unicode|auto)\$";
129
130 $self->{'outhandle'} = STDERR;
131 my $year = (localtime)[5]+1900;
132
133 # general options available to all plugins
134 if (!parsargv::parse(\@_,
135 q^process_exp/.*/^, \$self->{'process_exp'},
136 q^block_exp/.*/^, \$self->{'block_exp'},
137 qq^input_encoding/$enc/auto^, \$self->{'input_encoding'},
138 qq^default_encoding/$denc/iso_8859_1^, \$self->{'default_encoding'},
139 q^extract_acronyms^, \$self->{'extract_acronyms'},
140 q^extract_email^, \$self->{'extract_email'},
141 q^markup_acronyms^, \$self->{'markup_acronyms'},
142 q^extract_language^, \$self->{'extract_language'},
143 q^default_language/.{2}/en^, \$self->{'default_language'},
144 q^first/.*/^, \$self->{'first'},
145 q^extract_date^, \$self->{'date_extract'},
146 qq^maximum_date/\\d{4}/$year^, \$self->{'max_year'},
147 q^no_bibliography^, \$self->{'no_biblio'},
148 qq^maximum_century/-?\\d{1,2}( ?B\\.C\\.E\\.)?/-1^, \$self->{'max_century'},
149 "allow_extra_options")) {
150
151 print STDERR "\nThe $plugin_name plugin uses an incorrect general option (general options are those\n";
152 print STDERR "available to all plugins). Check your collect.cfg configuration file.\n";
153 &print_general_usage($plugin_name);
154 die "\n";
155 }
156
157 return bless $self, $class;
158}
159
160# initialize BasPlug options
161# if init() is overridden in a sub-class, remember to call BasPlug::init()
162sub init {
163 my $self = shift (@_);
164 my ($verbosity, $outhandle) = @_;
165
166 # verbosity is passed through from the processor
167 $self->{'verbosity'} = $verbosity;
168
169 # as is the outhandle ...
170 $self->{'outhandle'} = $outhandle if defined $outhandle;
171
172 # set process_exp and block_exp to defaults unless they were
173 # explicitly set
174
175 if ((!$self->is_recursive()) and
176 (!defined $self->{'process_exp'}) || ($self->{'process_exp'} eq "")) {
177
178 $self->{'process_exp'} = $self->get_default_process_exp ();
179 if ($self->{'process_exp'} eq "") {
180 warn ref($self) . " Warning: Non-recursive plugin has no process_exp\n";
181 }
182 }
183
184 if ((!defined $self->{'block_exp'}) || ($self->{'block_exp'} eq "")) {
185 $self->{'block_exp'} = $self->get_default_block_exp ();
186 }
187}
188
189sub begin {
190 my $self = shift (@_);
191 my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;
192 $self->initialise_extractors();
193}
194
195sub end {
196 my ($self) = @_;
197 $self->finalise_extractors();
198}
199
200# this function should be overridden to return 1
201# in recursive plugins
202sub is_recursive {
203 my $self = shift (@_);
204
205 return 0;
206}
207
208sub get_default_block_exp {
209 my $self = shift (@_);
210
211 return "";
212}
213
214sub get_default_process_exp {
215 my $self = shift (@_);
216
217 return "";
218}
219
220# The BasPlug read() function. This function does all the right things
221# to make general options work for a given plugin. It calls the process()
222# function which does all the work specific to a plugin (like the old
223# read functions used to do). Most plugins should define their own
224# process() function and let this read() function keep control.
225#
226# recursive plugins (e.g. RecPlug) and specialized plugins like those
227# capable of processing many documents within a single file (e.g.
228# GMLPlug) should normally implement their own version of read()
229#
230# Return number of files processed, undef if can't process
231# Note that $base_dir might be "" and that $file might
232# include directories
233
234sub read {
235 my $self = shift (@_);
236 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs) = @_;
237
238 if ($self->is_recursive()) {
239 die "BasPlug::read function must be implemented in sub-class for recursive plugins\n";
240 }
241
242 my $outhandle = $self->{'outhandle'};
243
244 my $filename = &util::filename_cat($base_dir, $file);
245 return 0 if $self->{'block_exp'} ne "" && $filename =~ /$self->{'block_exp'}/;
246 if ($filename !~ /$self->{'process_exp'}/ || !-f $filename) {
247 return undef;
248 }
249 my $plugin_name = ref ($self);
250 $file =~ s/^[\/\\]+//; # $file often begins with / so we'll tidy it up
251
252 my ($language, $encoding);
253 if ($self->{'input_encoding'} eq "auto") {
254 # use textcat to automatically work out the input encoding and language
255 ($language, $encoding) = $self->get_language_encoding ($filename);
256
257 } elsif ($self->{'extract_language'}) {
258 # use textcat to get language metadata
259 ($language, $extracted_encoding) = $self->get_language_encoding ($filename);
260 $encoding = $self->{'input_encoding'};
261
262 if ($extracted_encoding ne $encoding && $self->{'verbosity'}) {
263 print $outhandle "$plugin_name: WARNING: $file was read using $encoding encoding but ";
264 print $outhandle "appears to be encoded as $extracted_encoding.\n";
265 }
266
267 } else {
268 $language = $self->{'default_language'};
269 $encoding = $self->{'input_encoding'};
270 }
271
272 # create a new document
273 my $doc_obj = new doc ($filename, "indexed_doc");
274 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Language", $language);
275 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Encoding", $encoding);
276
277 # read in file ($text will be in utf8)
278 my $text = "";
279 $self->read_file ($filename, $encoding, \$text);
280
281 if (!length ($text)) {
282 print $outhandle "$plugin_name: ERROR: $file contains no text\n" if $self->{'verbosity'};
283 return 0;
284 }
285
286 # include any metadata passed in from previous plugins
287 # note that this metadata is associated with the top level section
288 $self->extra_metadata ($doc_obj, $doc_obj->get_top_section(), $metadata);
289
290 # do plugin specific processing of doc_obj
291 return undef unless defined ($self->process (\$text, $pluginfo, $base_dir, $file, $metadata, $doc_obj));
292
293 # do any automatic metadata extraction
294 $self->auto_extract_metadata ($doc_obj);
295
296 # add an OID
297 $doc_obj->set_OID();
298
299 # process the document
300 $processor->process($doc_obj);
301
302 return 1; # processed the file
303}
304
305# returns undef if file is rejected by the plugin
306sub process {
307 my $self = shift (@_);
308 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj) = @_;
309
310 die "Basplug::process function must be implemented in sub-class\n";
311
312 return undef; # never gets here
313}
314
315# uses the multiread package to read in the entire file pointed to
316# by filename and loads the resulting text into $$textref. Input text
317# may be in any of the encodings handled by multiread, output text
318# will be in utf8
319sub read_file {
320 my $self = shift (@_);
321 my ($filename, $encoding, $textref) = @_;
322
323 if (!-r $filename)
324 {
325 my $outhandle = $self->{'outhandle'};
326 print $outhandle "Read permission denied for $filename\n" if $self->{'verbosity'};
327 return;
328 }
329
330 $$textref = "";
331
332 open (FILE, $filename) || die "BasPlug::read_file could not open $filename for reading ($!)\n";
333
334 if ($encoding eq "ascii") {
335 undef $/;
336 $$textref = <FILE>;
337 $/ = "\n";
338 } else {
339 my $reader = new multiread();
340 $reader->set_handle ('BasPlug::FILE');
341 $reader->set_encoding ($encoding);
342 $reader->read_file ($textref);
343
344 if ($encoding eq "gb") {
345 # segment the Chinese words
346 $$textref = &cnseg::segment($$textref);
347 }
348 }
349
350 close FILE;
351}
352
353# Uses textcat to work out the encoding and language of the text in
354# $filename. All html tags are removed before processing.
355# returns an array containing "language" and "encoding"
356sub get_language_encoding {
357 my $self = shift (@_);
358 my ($filename) = @_;
359 my $outhandle = $self->{'outhandle'};
360
361 # read in file
362 open (FILE, $filename) || die "BasPlug::get_language_encoding could not open $filename for reading ($!)\n";
363 undef $/;
364 my $text = <FILE>;
365 $/ = "\n";
366 close FILE;
367
368 # remove all HTML tags
369 $text =~ s/<[^>]*>//sg;
370
371 # get the language/encoding
372 my @results = textcat::classify($text);
373
374 # if textcat returns 3 or less possibilities we'll use the
375 # first one in the list - otherwise use the defaults
376 if (scalar @results > 3) {
377
378 if ($self->{'input_encoding'} ne 'auto') {
379 if ($self->{'extract_language'} && $self->{'verbosity'}) {
380 print $outhandle "BasPlug: WARNING: language could not be extracted from $filename - ";
381 print $outhandle "defaulting to $self->{'default_language'}\n";
382 }
383 return ($self->{'default_language'}, $self->{'input_encoding'});
384
385 } else {
386 if ($self->{'verbosity'}) {
387 print $outhandle "BASPlug: WARNING: language/encoding could not be extracted from $filename - ";
388 print $outhandle "defaulting to $self->{'default_language'}/$self->{'default_encoding'}\n";
389 }
390 return ($self->{'default_language'}, $self->{'default_encoding'});
391 }
392 }
393
394 # format language/encoding
395 my ($language, $encoding) = $results[0] =~ /^([^-]*)(?:-(.*))?$/;
396 if (!defined $language) {
397 if ($self->{'verbosity'}) {
398 print $outhandle "BasPlug: WARNING: language could not be extracted from $filename - ";
399 print $outhandle "defaulting to $self->{'default_language'}\n";
400 }
401 $language = $self->{'default_language'};
402 }
403 if (!defined $encoding) {
404 if ($self->{'verbosity'}) {
405 print $outhandle "BasPlug: WARNING: encoding could not be extracted from $filename - ";
406 print $outhandle "defaulting to $self->{'default_encoding'}\n";
407 }
408 $encoding = $self->{'default_encoding'};
409 }
410
411 if ($encoding !~ /^(ascii|utf8|unicode)$/ &&
412 !defined $encodings::encodings->{$encoding}) {
413 if ($self->{'verbosity'}) {
414 print $outhandle "BasPlug: WARNING: $filename appears to be encoded in an unsupported encoding ($encoding) - ";
415 print $outhandle "using $self->{'default_encoding'}\n";
416 }
417 $encoding = $self->{'default_encoding'};
418 }
419
420 return ($language, $encoding);
421}
422
423# add any extra metadata that's been passed around from one
424# plugin to another.
425# extra_metadata uses add_utf8_metadata so it expects metadata values
426# to already be in utf8
427sub extra_metadata {
428 my $self = shift (@_);
429 my ($doc_obj, $cursection, $metadata) = @_;
430
431 foreach my $field (keys(%$metadata)) {
432 # $metadata->{$field} may be an array reference
433 if (ref ($metadata->{$field}) eq "ARRAY") {
434 map {
435 $doc_obj->add_utf8_metadata ($cursection, $field, $_);
436 } @{$metadata->{$field}};
437 } else {
438 $doc_obj->add_utf8_metadata ($cursection, $field, $metadata->{$field});
439 }
440 }
441}
442
443# initialise metadata extractors
444sub initialise_extractors {
445 my $self = shift (@_);
446
447 if ($self->{'extract_acronyms'} || $self->{'markup_acronyms'}) {
448 &acronym::initialise_acronyms();
449 }
450}
451
452# finalise metadata extractors
453sub finalise_extractors {
454 my $self = shift (@_);
455
456 if ($self->{'extract_acronyms'} || $self->{'markup_acronyms'}) {
457 &acronym::finalise_acronyms();
458 }
459}
460
461# FIRSTNNN: extract the first NNN characters as metadata
462sub extract_first_NNNN_characters {
463 my $self = shift (@_);
464 my ($textref, $doc_obj, $thissection) = @_;
465
466 foreach my $size (split /,/, $self->{'first'}) {
467 my $tmptext = $$textref;
468 $tmptext =~ s/^\s+//;
469 $tmptext =~ s/\s+$//;
470 $tmptext =~ s/\s+/ /gs;
471 $tmptext = substr ($tmptext, 0, $size);
472 $tmptext =~ s/\s\S*$/&#8230;/;
473 $doc_obj->add_utf8_metadata ($thissection, "First$size", $tmptext);
474 }
475}
476
477sub extract_email {
478 my $self = shift (@_);
479 my ($textref, $doc_obj, $thissection) = @_;
480 my $outhandle = $self->{'outhandle'};
481
482 print $outhandle " extracting email addresses ...\n"
483 if ($self->{'verbosity'} > 2);
484
485 my @email = ($$textref =~ m/([-a-z0-9\.@+_=]+@(?:[-a-z0-9]+\.)+(?:com|org|edu|mil|int|[a-z][a-z]))/g);
486 @email = sort @email;
487
488 my @email2 = ();
489 foreach my $address (@email) {
490 if (!(join(" ",@email2) =~ m/$address/ )) {
491 push @email2, $address;
492 $doc_obj->add_utf8_metadata ($thissection, "emailAddress", $address);
493 print $outhandle " extracting $address\n"
494 if ($self->{'verbosity'} > 3);
495 }
496 }
497 print $outhandle " done extracting email addresses.\n"
498 if ($self->{'verbosity'} > 2);
499
500}
501
502# extract metadata
503sub auto_extract_metadata {
504 my $self = shift (@_);
505 my ($doc_obj) = @_;
506
507 if ($self->{'extract_email'}) {
508 my $thissection = $doc_obj->get_top_section();
509 while (defined $thissection) {
510 my $text = $doc_obj->get_text($thissection);
511 $self->extract_email (\$text, $doc_obj, $thissection) if $text =~ /./;
512 $thissection = $doc_obj->get_next_section ($thissection);
513 }
514 }
515 if ($self->{'first'}) {
516 my $thissection = $doc_obj->get_top_section();
517 while (defined $thissection) {
518 my $text = $doc_obj->get_text($thissection);
519 $self->extract_first_NNNN_characters (\$text, $doc_obj, $thissection) if $text =~ /./;
520 $thissection = $doc_obj->get_next_section ($thissection);
521 }
522 }
523
524 if ($self->{'extract_acronyms'}) {
525 my $thissection = $doc_obj->get_top_section();
526 while (defined $thissection) {
527 my $text = $doc_obj->get_text($thissection);
528 $self->extract_acronyms (\$text, $doc_obj, $thissection) if $text =~ /./;
529 $thissection = $doc_obj->get_next_section ($thissection);
530 }
531 }
532
533 if ($self->{'markup_acronyms'}) {
534 my $thissection = $doc_obj->get_top_section();
535 while (defined $thissection) {
536 my $text = $doc_obj->get_text($thissection);
537 $text = $self->markup_acronyms ($text, $doc_obj, $thissection);
538 $doc_obj->delete_text($thissection);
539 $doc_obj->add_text($thissection, $text);
540 $thissection = $doc_obj->get_next_section ($thissection);
541 }
542 }
543
544 if($self->{'date_extract'}) {
545 my $thissection = $doc_obj->get_top_section();
546 while (defined $thissection) {
547
548 my $text = $doc_obj->get_text($thissection);
549 &DateExtract::get_date_metadata($text, $doc_obj,
550 $thissection,
551 $self->{'no_biblio'},
552 $self->{'max_year'},
553 $self->{'max_century'});
554 $thissection = $doc_obj->get_next_section ($thissection);
555 }
556 }
557}
558
559# extract acronyms from a section in a document. progress is
560# reported to outhandle based on the verbosity. both the Acronym
561# and the AcronymKWIC metadata items are created.
562
563sub extract_acronyms {
564 my $self = shift (@_);
565 my ($textref, $doc_obj, $thissection) = @_;
566 my $outhandle = $self->{'outhandle'};
567
568 print $outhandle " extracting acronyms ...\n"
569 if ($self->{'verbosity'} > 2);
570
571 my $acro_array = &acronym::acronyms($textref);
572
573 foreach my $acro (@$acro_array) {
574
575 #check that this is the first time ...
576 my $seen_before = "false";
577 my $previous_data = $doc_obj->get_metadata($thissection, "Acronym");
578 foreach my $thisAcro (@$previous_data) {
579 if ($thisAcro eq $acro->to_string()) {
580 $seen_before = "true";
581 print $outhandle " already seen ". $acro->to_string() . "\n"
582 if ($self->{'verbosity'} >= 4);
583 }
584 }
585
586 if ($seen_before eq "false") {
587 #write it to the file ...
588 $acro->write_to_file();
589
590 #do the normal acronym
591 $doc_obj->add_utf8_metadata($thissection, "Acronym", $acro->to_string());
592 print $outhandle " adding ". $acro->to_string() . "\n"
593 if ($self->{'verbosity'} > 3);
594
595 }
596 }
597 print $outhandle " done extracting acronyms. \n"
598 if ($self->{'verbosity'} > 2);
599}
600
601sub markup_acronyms {
602 my $self = shift (@_);
603 my ($text, $doc_obj, $thissection) = @_;
604 my $outhandle = $self->{'outhandle'};
605
606 print $outhandle " marking up acronyms ...\n"
607 if ($self->{'verbosity'} > 2);
608
609 #self is passed in to check for verbosity ...
610 $text = &acronym::markup_acronyms($text, $self);
611
612 print $outhandle " done marking up acronyms. \n"
613 if ($self->{'verbosity'} > 2);
614
615 return $text;
616}
617
6181;
Note: See TracBrowser for help on using the repository browser.