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

Last change on this file since 8366 was 8166, checked in by mdewsnip, 20 years ago

Added FileSize metadata in most plugins.

  • Property svn:keywords set to Author Date Id Revision
File size: 31.0 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
28eval {require bytes};
29
30# suppress the annoying "subroutine redefined" warning that various
31# plugins cause under perl 5.6
32$SIG{__WARN__} = sub {warn($_[0]) unless ($_[0] =~ /Subroutine\s+\S+\sredefined/)};
33
34use Kea;
35use parsargv;
36use multiread;
37use encodings;
38use cnseg;
39use acronym;
40use textcat;
41use doc;
42eval "require diagnostics"; # some perl distros (eg mac) don't have this
43use DateExtract;
44use ghtml;
45use gsprintf;
46use printusage;
47
48
49my $unicode_list =
50 [ { 'name' => "auto",
51 'desc' => "{BasPlug.input_encoding.auto}" },
52 { 'name' => "ascii",
53 'desc' => "{BasPlug.input_encoding.ascii}" },
54 { 'name' => "utf8",
55 'desc' => "{BasPlug.input_encoding.utf8}" },
56 { 'name' => "unicode",
57 'desc' => "{BasPlug.input_encoding.unicode}" } ];
58
59my $arguments =
60 [ { 'name' => "process_exp",
61 'desc' => "{BasPlug.process_exp}",
62 'type' => "regexp",
63 'deft' => "",
64 'reqd' => "no" },
65 { 'name' => "block_exp",
66 'desc' => "{BasPlug.block_exp}",
67 'type' => "regexp",
68 'deft' => "",
69 'reqd' => "no" },
70 { 'name' => "input_encoding",
71 'desc' => "{BasPlug.input_encoding}",
72 'type' => "enum",
73 'list' => $unicode_list,
74 'reqd' => "no" ,
75 'deft' => "auto" } ,
76 { 'name' => "default_encoding",
77 'desc' => "{BasPlug.default_encoding}",
78 'type' => "enum",
79 'list' => $unicode_list,
80 'reqd' => "no",
81 'deft' => "utf8" },
82 { 'name' => "extract_language",
83 'desc' => "{BasPlug.extract_language}",
84 'type' => "flag",
85 'reqd' => "no" },
86 { 'name' => "default_language",
87 'desc' => "{BasPlug.default_language}",
88 'type' => "language",
89 'deft' => "en",
90 'reqd' => "no" },
91 { 'name' => "extract_acronyms",
92 'desc' => "{BasPlug.extract_acronyms}",
93 'type' => "flag",
94 'reqd' => "no" },
95 { 'name' => "markup_acronyms",
96 'desc' => "{BasPlug.markup_acronyms}",
97 'type' => "flag",
98 'reqd' => "no" },
99 { 'name' => "first",
100 'desc' => "{BasPlug.first}",
101 'type' => "string",
102 'reqd' => "no" },
103 { 'name' => "extract_email",
104 'desc' => "{BasPlug.extract_email}",
105 'type' => "flag",
106 'reqd' => "no" },
107 { 'name' => "extract_historical_years",
108 'desc' => "{BasPlug.extract_historical_years}",
109 'type' => "flag",
110 'reqd' => "no" },
111 { 'name' => "maximum_year",
112 'desc' => "{BasPlug.maximum_year}",
113 'type' => "int",
114 'deft' => (localtime)[5]+1900,
115 'reqd' => "no"},
116 { 'name' => "maximum_century",
117 'desc' => "{BasPlug.maximum_century}",
118 'type' => "string",
119 'deft' => "",
120 'reqd' => "no" },
121 { 'name' => "no_bibliography",
122 'desc' => "{BasPlug.no_bibliography}",
123 'type' => "flag",
124 'reqd' => "no"},
125 { 'name' => "cover_image",
126 'desc' => "{BasPlug.cover_image}",
127 'type' => "flag",
128 'reqd' => "no" } ];
129
130my $options = { 'name' => "BasPlug",
131 'desc' => "{BasPlug.desc}",
132 'abstract' => "yes",
133 'inherits' => "no",
134 'args' => $arguments };
135
136
137sub gsprintf
138{
139 return &gsprintf::gsprintf(@_);
140}
141
142
143sub get_arguments
144{
145 local $self = shift(@_);
146 local $optionlistref = $self->{'option_list'};
147 local @optionlist = @$optionlistref;
148 local $pluginoptions = pop(@$optionlistref);
149 local $pluginarguments = $pluginoptions->{'args'};
150 return $pluginarguments;
151}
152
153
154sub print_xml_usage
155{
156 local $self = shift(@_);
157
158 # XML output is always in UTF-8
159 &gsprintf::output_strings_in_UTF8;
160
161 &PrintUsage::print_xml_header();
162 $self->print_xml();
163}
164
165
166sub print_xml
167{
168 local $self = shift(@_);
169
170 local $optionlistref = $self->{'option_list'};
171 local @optionlist = @$optionlistref;
172 local $pluginoptions = pop(@$optionlistref);
173 return if (!defined($pluginoptions));
174
175 &gsprintf(STDERR, "<PlugInfo>\n");
176 &gsprintf(STDERR, " <Name>$pluginoptions->{'name'}</Name>\n");
177 my $desc = &gsprintf::lookup_string($pluginoptions->{'desc'});
178 $desc =~ s/</&amp;lt;/g; # doubly escaped
179 $desc =~ s/>/&amp;gt;/g;
180
181 &gsprintf(STDERR, " <Desc>$desc</Desc>\n");
182 &gsprintf(STDERR, " <Abstract>$pluginoptions->{'abstract'}</Abstract>\n");
183 &gsprintf(STDERR, " <Inherits>$pluginoptions->{'inherits'}</Inherits>\n");
184 &gsprintf(STDERR, " <Arguments>\n");
185 if (defined($pluginoptions->{'args'})) {
186 &PrintUsage::print_options_xml($pluginoptions->{'args'});
187 }
188
189 # Recurse up the plugin hierarchy
190 $self->print_xml();
191
192 &gsprintf(STDERR, " </Arguments>\n");
193 &gsprintf(STDERR, "</PlugInfo>\n");
194}
195
196
197sub print_txt_usage
198{
199 local $self = shift(@_);
200
201 # Print the usage message for a plugin (recursively)
202 local $descoffset = $self->determine_description_offset(0);
203 $self->print_plugin_usage($descoffset, 1);
204}
205
206
207sub determine_description_offset
208{
209 local $self = shift(@_);
210 local $maxoffset = shift(@_);
211
212 local $optionlistref = $self->{'option_list'};
213 local @optionlist = @$optionlistref;
214 local $pluginoptions = pop(@$optionlistref);
215 return $maxoffset if (!defined($pluginoptions));
216
217 # Find the length of the longest option string of this plugin
218 local $pluginargs = $pluginoptions->{'args'};
219 if (defined($pluginargs)) {
220 local $longest = &PrintUsage::find_longest_option_string($pluginargs);
221 if ($longest > $maxoffset) {
222 $maxoffset = $longest;
223 }
224 }
225
226 # Recurse up the plugin hierarchy
227 $maxoffset = $self->determine_description_offset($maxoffset);
228 $self->{'option_list'} = \@optionlist;
229 return $maxoffset;
230}
231
232
233sub print_plugin_usage
234{
235 local $self = shift(@_);
236 local $descoffset = shift(@_);
237 local $isleafclass = shift(@_);
238
239 local $optionlistref = $self->{'option_list'};
240 local @optionlist = @$optionlistref;
241 local $pluginoptions = pop(@$optionlistref);
242 return if (!defined($pluginoptions));
243
244 local $pluginname = $pluginoptions->{'name'};
245 local $pluginargs = $pluginoptions->{'args'};
246 local $plugindesc = $pluginoptions->{'desc'};
247
248 # Produce the usage information using the data structure above
249 if ($isleafclass) {
250 if (defined($plugindesc)) {
251 &gsprintf(STDERR, "$plugindesc\n\n");
252 }
253 &gsprintf(STDERR, " {common.usage}: plugin $pluginname [{common.options}]\n\n");
254 }
255
256 # Display the plugin options, if there are some
257 if (defined($pluginargs)) {
258 # Calculate the column offset of the option descriptions
259 local $optiondescoffset = $descoffset + 2; # 2 spaces between options & descriptions
260
261 if ($isleafclass) {
262 &gsprintf(STDERR, " {common.specific_options}:\n");
263 }
264 else {
265 &gsprintf(STDERR, " {common.general_options}:\n", $pluginname);
266 }
267
268 # Display the plugin options
269 &PrintUsage::print_options_txt($pluginargs, $optiondescoffset);
270 }
271
272 # Recurse up the plugin hierarchy
273 $self->print_plugin_usage($descoffset, 0);
274 $self->{'option_list'} = \@optionlist;
275}
276
277
278sub new {
279 my $class = shift (@_);
280 my $plugin_name = shift (@_);
281 my $self = {};
282 $self->{'plugin_type'} = "BasPlug";
283 my $enc = "^(";
284 map {$enc .= "$_|";} keys %$encodings::encodings;
285 my $denc = $enc . "ascii|utf8|unicode)\$";
286 $enc .= "ascii|utf8|unicode|auto)\$";
287
288 $self->{'outhandle'} = STDERR;
289 my $year = (localtime)[5]+1900;
290
291 $self->{'textcat'} = new textcat();
292
293 $self->{'num_processed'} = 0;
294 $self->{'num_not_processed'} = 0;
295 $self->{'num_blocked'} = 0;
296 $self->{'num_archives'} = 0;
297
298 # 14-05-02 To allow for proper inheritance of arguments - John Thompson
299 $self->{'option_list'} = [ $options ];
300
301 # general options available to all plugins
302 if (!parsargv::parse(\@_,
303 q^process_exp/.*/^, \$self->{'process_exp'},
304 q^block_exp/.*/^, \$self->{'block_exp'},
305 q^extract_language^, \$self->{'extract_language'},
306 q^extract_acronyms^, \$self->{'extract_acronyms'},
307 q^extract_keyphrases^, \$self->{'kea'}, #with extra options (UNDOCUMENTED)
308 q^extract_keyphrase_options/.*/^, \$self->{'kea_options'}, #no extra options (UNDOCUMENTED)
309 qq^input_encoding/$enc/auto^, \$self->{'input_encoding'},
310 qq^default_encoding/$denc/utf8^, \$self->{'default_encoding'},
311 q^extract_email^, \$self->{'extract_email'},
312 q^markup_acronyms^, \$self->{'markup_acronyms'},
313 q^default_language/.{2}/en^, \$self->{'default_language'},
314 q^first/.*/^, \$self->{'first'},
315 q^extract_historical_years^, \$self->{'date_extract'},
316 qq^maximum_year/\\d{4}/$year^, \$self->{'max_year'},
317 q^no_bibliography^, \$self->{'no_biblio'},
318 qq^maximum_century/-?\\d{1,2}( ?B\\.C\\.E\\.)?/-1^, \$self->{'max_century'},
319 q^cover_image^, \$self->{'cover_image'},
320 q^separate_cjk^, \$self->{'separate_cjk'},
321 "allow_extra_options")) {
322
323 &gsprintf(STDERR, "\n{BasPlug.bad_general_option}\n", $plugin_name);
324 $self->print_txt_usage(""); # Use default resource bundle
325 die "\n";
326 }
327
328 return bless $self, $class;
329}
330
331# initialize BasPlug options
332# if init() is overridden in a sub-class, remember to call BasPlug::init()
333sub init {
334 my $self = shift (@_);
335 my ($verbosity, $outhandle, $failhandle) = @_;
336
337 # verbosity is passed through from the processor
338 $self->{'verbosity'} = $verbosity;
339
340 # as are the outhandle and failhandle
341 $self->{'outhandle'} = $outhandle if defined $outhandle;
342 $self->{'failhandle'} = $failhandle;
343
344 # set process_exp and block_exp to defaults unless they were
345 # explicitly set
346
347 if ((!$self->is_recursive()) and
348 (!defined $self->{'process_exp'}) || ($self->{'process_exp'} eq "")) {
349
350 $self->{'process_exp'} = $self->get_default_process_exp ();
351 if ($self->{'process_exp'} eq "") {
352 warn ref($self) . " Warning: Non-recursive plugin has no process_exp\n";
353 }
354 }
355
356 if ((!defined $self->{'block_exp'}) || ($self->{'block_exp'} eq "")) {
357 $self->{'block_exp'} = $self->get_default_block_exp ();
358 }
359}
360
361sub begin {
362 my $self = shift (@_);
363 my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;
364 $self->initialise_extractors();
365}
366
367sub end {
368 my ($self) = @_;
369 $self->finalise_extractors();
370}
371
372# this function should be overridden to return 1
373# in recursive plugins
374sub is_recursive {
375 my $self = shift (@_);
376
377 return 0;
378}
379
380sub get_default_block_exp {
381 my $self = shift (@_);
382
383 return "";
384}
385
386sub get_default_process_exp {
387 my $self = shift (@_);
388
389 return "";
390}
391
392# The BasPlug read() function. This function does all the right things
393# to make general options work for a given plugin. It calls the process()
394# function which does all the work specific to a plugin (like the old
395# read functions used to do). Most plugins should define their own
396# process() function and let this read() function keep control.
397#
398# recursive plugins (e.g. RecPlug) and specialized plugins like those
399# capable of processing many documents within a single file (e.g.
400# GMLPlug) should normally implement their own version of read()
401#
402# Return number of files processed, undef if can't recognise, -1 if can't
403# process
404# Note that $base_dir might be "" and that $file might
405# include directories
406
407sub read {
408 my $self = shift (@_);
409
410 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $gli) = @_;
411
412 if ($self->is_recursive()) {
413 &gsprintf(STDERR, "{BasPlug.read_must_be_implemented}") && die "\n";
414 }
415
416 my $outhandle = $self->{'outhandle'};
417
418 my $filename = $file;
419 $filename = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\w/;
420
421 if ($self->{'block_exp'} ne "" && $filename =~ /$self->{'block_exp'}/) {
422 $self->{'num_blocked'} ++;
423 return 0; # blocked
424 }
425 if ($filename !~ /$self->{'process_exp'}/ || !-f $filename) {
426 return undef; # can't recognise
427 }
428 $file =~ s/^[\/\\]+//; # $file often begins with / so we'll tidy it up
429
430 # Do encoding stuff
431 my ($language, $encoding) = $self->textcat_get_language_encoding ($filename);
432
433 # create a new document
434 my $doc_obj = new doc ($filename, "indexed_doc");
435 $doc_obj->set_OIDtype ($processor->{'OIDtype'});
436 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Language", $language);
437 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Encoding", $encoding);
438 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
439 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "FileSize", (-s $filename));
440
441 my ($filemeta) = $file =~ /([^\\\/]+)$/;
442 # how do we know what encoding the filename is in?
443 $doc_obj->add_metadata($doc_obj->get_top_section(), "Source", &ghtml::dmsafe($filemeta));
444 if ($self->{'cover_image'}) {
445 $self->associate_cover_image($doc_obj, $filename);
446 }
447
448 # read in file ($text will be in utf8)
449 my $text = "";
450 $self->read_file ($filename, $encoding, $language, \$text);
451
452 if (!length ($text)) {
453 my $plugin_name = ref ($self);
454 &gsprintf($outhandle, "$plugin_name: {BasPlug.file_has_no_text}\n", $filename) if $self->{'verbosity'};
455
456 my $failhandle = $self->{'failhandle'};
457 &gsprintf($failhandle, "$file: " . ref($self) . ": {BasPlug.empty_file}\n");
458 # print $failhandle "$file: " . ref($self) . ": file contains no text\n";
459 $self->{'num_not_processed'} ++;
460
461 return 0; # what should we return here?? error but don't want to pass it on
462 }
463
464 # include any metadata passed in from previous plugins
465 # note that this metadata is associated with the top level section
466 $self->extra_metadata ($doc_obj, $doc_obj->get_top_section(), $metadata);
467
468 # do plugin specific processing of doc_obj
469 return -1 unless defined ($self->process (\$text, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli));
470
471 # do any automatic metadata extraction
472 $self->auto_extract_metadata ($doc_obj);
473
474 # add an OID
475 # see if there is a plugin-specific set_OID function...
476 if (defined ($self->can(set_OID))) {
477 # it will need $doc_obj to set the Identifier metadata...
478 $self->set_OID($doc_obj);
479 } else {
480 # use the default set_OID() in doc.pm
481 $doc_obj->set_OID();
482 }
483
484 # process the document
485 $processor->process($doc_obj);
486
487 $self->{'num_processed'} ++;
488
489 return 1; # processed the file
490}
491
492# returns undef if file is rejected by the plugin
493sub process {
494 my $self = shift (@_);
495 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj) = @_;
496
497 &gsprintf(STDERR, "BasPlug::process {common.must_be_implemented}\n") && die "\n";
498 # die "Basplug::process function must be implemented in sub-class\n";
499
500 return undef; # never gets here
501}
502
503# uses the multiread package to read in the entire file pointed to
504# by filename and loads the resulting text into $$textref. Input text
505# may be in any of the encodings handled by multiread, output text
506# will be in utf8
507sub read_file {
508 my $self = shift (@_);
509 my ($filename, $encoding, $language, $textref) = @_;
510
511 if (!-r $filename)
512 {
513 my $outhandle = $self->{'outhandle'};
514 &gsprintf($outhandle, "{BasPlug.read_denied}\n", $filename) if $self->{'verbosity'};
515 # print $outhandle "Read permission denied for $filename\n" if $self->{'verbosity'};
516 return;
517 }
518
519 $$textref = "";
520
521 open (FILE, $filename) || (&gsprintf(STDERR, "BasPlug::read_file {BasPlug.could_not_open_for_reading} ($!)\n", $filename) && die "\n");
522 # open (FILE, $filename) || die "BasPlug::read_file could not open $filename for reading ($!)\n";
523
524 if ($encoding eq "ascii") {
525 undef $/;
526 $$textref = <FILE>;
527 $/ = "\n";
528 } else {
529 my $reader = new multiread();
530 $reader->set_handle ('BasPlug::FILE');
531 $reader->set_encoding ($encoding);
532 $reader->read_file ($textref);
533
534 #Now segments chinese if the separate_cjk option is set
535 if ($self->{'separate_cjk'}) {
536 # segment the Chinese words
537 $$textref = &cnseg::segment($$textref);
538 }
539 }
540
541 close FILE;
542}
543
544sub filename_based_title
545{
546 my $self = shift (@_);
547 my ($file) = @_;
548
549 my $file_derived_title = $file;
550 $file_derived_title =~ s/_/ /g;
551 $file_derived_title =~ s/\..*?$//;
552
553 return $file_derived_title;
554}
555
556
557sub title_fallback
558{
559 my $self = shift (@_);
560 my ($doc_obj,$section,$file) = @_;
561
562 if (!defined $doc_obj->get_metadata_element ($section, "Title")) {
563
564 my $file_derived_title = $self->filename_based_title($file);
565 $doc_obj->add_metadata ($section, "Title", $file_derived_title);
566 }
567}
568
569sub textcat_get_language_encoding {
570 my $self = shift (@_);
571 my ($filename) = @_;
572
573 my ($language, $encoding, $extracted_encoding);
574 if ($self->{'input_encoding'} eq "auto") {
575 # use textcat to automatically work out the input encoding and language
576 ($language, $encoding) = $self->get_language_encoding ($filename);
577 } elsif ($self->{'extract_language'}) {
578 # use textcat to get language metadata
579 ($language, $extracted_encoding) = $self->get_language_encoding ($filename);
580 $encoding = $self->{'input_encoding'};
581 # don't print this message for english... english in utf8 is identical
582 # to english in iso-8859-1 (except for some punctuation). We don't have
583 # a language model for en_utf8, so textcat always says iso-8859-1!
584 if ($extracted_encoding ne $encoding && $language ne "en"
585 && $self->{'verbosity'}) {
586 my $plugin_name = ref ($self);
587 my $outhandle = $self->{'outhandle'};
588 &gsprintf($outhandle, "$plugin_name: {BasPlug.wrong_encoding}\n", $filename, $encoding, $extracted_encoding);
589 # print $outhandle "$plugin_name: WARNING: $filename was read using $encoding encoding but ";
590 # print $outhandle "appears to be encoded as $extracted_encoding.\n";
591 }
592 } else {
593 $language = $self->{'default_language'};
594 $encoding = $self->{'input_encoding'};
595 }
596 return ($language, $encoding);
597}
598
599# Uses textcat to work out the encoding and language of the text in
600# $filename. All html tags are removed before processing.
601# returns an array containing "language" and "encoding"
602sub get_language_encoding {
603 my $self = shift (@_);
604 my ($filename) = @_;
605 my $outhandle = $self->{'outhandle'};
606
607 # read in file
608 open (FILE, $filename) || (&gsprintf(STDERR, "BasPlug::get_language_encoding {BasPlug.could_not_open_for_reading} ($!)\n", $filename) && die "\n"); # die "BasPlug::get_language_encoding could not open $filename for reading ($!)\n";
609 undef $/;
610 my $text = <FILE>;
611 $/ = "\n";
612 close FILE;
613
614 # remove <title>stuff</title> -- as titles tend often to be in English
615 # for foreign language documents
616 $text =~ s/<title>.*?<\/title>//i;
617
618 # remove all HTML tags
619 $text =~ s/<[^>]*>//sg;
620
621 # get the language/encoding
622 my $results = $self->{'textcat'}->classify(\$text);
623
624 # if textcat returns 3 or less possibilities we'll use the
625 # first one in the list - otherwise use the defaults
626 if (scalar @$results > 3) {
627 # changed 12 Feb 2003 by jrm21
628 # use the most popular encoding at least... otherwise we might
629 # generate invalid archive files!
630 my %guessed_encodings = ();
631 foreach my $result (@$results) {
632 $result =~ /([^\-]+)$/;
633 my $enc=$1;
634 if (!defined($guessed_encodings{$enc})) {
635 $guessed_encodings{$enc}=0;
636 }
637 $guessed_encodings{$enc}++;
638 }
639 my $best_encoding="";
640 $guessed_encodings{""}=-1;
641 foreach my $enc (keys %guessed_encodings) {
642 if ($guessed_encodings{$enc} > $guessed_encodings{$best_encoding}){
643 $best_encoding=$enc;
644 }
645 }
646
647 if ($self->{'input_encoding'} ne 'auto') {
648 if ($self->{'extract_language'} && $self->{'verbosity'}) {
649 &gsprintf($outhandle, "BasPlug: {BasPlug.could_not_extract_language}\n", $filename, $self->{'default_language'});
650 # print $outhandle "BasPlug: WARNING: language could not be extracted from $filename - ";
651 # print $outhandle "defaulting to $self->{'default_language'}\n";
652 }
653 return ($self->{'default_language'}, $self->{'input_encoding'});
654
655 } else {
656 if ($self->{'verbosity'}) {
657 &gsprintf($outhandle, "BasPlug: {BasPlug.could_not_extract_language}\n", $filename, $self->{'default_language'});
658 # print $outhandle "BASPlug: WARNING: language could not be extracted from $filename - ";
659 # print $outhandle "defaulting to $self->{'default_language'}.\n";
660 }
661 return ($self->{'default_language'}, $best_encoding);
662 }
663 }
664
665 # format language/encoding
666 my ($language, $encoding) = $results->[0] =~ /^([^-]*)(?:-(.*))?$/;
667 if (!defined $language) {
668 if ($self->{'verbosity'}) {
669 &gsprintf($outhandle, "BasPlug: {BasPlug.could_not_extract_language}\n", $filename, $self->{'default_language'});
670 # print $outhandle "BasPlug: WARNING: language could not be extracted from $filename - ";
671 # print $outhandle "defaulting to $self->{'default_language'}\n";
672 }
673 $language = $self->{'default_language'};
674 }
675 if (!defined $encoding) {
676 if ($self->{'verbosity'}) {
677 &gsprintf($outhandle, "BasPlug: {BasPlug.could_not_extract_encoding}\n", $filename, $self->{'default_encoding'});
678 # print $outhandle "BasPlug: WARNING: encoding could not be extracted from $filename - ";
679 # print $outhandle "defaulting to $self->{'default_encoding'}\n";
680 }
681 $encoding = $self->{'default_encoding'};
682 }
683
684
685 # check for equivalents where textcat doesn't have some encodings...
686 # eg MS versions of standard encodings
687 if ($encoding =~ /^iso_8859_(\d+)/) {
688 my $iso = $1; # which variant of the iso standard?
689 # iso-8859 sets don't use chars 0x80-0x9f, windows codepages do
690 if ($text =~ /[\x80-\x9f]/) {
691 # Western Europe
692 if ($iso == 1 or $iso == 15) { $encoding = 'windows_1252' }
693 elsif ($iso == 2) { $encoding = 'windows_1250' } # Central Europe
694 elsif ($iso == 5) { $encoding = 'windows_1251' } # Cyrillic
695 elsif ($iso == 6) { $encoding = 'windows_1256' } # Arabic
696 elsif ($iso == 7) { $encoding = 'windows_1253' } # Greek
697 elsif ($iso == 8) { $encoding = 'windows_1255' } # Hebrew
698 elsif ($iso == 9) { $encoding = 'windows_1254' } # Turkish
699 }
700 }
701
702 if ($encoding !~ /^(ascii|utf8|unicode)$/ &&
703 !defined $encodings::encodings->{$encoding}) {
704 if ($self->{'verbosity'}) {
705 gsprintf($outhandle, "BasPlug: {BasPlug.unsupported_encoding}\n",
706 $filename, $encoding, $self->{'default_encoding'});
707 }
708 $encoding = $self->{'default_encoding'};
709 }
710
711 return ($language, $encoding);
712}
713
714# add any extra metadata that's been passed around from one
715# plugin to another.
716# extra_metadata uses add_utf8_metadata so it expects metadata values
717# to already be in utf8
718sub extra_metadata {
719 my $self = shift (@_);
720 my ($doc_obj, $cursection, $metadata) = @_;
721
722 foreach my $field (keys(%$metadata)) {
723 # $metadata->{$field} may be an array reference
724 if (ref ($metadata->{$field}) eq "ARRAY") {
725 map {
726 $doc_obj->add_utf8_metadata ($cursection, $field, $_);
727 } @{$metadata->{$field}};
728 } else {
729 $doc_obj->add_utf8_metadata ($cursection, $field, $metadata->{$field});
730 }
731 }
732}
733
734# initialise metadata extractors
735sub initialise_extractors {
736 my $self = shift (@_);
737
738 if ($self->{'extract_acronyms'} || $self->{'markup_acronyms'}) {
739 &acronym::initialise_acronyms();
740 }
741}
742
743# finalise metadata extractors
744sub finalise_extractors {
745 my $self = shift (@_);
746
747 if ($self->{'extract_acronyms'} || $self->{'markup_acronyms'}) {
748 &acronym::finalise_acronyms();
749 }
750}
751
752# FIRSTNNN: extract the first NNN characters as metadata
753sub extract_first_NNNN_characters {
754 my $self = shift (@_);
755 my ($textref, $doc_obj, $thissection) = @_;
756
757 foreach my $size (split /,/, $self->{'first'}) {
758 my $tmptext = $$textref;
759 $tmptext =~ s/^\s+//;
760 $tmptext =~ s/\s+$//;
761 $tmptext =~ s/\s+/ /gs;
762 $tmptext = substr ($tmptext, 0, $size);
763 $tmptext =~ s/\s\S*$/&#8230;/;
764 $doc_obj->add_utf8_metadata ($thissection, "First$size", $tmptext);
765 }
766}
767
768sub extract_email {
769 my $self = shift (@_);
770 my ($textref, $doc_obj, $thissection) = @_;
771 my $outhandle = $self->{'outhandle'};
772
773 # print $outhandle " extracting email addresses ...\n"
774 &gsprintf($outhandle, " {BasPlug.extracting_emails}...\n")
775 if ($self->{'verbosity'} > 2);
776
777 my @email = ($$textref =~ m/([-a-z0-9\.@+_=]+@(?:[-a-z0-9]+\.)+(?:com|org|edu|mil|int|net|[a-z][a-z]))/g);
778 @email = sort @email;
779
780 my @email2 = ();
781 foreach my $address (@email) {
782 if (!(join(" ",@email2) =~ m/$address/ )) {
783 push @email2, $address;
784 $doc_obj->add_utf8_metadata ($thissection, "emailAddress", $address);
785 # print $outhandle " extracting $address\n"
786 &gsprintf($outhandle, " {BasPlug.extracting} $address\n")
787 if ($self->{'verbosity'} > 3);
788 }
789 }
790 # print $outhandle " done extracting email addresses.\n"
791 &gsprintf($outhandle, " {BasPlug.done_email_extract}\n")
792 if ($self->{'verbosity'} > 2);
793}
794
795# extract metadata
796sub auto_extract_metadata {
797
798 my $self = shift (@_);
799 my ($doc_obj) = @_;
800
801 if ($self->{'extract_email'}) {
802 my $thissection = $doc_obj->get_top_section();
803 while (defined $thissection) {
804 my $text = $doc_obj->get_text($thissection);
805 $self->extract_email (\$text, $doc_obj, $thissection) if $text =~ /./;
806 $thissection = $doc_obj->get_next_section ($thissection);
807 }
808 }
809
810
811#adding kea keyphrases
812 if ($self->{'kea'}) {
813
814 my $thissection = $doc_obj->get_top_section();
815 my $text = "";
816 my @list;
817
818 while (defined $thissection) { #loop through sections to gather whole doc
819 my $sectiontext = $doc_obj->get_text($thissection);
820 $text = $text.$sectiontext;
821 $thissection = $doc_obj->get_next_section ($thissection);
822 }
823
824 if($self->{'kea_options'}) { #if kea options flag is set, call Kea with specified options
825 @list = &Kea::extract_KeyPhrases ($text, $self->{'kea_options'});
826 } else { #otherwise call Kea with no options
827 @list = &Kea::extract_KeyPhrases ($text);
828 }
829
830 if(@list){ #if a list of kea keyphrases was returned (ie not empty)
831 my $keyphrases = $list[0]; #first arg is keyphrase list
832 my $stems = $list[1]; #second arg is stemmed keyphrase list
833 &gsprintf(STDERR, "{BasPlug.keyphrases}: $keyphrases\n");
834 # print STDERR "keyphrases: $keyphrases\n";
835 &gsprintf(STDERR, "{BasPlug.stems}: $stems\n");
836 # print STDERR "stems: $stems\n";
837 $thissection = $doc_obj->get_top_section(); #add metadata to top section
838 # add all key phrases as one metadata
839 $doc_obj->add_metadata($thissection, "Keyphrases", $keyphrases);
840 # add individual key phrases as multiple metadata
841 foreach my $keyphrase (split(',', $keyphrases)) {
842 $keyphrase =~ s/^\s*//; $keyphrase =~ s/\s*$//;
843 $doc_obj->add_metadata($thissection, "Keyphrase", $keyphrase);
844 }
845 $doc_obj->add_metadata($thissection, "stems", $stems);
846 }
847 } #end of kea
848
849 if ($self->{'first'}) {
850 my $thissection = $doc_obj->get_top_section();
851 while (defined $thissection) {
852 my $text = $doc_obj->get_text($thissection);
853 $self->extract_first_NNNN_characters (\$text, $doc_obj, $thissection) if $text =~ /./;
854 $thissection = $doc_obj->get_next_section ($thissection);
855 }
856 }
857
858 if ($self->{'extract_acronyms'}) {
859 my $thissection = $doc_obj->get_top_section();
860 while (defined $thissection) {
861 my $text = $doc_obj->get_text($thissection);
862 $self->extract_acronyms (\$text, $doc_obj, $thissection) if $text =~ /./;
863 $thissection = $doc_obj->get_next_section ($thissection);
864 }
865 }
866
867 if ($self->{'markup_acronyms'}) {
868 my $thissection = $doc_obj->get_top_section();
869 while (defined $thissection) {
870 my $text = $doc_obj->get_text($thissection);
871 $text = $self->markup_acronyms ($text, $doc_obj, $thissection);
872 $doc_obj->delete_text($thissection);
873 $doc_obj->add_text($thissection, $text);
874 $thissection = $doc_obj->get_next_section ($thissection);
875 }
876 }
877
878 if($self->{'date_extract'}) {
879 my $thissection = $doc_obj->get_top_section();
880 while (defined $thissection) {
881
882 my $text = $doc_obj->get_text($thissection);
883 &DateExtract::get_date_metadata($text, $doc_obj,
884 $thissection,
885 $self->{'no_biblio'},
886 $self->{'max_year'},
887 $self->{'max_century'});
888 $thissection = $doc_obj->get_next_section ($thissection);
889 }
890 }
891}
892
893# extract acronyms from a section in a document. progress is
894# reported to outhandle based on the verbosity. both the Acronym
895# and the AcronymKWIC metadata items are created.
896
897sub extract_acronyms {
898 my $self = shift (@_);
899 my ($textref, $doc_obj, $thissection) = @_;
900 my $outhandle = $self->{'outhandle'};
901
902 # print $outhandle " extracting acronyms ...\n"
903 &gsprintf($outhandle, " {BasPlug.extracting_acronyms}...\n")
904 if ($self->{'verbosity'} > 2);
905
906 my $acro_array = &acronym::acronyms($textref);
907
908 foreach my $acro (@$acro_array) {
909
910 #check that this is the first time ...
911 my $seen_before = "false";
912 my $previous_data = $doc_obj->get_metadata($thissection, "Acronym");
913 foreach my $thisAcro (@$previous_data) {
914 if ($thisAcro eq $acro->to_string()) {
915 $seen_before = "true";
916 # print $outhandle " already seen ". $acro->to_string() . "\n"
917 &gsprintf($outhandle, " {BasPlug.already_seen} " . $acro->to_string() . "\n")
918 if ($self->{'verbosity'} >= 4);
919 }
920 }
921
922 if ($seen_before eq "false") {
923 #write it to the file ...
924 $acro->write_to_file();
925
926 #do the normal acronym
927 $doc_obj->add_utf8_metadata($thissection, "Acronym", $acro->to_string());
928 # print $outhandle " adding ". $acro->to_string() . "\n"
929 &gsprintf($outhandle, " {BasPlug.adding} " . $acro->to_string() . "\n")
930 if ($self->{'verbosity'} > 3);
931 }
932 }
933
934 # print $outhandle " done extracting acronyms. \n"
935 &gsprintf($outhandle, " {BasPlug.done_acronym_extract}\n")
936 if ($self->{'verbosity'} > 2);
937}
938
939sub markup_acronyms {
940 my $self = shift (@_);
941 my ($text, $doc_obj, $thissection) = @_;
942 my $outhandle = $self->{'outhandle'};
943
944 # print $outhandle " marking up acronyms ...\n"
945 &gsprintf($outhandle, " {BasPlug.marking_up_acronyms}...\n")
946 if ($self->{'verbosity'} > 2);
947
948 #self is passed in to check for verbosity ...
949 $text = &acronym::markup_acronyms($text, $self);
950
951 # print $outhandle " done marking up acronyms. \n"
952 &gsprintf($outhandle, " {BasPlug.done_acronym_markup}\n")
953 if ($self->{'verbosity'} > 2);
954
955 return $text;
956}
957
958sub compile_stats {
959 my $self = shift(@_);
960 my ($stats) = @_;
961
962 $stats->{'num_processed'} += $self->{'num_processed'};
963 $stats->{'num_not_processed'} += $self->{'num_not_processed'};
964 $stats->{'num_archives'} += $self->{'num_archives'};
965
966}
967
968sub associate_cover_image {
969 my $self = shift(@_);
970 my ($doc_obj, $filename) = @_;
971
972 $filename =~ s/\.[^\\\/\.]+$/\.jpg/;
973 if (-e $filename) {
974 $doc_obj->associate_file($filename, "cover.jpg", "image/jpeg");
975 } else {
976 $filename =~ s/jpg$/JPG/;
977 if (-e $filename) {
978 $doc_obj->associate_file($filename, "cover.jpg", "image/jpeg");
979 }
980 }
981}
982
9831;
Note: See TracBrowser for help on using the repository browser.