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

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

* empty log message *

  • Property svn:keywords set to Author Date Id Revision
File size: 21.8 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 (scalar @results != 1) {
375
376 if ($self->{'input_encoding'} ne 'auto') {
377 if ($self->{'extract_language'} && $self->{'verbosity'}) {
378 print $outhandle "BasPlug: WARNING: language could not be extracted from $filename - ";
379 print $outhandle "defaulting to $self->{'default_language'}\n";
380 }
381 return ($self->{'default_language'}, $self->{'input_encoding'});
382
383 } else {
384 if ($self->{'verbosity'}) {
385 print $outhandle "BASPlug: WARNING: language/encoding could not be extracted from $filename - ";
386 print $outhandle "defaulting to $self->{'default_language'}/$self->{'default_encoding'}\n";
387 }
388 return ($self->{'default_language'}, $self->{'default_encoding'});
389 }
390 }
391
392 # format language/encoding
393 my ($language, $encoding) = $results[0] =~ /^([^-]*)(?:-(.*))?$/;
394 if (!defined $language) {
395 if ($self->{'verbosity'}) {
396 print $outhandle "BasPlug: WARNING: language could not be extracted from $filename - ";
397 print $outhandle "defaulting to $self->{'default_language'}\n";
398 }
399 $language = $self->{'default_language'};
400 }
401 if (!defined $encoding) {
402 if ($self->{'verbosity'}) {
403 print $outhandle "BasPlug: WARNING: encoding could not be extracted from $filename - ";
404 print $outhandle "defaulting to $self->{'default_encoding'}\n";
405 }
406 $encoding = $self->{'default_encoding'};
407 }
408
409 if ($encoding !~ /^(ascii|utf8|unicode)$/ &&
410 !defined $encodings::encodings->{$encoding}) {
411 if ($self->{'verbosity'}) {
412 print $outhandle "BasPlug: WARNING: $filename appears to be encoded in an unsupported encoding ($encoding) - ";
413 print $outhandle "using $self->{'default_encoding'}\n";
414 }
415 $encoding = $self->{'default_encoding'};
416 }
417
418 return ($language, $encoding);
419}
420
421# add any extra metadata that's been passed around from one
422# plugin to another.
423# extra_metadata uses add_utf8_metadata so it expects metadata values
424# to already be in utf8
425sub extra_metadata {
426 my $self = shift (@_);
427 my ($doc_obj, $cursection, $metadata) = @_;
428
429 foreach my $field (keys(%$metadata)) {
430 # $metadata->{$field} may be an array reference
431 if (ref ($metadata->{$field}) eq "ARRAY") {
432 map {
433 $doc_obj->add_utf8_metadata ($cursection, $field, $_);
434 } @{$metadata->{$field}};
435 } else {
436 $doc_obj->add_utf8_metadata ($cursection, $field, $metadata->{$field});
437 }
438 }
439}
440
441# initialise metadata extractors
442sub initialise_extractors {
443 my $self = shift (@_);
444
445 if ($self->{'extract_acronyms'} || $self->{'markup_acronyms'}) {
446 &acronym::initialise_acronyms();
447 }
448}
449
450# finalise metadata extractors
451sub finalise_extractors {
452 my $self = shift (@_);
453
454 if ($self->{'extract_acronyms'} || $self->{'markup_acronyms'}) {
455 &acronym::finalise_acronyms();
456 }
457}
458
459# FIRSTNNN: extract the first NNN characters as metadata
460sub extract_first_NNNN_characters {
461 my $self = shift (@_);
462 my ($textref, $doc_obj, $thissection) = @_;
463
464 foreach my $size (split /,/, $self->{'first'}) {
465 my $tmptext = $$textref;
466 $tmptext =~ s/^\s+//;
467 $tmptext =~ s/\s+$//;
468 $tmptext =~ s/\s+/ /gs;
469 $tmptext = substr ($tmptext, 0, $size);
470 $tmptext =~ s/\s\S*$/&#8230;/;
471 $doc_obj->add_utf8_metadata ($thissection, "First$size", $tmptext);
472 }
473}
474
475sub extract_email {
476 my $self = shift (@_);
477 my ($textref, $doc_obj, $thissection) = @_;
478 my $outhandle = $self->{'outhandle'};
479
480 print $outhandle " extracting email addresses ...\n"
481 if ($self->{'verbosity'} > 2);
482
483 my @email = ($$textref =~ m/([-a-z0-9\.@+_=]+@(?:[-a-z0-9]+\.)+(?:com|org|edu|mil|int|[a-z][a-z]))/g);
484 @email = sort @email;
485
486 my @email2 = ();
487 foreach my $address (@email) {
488 if (!(join(" ",@email2) =~ m/$address/ )) {
489 push @email2, $address;
490 $doc_obj->add_utf8_metadata ($thissection, "emailAddress", $address);
491 print $outhandle " extracting $address\n"
492 if ($self->{'verbosity'} > 3);
493 }
494 }
495 print $outhandle " done extracting email addresses.\n"
496 if ($self->{'verbosity'} > 2);
497
498}
499
500# extract metadata
501sub auto_extract_metadata {
502 my $self = shift (@_);
503 my ($doc_obj) = @_;
504
505 if ($self->{'extract_email'}) {
506 my $thissection = $doc_obj->get_top_section();
507 while (defined $thissection) {
508 my $text = $doc_obj->get_text($thissection);
509 $self->extract_email (\$text, $doc_obj, $thissection) if $text =~ /./;
510 $thissection = $doc_obj->get_next_section ($thissection);
511 }
512 }
513 if ($self->{'first'}) {
514 my $thissection = $doc_obj->get_top_section();
515 while (defined $thissection) {
516 my $text = $doc_obj->get_text($thissection);
517 $self->extract_first_NNNN_characters (\$text, $doc_obj, $thissection) if $text =~ /./;
518 $thissection = $doc_obj->get_next_section ($thissection);
519 }
520 }
521
522 if ($self->{'extract_acronyms'}) {
523 my $thissection = $doc_obj->get_top_section();
524 while (defined $thissection) {
525 my $text = $doc_obj->get_text($thissection);
526 $self->extract_acronyms (\$text, $doc_obj, $thissection) if $text =~ /./;
527 $thissection = $doc_obj->get_next_section ($thissection);
528 }
529 }
530
531 if ($self->{'markup_acronyms'}) {
532 my $thissection = $doc_obj->get_top_section();
533 while (defined $thissection) {
534 my $text = $doc_obj->get_text($thissection);
535 $text = $self->markup_acronyms ($text, $doc_obj, $thissection);
536 $doc_obj->delete_text($thissection);
537 $doc_obj->add_text($thissection, $text);
538 $thissection = $doc_obj->get_next_section ($thissection);
539 }
540 }
541
542 if($self->{'date_extract'}) {
543 my $thissection = $doc_obj->get_top_section();
544 while (defined $thissection) {
545
546 my $text = $doc_obj->get_text($thissection);
547 &DateExtract::get_date_metadata($text, $doc_obj,
548 $thissection,
549 $self->{'no_biblio'},
550 $self->{'max_year'},
551 $self->{'max_century'});
552 $thissection = $doc_obj->get_next_section ($thissection);
553 }
554 }
555}
556
557# extract acronyms from a section in a document. progress is
558# reported to outhandle based on the verbosity. both the Acronym
559# and the AcronymKWIC metadata items are created.
560
561sub extract_acronyms {
562 my $self = shift (@_);
563 my ($textref, $doc_obj, $thissection) = @_;
564 my $outhandle = $self->{'outhandle'};
565
566 print $outhandle " extracting acronyms ...\n"
567 if ($self->{'verbosity'} > 2);
568
569 my $acro_array = &acronym::acronyms($textref);
570
571 foreach my $acro (@$acro_array) {
572
573 #check that this is the first time ...
574 my $seen_before = "false";
575 my $previous_data = $doc_obj->get_metadata($thissection, "Acronym");
576 foreach my $thisAcro (@$previous_data) {
577 if ($thisAcro eq $acro->to_string()) {
578 $seen_before = "true";
579 print $outhandle " already seen ". $acro->to_string() . "\n"
580 if ($self->{'verbosity'} >= 4);
581 }
582 }
583
584 if ($seen_before eq "false") {
585 #write it to the file ...
586 $acro->write_to_file();
587
588 #do the normal acronym
589 $doc_obj->add_utf8_metadata($thissection, "Acronym", $acro->to_string());
590 print $outhandle " adding ". $acro->to_string() . "\n"
591 if ($self->{'verbosity'} > 3);
592
593 }
594 }
595 print $outhandle " done extracting acronyms. \n"
596 if ($self->{'verbosity'} > 2);
597}
598
599sub markup_acronyms {
600 my $self = shift (@_);
601 my ($text, $doc_obj, $thissection) = @_;
602 my $outhandle = $self->{'outhandle'};
603
604 print $outhandle " marking up acronyms ...\n"
605 if ($self->{'verbosity'} > 2);
606
607 #self is passed in to check for verbosity ...
608 $text = &acronym::markup_acronyms($text, $self);
609
610 print $outhandle " done marking up acronyms. \n"
611 if ($self->{'verbosity'} > 2);
612
613 return $text;
614}
615
6161;
Note: See TracBrowser for help on using the repository browser.