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

Last change on this file since 9962 was 9961, checked in by davidb, 19 years ago

Minor refinement made to print statements (warnings) generated by BasPlug.

  • Property svn:keywords set to Author Date Id Revision
File size: 39.1 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-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 BasPlug;
27
28BEGIN {
29 die "GSDLHOME not set\n" unless defined $ENV{'GSDLHOME'};
30}
31
32eval {require bytes};
33
34# suppress the annoying "subroutine redefined" warning that various
35# plugins cause under perl 5.6
36$SIG{__WARN__} = sub {warn($_[0]) unless ($_[0] =~ /Subroutine\s+\S+\sredefined/)};
37
38use strict; no strict 'subs';
39
40use File::Basename;
41
42use Kea;
43use parsargv;
44use multiread;
45use encodings;
46use cnseg;
47use acronym;
48use textcat;
49use doc;
50eval "require diagnostics"; # some perl distros (eg mac) don't have this
51use DateExtract;
52use ghtml;
53use gsprintf 'gsprintf';
54use printusage;
55
56use GISBasPlug;
57
58@BasPlug::ISA = ( GISBasPlug );
59
60my $unicode_list =
61 [ { 'name' => "auto",
62 'desc' => "{BasPlug.input_encoding.auto}" },
63 { 'name' => "ascii",
64 'desc' => "{BasPlug.input_encoding.ascii}" },
65 { 'name' => "utf8",
66 'desc' => "{BasPlug.input_encoding.utf8}" },
67 { 'name' => "unicode",
68 'desc' => "{BasPlug.input_encoding.unicode}" } ];
69
70my $arguments =
71 [ { 'name' => "process_exp",
72 'desc' => "{BasPlug.process_exp}",
73 'type' => "regexp",
74 'deft' => "",
75 'reqd' => "no" },
76 { 'name' => "block_exp",
77 'desc' => "{BasPlug.block_exp}",
78 'type' => "regexp",
79 'deft' => "",
80 'reqd' => "no" },
81 { 'name' => "smart_block",
82 'desc' => "{BasPlug.smart_block}",
83 'type' => "flag",
84 'reqd' => "no" },
85 { 'name' => "associate_ext",
86 'desc' => "{BasPlug.associate_ext}",
87 'type' => "string",
88 'reqd' => "no" },
89 { 'name' => "input_encoding",
90 'desc' => "{BasPlug.input_encoding}",
91 'type' => "enum",
92 'list' => $unicode_list,
93 'reqd' => "no" ,
94 'deft' => "auto" } ,
95 { 'name' => "default_encoding",
96 'desc' => "{BasPlug.default_encoding}",
97 'type' => "enum",
98 'list' => $unicode_list,
99 'reqd' => "no",
100 'deft' => "utf8" },
101 { 'name' => "extract_language",
102 'desc' => "{BasPlug.extract_language}",
103 'type' => "flag",
104 'reqd' => "no" },
105 { 'name' => "default_language",
106 'desc' => "{BasPlug.default_language}",
107 'type' => "language",
108 'deft' => "en",
109 'reqd' => "no" },
110 { 'name' => "extract_acronyms",
111 'desc' => "{BasPlug.extract_acronyms}",
112 'type' => "flag",
113 'reqd' => "no" },
114 { 'name' => "markup_acronyms",
115 'desc' => "{BasPlug.markup_acronyms}",
116 'type' => "flag",
117 'reqd' => "no" },
118 { 'name' => "extract_keyphrases",
119 'desc' => "{BasPlug.extract_keyphrases}",
120 'type' => "flag",
121 'reqd' => "no" },
122 { 'name' => "extract_keyphrase_options",
123 'desc' => "{BasPlug.extract_keyphrase_options}",
124 'type' => "string",
125 'deft' => "",
126 'reqd' => "no" },
127 { 'name' => "first",
128 'desc' => "{BasPlug.first}",
129 'type' => "string",
130 'reqd' => "no" },
131 { 'name' => "extract_email",
132 'desc' => "{BasPlug.extract_email}",
133 'type' => "flag",
134 'reqd' => "no" },
135 { 'name' => "extract_historical_years",
136 'desc' => "{BasPlug.extract_historical_years}",
137 'type' => "flag",
138 'reqd' => "no" },
139 { 'name' => "maximum_year",
140 'desc' => "{BasPlug.maximum_year}",
141 'type' => "int",
142 'deft' => (localtime)[5]+1900,
143 'reqd' => "no"},
144 { 'name' => "maximum_century",
145 'desc' => "{BasPlug.maximum_century}",
146 'type' => "string",
147 'deft' => "",
148 'reqd' => "no" },
149 { 'name' => "no_bibliography",
150 'desc' => "{BasPlug.no_bibliography}",
151 'type' => "flag",
152 'reqd' => "no"},
153 { 'name' => "no_cover_image",
154 'desc' => "{BasPlug.no_cover_image}",
155 'type' => "flag",
156 'reqd' => "no" } ];
157
158my $gis_arguments =
159 [ { 'name' => "extract_placenames",
160 'desc' => "{GISBasPlug.extract_placenames}",
161 'type' => "flag",
162 'reqd' => "no" },
163 { 'name' => "gazetteer",
164 'desc' => "{GISBasPlug.gazetteer}",
165 'type' => "string",
166 'reqd' => "no" },
167 { 'name' => "place_list",
168 'desc' => "{GISBasPlug.place_list}",
169 'type' => "flag",
170 'reqd' => "no" } ];
171
172
173my $options = { 'name' => "BasPlug",
174 'desc' => "{BasPlug.desc}",
175 'abstract' => "yes",
176 'inherits' => "no",
177 'args' => $arguments };
178
179
180
181
182sub get_arguments
183{
184 my $self = shift(@_);
185 my $optionlistref = $self->{'option_list'};
186 my @optionlist = @$optionlistref;
187 my $pluginoptions = pop(@$optionlistref);
188 my $pluginarguments = $pluginoptions->{'args'};
189 return $pluginarguments;
190}
191
192
193sub print_xml_usage
194{
195 my $self = shift(@_);
196
197 # XML output is always in UTF-8
198 gsprintf::output_strings_in_UTF8;
199
200 PrintUsage::print_xml_header();
201 $self->print_xml();
202}
203
204
205sub print_xml
206{
207 my $self = shift(@_);
208
209 my $optionlistref = $self->{'option_list'};
210 my @optionlist = @$optionlistref;
211 my $pluginoptions = pop(@$optionlistref);
212 return if (!defined($pluginoptions));
213
214 gsprintf(STDERR, "<PlugInfo>\n");
215 gsprintf(STDERR, " <Name>$pluginoptions->{'name'}</Name>\n");
216 my $desc = gsprintf::lookup_string($pluginoptions->{'desc'});
217 $desc =~ s/</&amp;lt;/g; # doubly escaped
218 $desc =~ s/>/&amp;gt;/g;
219
220 gsprintf(STDERR, " <Desc>$desc</Desc>\n");
221 gsprintf(STDERR, " <Abstract>$pluginoptions->{'abstract'}</Abstract>\n");
222 gsprintf(STDERR, " <Inherits>$pluginoptions->{'inherits'}</Inherits>\n");
223 gsprintf(STDERR, " <Explodes>" . ($pluginoptions->{'explodes'} || "no") . "</Explodes>\n");
224 gsprintf(STDERR, " <Arguments>\n");
225 if (defined($pluginoptions->{'args'})) {
226 &PrintUsage::print_options_xml($pluginoptions->{'args'});
227 }
228
229 # Recurse up the plugin hierarchy
230 $self->print_xml();
231
232 gsprintf(STDERR, " </Arguments>\n");
233 gsprintf(STDERR, "</PlugInfo>\n");
234}
235
236
237sub print_txt_usage
238{
239 my $self = shift(@_);
240
241 # Print the usage message for a plugin (recursively)
242 my $descoffset = $self->determine_description_offset(0);
243 $self->print_plugin_usage($descoffset, 1);
244}
245
246
247sub determine_description_offset
248{
249 my $self = shift(@_);
250 my $maxoffset = shift(@_);
251
252 my $optionlistref = $self->{'option_list'};
253 my @optionlist = @$optionlistref;
254 my $pluginoptions = pop(@$optionlistref);
255 return $maxoffset if (!defined($pluginoptions));
256
257 # Find the length of the longest option string of this plugin
258 my $pluginargs = $pluginoptions->{'args'};
259 if (defined($pluginargs)) {
260 my $longest = &PrintUsage::find_longest_option_string($pluginargs);
261 if ($longest > $maxoffset) {
262 $maxoffset = $longest;
263 }
264 }
265
266 # Recurse up the plugin hierarchy
267 $maxoffset = $self->determine_description_offset($maxoffset);
268 $self->{'option_list'} = \@optionlist;
269 return $maxoffset;
270}
271
272
273sub print_plugin_usage
274{
275 my $self = shift(@_);
276 my $descoffset = shift(@_);
277 my $isleafclass = shift(@_);
278
279 my $optionlistref = $self->{'option_list'};
280 my @optionlist = @$optionlistref;
281 my $pluginoptions = pop(@$optionlistref);
282 return if (!defined($pluginoptions));
283
284 my $pluginname = $pluginoptions->{'name'};
285 my $pluginargs = $pluginoptions->{'args'};
286 my $plugindesc = $pluginoptions->{'desc'};
287
288 # Produce the usage information using the data structure above
289 if ($isleafclass) {
290 if (defined($plugindesc)) {
291 gsprintf(STDERR, "$plugindesc\n\n");
292 }
293 gsprintf(STDERR, " {common.usage}: plugin $pluginname [{common.options}]\n\n");
294 }
295
296 # Display the plugin options, if there are some
297 if (defined($pluginargs)) {
298 # Calculate the column offset of the option descriptions
299 my $optiondescoffset = $descoffset + 2; # 2 spaces between options & descriptions
300
301 if ($isleafclass) {
302 gsprintf(STDERR, " {common.specific_options}:\n");
303 }
304 else {
305 gsprintf(STDERR, " {common.general_options}:\n", $pluginname);
306 }
307
308 # Display the plugin options
309 &PrintUsage::print_options_txt($pluginargs, $optiondescoffset);
310 }
311
312 # Recurse up the plugin hierarchy
313 $self->print_plugin_usage($descoffset, 0);
314 $self->{'option_list'} = \@optionlist;
315}
316
317
318sub new {
319 my $class = shift (@_);
320 my $plugin_name = shift (@_);
321 my $self = {};
322 $self->{'plugin_type'} = "BasPlug";
323
324 if (GISBasPlug::has_mapdata()) {
325 push(@$arguments,@$gis_arguments);
326 }
327
328 my $enc = "^(";
329 map {$enc .= "$_|";} keys %$encodings::encodings;
330 my $denc = $enc . "ascii|utf8|unicode)\$";
331 $enc .= "ascii|utf8|unicode|auto)\$";
332
333 $self->{'outhandle'} = STDERR;
334 my $year = (localtime)[5]+1900;
335
336 $self->{'textcat'} = new textcat();
337
338 $self->{'num_processed'} = 0;
339 $self->{'num_not_processed'} = 0;
340 $self->{'num_blocked'} = 0;
341 $self->{'num_archives'} = 0;
342 $self->{'cover_image'} = 1; # cover image is on by default
343
344 # 14-05-02 To allow for proper inheritance of arguments - John Thompson
345 $self->{'option_list'} = [ $options ];
346
347 my $no_cover_image = 0;
348 # general options available to all plugins
349 if (!parsargv::parse(\@_,
350 q^process_exp/.*/^, \$self->{'process_exp'},
351 q^block_exp/.*/^, \$self->{'block_exp'},
352 q^associate_ext/.*/^, \$self->{'associate_ext'},
353 q^extract_language^, \$self->{'extract_language'},
354 q^extract_acronyms^, \$self->{'extract_acronyms'},
355 q^extract_keyphrases^, \$self->{'kea'}, #with extra options (UNDOCUMENTED)
356 q^extract_keyphrase_options/.*/^, \$self->{'kea_options'}, #no extra options (UNDOCUMENTED)
357 qq^input_encoding/$enc/auto^, \$self->{'input_encoding'},
358 qq^default_encoding/$denc/utf8^, \$self->{'default_encoding'},
359 q^extract_email^, \$self->{'extract_email'},
360 q^extract_placenames^, \$self->{'extract_placenames'},
361 q^gazetteer/.*/^, \$self->{'gazetteer'},
362 q^place_list^, \$self->{'place_list'},
363 q^markup_acronyms^, \$self->{'markup_acronyms'},
364 q^default_language/.{2}/en^, \$self->{'default_language'},
365 q^first/.*/^, \$self->{'first'},
366 q^extract_historical_years^, \$self->{'date_extract'},
367 qq^maximum_year/\\d{4}/$year^, \$self->{'max_year'},
368 q^no_bibliography^, \$self->{'no_biblio'},
369 qq^maximum_century/-?\\d{1,2}( ?B\\.C\\.E\\.)?/-1^, \$self->{'max_century'},
370 q^no_cover_image^, \$no_cover_image,
371 q^separate_cjk^, \$self->{'separate_cjk'},
372 q^smart_block^, \$self->{'smart_block'},
373 q^smart_block_BN^, \$self->{'smart_block_BN'},
374 "allow_extra_options")) {
375
376 gsprintf(STDERR, "\n{BasPlug.bad_general_option}\n", $plugin_name);
377 bless $self, $class;
378 $self->print_txt_usage(""); # Use default resource bundle
379 die "\n";
380 }
381
382 my $associate_ext = $self->{'associate_ext'};
383 if ((defined $associate_ext) && ($associate_ext ne "")) {
384 my @exts = split(/,/,$associate_ext);
385
386 my %associate_ext_lookup = ();
387 foreach my $e (@exts) {
388 $associate_ext_lookup{$e} = 1;
389 }
390
391 $self->{'associate_ext_lookup'} = \%associate_ext_lookup;
392 }
393
394 $self->{'shared_fileroot'} = {};
395 $self->{'file_blocks'} = {};
396
397 $self->{'cover_image'} = 0 if ($no_cover_image);
398
399 if ($self->{'extract_placenames'}) {
400
401 my $outhandle = $self->{'outhandle'};
402
403 my $places_ref
404 = GISBasPlug::loadGISDatabase($outhandle,$self->{'gazetteer'});
405
406 if (!defined $places_ref) {
407 print $outhandle "Warning: Error loading mapdata gazetteer \"$self->{'gazetteer'}\"\n";
408 print $outhandle " No placename extraction will take place.\n";
409 $self->{'extract_placenames'} = undef;
410 }
411 else {
412 $self->{'places'} = $places_ref;
413 }
414 }
415 return bless $self, $class;
416}
417
418# initialize BasPlug options
419# if init() is overridden in a sub-class, remember to call BasPlug::init()
420sub init {
421 my $self = shift (@_);
422 my ($verbosity, $outhandle, $failhandle) = @_;
423
424 # verbosity is passed through from the processor
425 $self->{'verbosity'} = $verbosity;
426
427 # as are the outhandle and failhandle
428 $self->{'outhandle'} = $outhandle if defined $outhandle;
429 $self->{'failhandle'} = $failhandle;
430
431 # set process_exp and block_exp to defaults unless they were
432 # explicitly set
433
434 if ((!$self->is_recursive()) and
435 (!defined $self->{'process_exp'}) || ($self->{'process_exp'} eq "")) {
436
437 $self->{'process_exp'} = $self->get_default_process_exp ();
438 if ($self->{'process_exp'} eq "") {
439 warn ref($self) . " Warning: Non-recursive plugin has no process_exp\n";
440 }
441 }
442
443 if ((!defined $self->{'block_exp'}) || ($self->{'block_exp'} eq "")) {
444 $self->{'block_exp'} = $self->get_default_block_exp ();
445 }
446}
447
448sub begin {
449 my $self = shift (@_);
450 my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;
451 $self->initialise_extractors();
452}
453
454sub end {
455 my ($self) = @_;
456 $self->finalise_extractors();
457}
458
459# this function should be overridden to return 1
460# in recursive plugins
461sub is_recursive {
462 my $self = shift (@_);
463
464 return 0;
465}
466
467sub get_default_block_exp {
468 my $self = shift (@_);
469
470 return "";
471}
472
473sub get_default_process_exp {
474 my $self = shift (@_);
475
476 return "";
477}
478
479# default implementation is to do nothing.
480sub store_block_files
481{
482 my $self =shift (@_);
483 my ($filename) = @_;
484 return;
485}
486
487#default implementation is to block a file with same name as this, but extension jpg or JPG, if cover_images is on.
488sub block_cover_image
489{
490 my $self =shift (@_);
491 my ($filename) = @_;
492 if ($self->{'cover_image'}) {
493 my $coverfile = $filename;
494 $coverfile =~ s/\.[^\\\/\.]+$/\.jpg/;
495 if (!-e $coverfile) {
496 $coverfile =~ s/jpg$/JPG/;
497 }
498 if (-e $coverfile) {
499 $self->{'file_blocks'}->{$coverfile} = 1;
500 }
501 }
502
503 return;
504}
505
506sub metadata_read {
507 my $self = shift (@_);
508 my ($pluginfo, $base_dir, $file, $metadata, $extrametakeys, $extrametadata, $processor, $maxdocs, $gli) = @_;
509 # Keep track of filenames with same root but different extensions
510 # Used to support -associate_ext
511
512 my $associate_ext = $self->{'associate_ext'};
513 if ((defined $associate_ext) && ($associate_ext ne "")) {
514
515 my ($file_prefix,$file_ext) = ($file =~ m/^(.*)\.(.*?)$/);
516 if ((defined $file_prefix) && (defined $file_ext)) {
517
518 my $shared_fileroot = $self->{'shared_fileroot'};
519 if (!defined $shared_fileroot->{$file_prefix}) {
520 my $file_prefix_rec = { 'tie_to' => undef, 'exts' => {} };
521 $shared_fileroot->{$file_prefix} = $file_prefix_rec;
522 }
523
524 my $file_prefix_rec = $shared_fileroot->{$file_prefix};
525
526 my $process_exp = $self->{'process_exp'};
527
528 if ($file =~ m/$self->{'process_exp'}/) {
529 # This is the document the others should be tied to
530 $file_prefix_rec->{'tie_to'} = $file_ext;
531 }
532 else {
533 if (defined $self->{'associate_ext_lookup'}->{$file_ext}) {
534 $file_prefix_rec->{'exts'}->{$file_ext} = 1;
535 }
536 }
537 }
538 }
539
540 # now check whether we are actually processing this
541 my $filename = $file;
542 $filename = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\w/;
543 if ($self->{'process_exp'} eq "" || $filename !~ /$self->{'process_exp'}/ || !-f $filename) {
544 return undef; # can't recognise
545 }
546
547 # do smart blocking if appropriate
548 if (defined $self->{'smart_block'}) {
549 $self->block_cover_image($filename);
550 $self->store_block_files($filename);
551 }
552
553 return 1;
554}
555
556sub tie_to_filename
557{
558 my $self = shift (@_);
559
560 my ($file_ext,$file_prefix_rec) = @_;
561
562 if (defined $file_prefix_rec) {
563 my $tie_to = $file_prefix_rec->{'tie_to'};
564
565 if (defined $tie_to) {
566 if ($tie_to eq $file_ext) {
567 return 1;
568 }
569 }
570 }
571
572 return 0;
573}
574
575sub tie_to_assoc_file
576{
577 my $self = shift (@_);
578 my ($file_ext,$file_prefix_rec) = @_;
579
580 if (defined $file_prefix_rec) {
581 my $tie_to = $file_prefix_rec->{'tie_to'};
582 if (defined $tie_to) {
583
584 my $exts = $file_prefix_rec->{'exts'};
585
586 my $has_file_ext = $exts->{$file_ext};
587
588 if ($has_file_ext) {
589 return 1;
590 }
591 }
592 }
593
594 return 0;
595}
596
597
598sub associate_with
599{
600 my $self = shift (@_);
601 my ($file, $filename, $metadata) = @_;
602
603 my $associate_ext = $self->{'associate_ext'};
604
605
606 return 0 if (!$associate_ext);
607
608 # If file, see if matches with "tie_to" doc or is one of the
609 # associated filename extensions.
610
611 my ($file_prefix,$file_ext) = ($file =~ m/^(.*)\.(.*?)$/);
612 if ((defined $file_prefix) && (defined $file_ext)) {
613
614 my $file_prefix_rec = $self->{'shared_fileroot'}->{$file_prefix};
615
616 if ($self->tie_to_filename($file_ext,$file_prefix_rec)) {
617
618 # Set up gsdlassocfile_tobe
619
620 my $exts = $file_prefix_rec->{'exts'};
621
622 if (!defined $metadata->{'gsdlassocfile_tobe'}) {
623 $metadata->{'gsdlassocfile_tobe'} = [];
624 }
625
626 my $assoc_tobe = $metadata->{'gsdlassocfile_tobe'};
627
628 my ($full_prefix) = ($filename =~ m/^(.*)\..*?$/);
629 foreach my $e (keys %$exts) {
630 my $assoc_file = "$full_prefix.$e";
631 my $mime_type = ""; # let system auto detect this
632 push(@$assoc_tobe,"$assoc_file:$mime_type:");
633 }
634 }
635 elsif ($self->tie_to_assoc_file($file_ext,$file_prefix_rec)) {
636 # a form of smart block
637
638 return 1;
639 }
640 }
641
642 return 0;
643}
644
645
646# The BasPlug read() function. This function does all the right things
647# to make general options work for a given plugin. It calls the process()
648# function which does all the work specific to a plugin (like the old
649# read functions used to do). Most plugins should define their own
650# process() function and let this read() function keep control.
651#
652# recursive plugins (e.g. RecPlug) and specialized plugins like those
653# capable of processing many documents within a single file (e.g.
654# GMLPlug) should normally implement their own version of read()
655#
656# Return number of files processed, undef if can't recognise, -1 if can't
657# process
658# Note that $base_dir might be "" and that $file might
659# include directories
660
661sub read {
662 my $self = shift (@_);
663
664 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
665
666 if ($self->is_recursive()) {
667 gsprintf(STDERR, "{BasPlug.read_must_be_implemented}") && die "\n";
668 }
669
670 my $outhandle = $self->{'outhandle'};
671 my $smart_block = $self->{'smart_block'};
672 my $smart_block_BN = $self->{'smart_block_BN'};
673
674 my $filename = $file;
675 $filename = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\w/;
676
677 if ($self->associate_with($file,$filename,$metadata)) {
678 # a form of smart block
679 $self->{'num_blocked'} ++;
680 return 0; # blocked
681 }
682
683 if ($smart_block || $smart_block_BN) {
684
685 if (defined $self->{'file_blocks'}->{$filename} && $self->{'file_blocks'}->{$filename} == 1){
686 $self->{'num_blocked'} ++;
687 return 0; # blocked
688 }
689 } elsif ($self->{'block_exp'} ne "" && $filename =~ /$self->{'block_exp'}/) {
690 $self->{'num_blocked'} ++;
691 return 0; # blocked
692 }
693
694 if ($filename !~ /$self->{'process_exp'}/ || !-f $filename) {
695 return undef; # can't recognise
696 }
697 $file =~ s/^[\/\\]+//; # $file often begins with / so we'll tidy it up
698
699 # Do encoding stuff
700 my ($language, $encoding) = $self->textcat_get_language_encoding ($filename);
701
702 # create a new document
703 my $doc_obj = new doc ($filename, "indexed_doc");
704 $doc_obj->set_OIDtype ($processor->{'OIDtype'});
705 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Language", $language);
706 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Encoding", $encoding);
707 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
708 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "FileSize", (-s $filename));
709
710 my ($filemeta) = $file =~ /([^\\\/]+)$/;
711 # how do we know what encoding the filename is in?
712 $doc_obj->add_metadata($doc_obj->get_top_section(), "Source", &ghtml::dmsafe($filemeta));
713 if ($self->{'cover_image'}) {
714 $self->associate_cover_image($doc_obj, $filename);
715 }
716
717 # read in file ($text will be in utf8)
718 my $text = "";
719 $self->read_file ($filename, $encoding, $language, \$text);
720
721 if (!length ($text)) {
722 my $plugin_name = ref ($self);
723 if ($gli) {
724 print STDERR "<ProcessingError n='$file' r='File contains no text'>\n";
725 }
726 gsprintf($outhandle, "$plugin_name: {BasPlug.file_has_no_text}\n", $filename) if $self->{'verbosity'};
727
728 my $failhandle = $self->{'failhandle'};
729 gsprintf($failhandle, "$file: " . ref($self) . ": {BasPlug.empty_file}\n");
730 # print $failhandle "$file: " . ref($self) . ": file contains no text\n";
731 $self->{'num_not_processed'} ++;
732
733 return 0; # what should we return here?? error but don't want to pass it on
734 }
735
736 # include any metadata passed in from previous plugins
737 # note that this metadata is associated with the top level section
738
739 $self->extra_metadata ($doc_obj, $doc_obj->get_top_section(), $metadata);
740
741 # do plugin specific processing of doc_obj
742 unless (defined ($self->process (\$text, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli))) {
743 $text = '';
744 undef $text;
745 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
746 return -1;
747 }
748 $text='';
749 undef $text;
750
751 # do any automatic metadata extraction
752 $self->auto_extract_metadata ($doc_obj);
753
754 # add an OID
755 # see if there is a plugin-specific set_OID function...
756 if (defined ($self->can('set_OID'))) {
757 # it will need $doc_obj to set the Identifier metadata...
758 $self->set_OID($doc_obj);
759 } else {
760 # use the default set_OID() in doc.pm
761 $doc_obj->set_OID();
762 }
763
764 # process the document
765 $processor->process($doc_obj);
766
767 if(defined($self->{'places_filename'})){
768 &util::rm($self->{'places_filename'});
769 $self->{'places_filename'} = undef;
770 }
771
772 $self->{'num_processed'} ++;
773 undef $doc_obj;
774 return 1; # processed the file
775}
776
777# returns undef if file is rejected by the plugin
778sub process {
779 my $self = shift (@_);
780 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj) = @_;
781
782 gsprintf(STDERR, "BasPlug::process {common.must_be_implemented}\n") && die "\n";
783 # die "Basplug::process function must be implemented in sub-class\n";
784
785 return undef; # never gets here
786}
787
788# uses the multiread package to read in the entire file pointed to
789# by filename and loads the resulting text into $$textref. Input text
790# may be in any of the encodings handled by multiread, output text
791# will be in utf8
792sub read_file {
793 my $self = shift (@_);
794 my ($filename, $encoding, $language, $textref) = @_;
795
796 if (!-r $filename)
797 {
798 my $outhandle = $self->{'outhandle'};
799 gsprintf($outhandle, "{BasPlug.read_denied}\n", $filename) if $self->{'verbosity'};
800 # print $outhandle "Read permission denied for $filename\n" if $self->{'verbosity'};
801 return;
802 }
803
804 $$textref = "";
805
806 if (!open (FILE, $filename)) {
807 gsprintf(STDERR, "BasPlug::read_file {BasPlug.could_not_open_for_reading} ($!)\n", $filename);
808 die "\n";
809 }
810
811 if ($encoding eq "ascii") {
812 undef $/;
813 $$textref = <FILE>;
814 $/ = "\n";
815 } else {
816 my $reader = new multiread();
817 $reader->set_handle ('BasPlug::FILE');
818 $reader->set_encoding ($encoding);
819 $reader->read_file ($textref);
820
821 #Now segments chinese if the separate_cjk option is set
822 if ($self->{'separate_cjk'}) {
823 # segment the Chinese words
824 $$textref = &cnseg::segment($$textref);
825 }
826 }
827
828 close FILE;
829}
830
831sub filename_based_title
832{
833 my $self = shift (@_);
834 my ($file) = @_;
835
836 my $file_derived_title = $file;
837 $file_derived_title =~ s/_/ /g;
838 $file_derived_title =~ s/\..*?$//;
839
840 return $file_derived_title;
841}
842
843
844sub title_fallback
845{
846 my $self = shift (@_);
847 my ($doc_obj,$section,$file) = @_;
848
849 if (!defined $doc_obj->get_metadata_element ($section, "Title")) {
850
851 my $file_derived_title = $self->filename_based_title($file);
852 $doc_obj->add_metadata ($section, "Title", $file_derived_title);
853 }
854}
855
856sub textcat_get_language_encoding {
857 my $self = shift (@_);
858 my ($filename) = @_;
859
860 my ($language, $encoding, $extracted_encoding);
861 if ($self->{'input_encoding'} eq "auto") {
862 # use textcat to automatically work out the input encoding and language
863 ($language, $encoding) = $self->get_language_encoding ($filename);
864 } elsif ($self->{'extract_language'}) {
865 # use textcat to get language metadata
866 ($language, $extracted_encoding) = $self->get_language_encoding ($filename);
867 $encoding = $self->{'input_encoding'};
868 # don't print this message for english... english in utf8 is identical
869 # to english in iso-8859-1 (except for some punctuation). We don't have
870 # a language model for en_utf8, so textcat always says iso-8859-1!
871 if ($extracted_encoding ne $encoding && $language ne "en"
872 && $self->{'verbosity'}) {
873 my $plugin_name = ref ($self);
874 my $outhandle = $self->{'outhandle'};
875 gsprintf($outhandle, "$plugin_name: {BasPlug.wrong_encoding}\n", $filename, $encoding, $extracted_encoding);
876 # print $outhandle "$plugin_name: WARNING: $filename was read using $encoding encoding but ";
877 # print $outhandle "appears to be encoded as $extracted_encoding.\n";
878 }
879 } else {
880 $language = $self->{'default_language'};
881 $encoding = $self->{'input_encoding'};
882 }
883 return ($language, $encoding);
884}
885
886# Uses textcat to work out the encoding and language of the text in
887# $filename. All html tags are removed before processing.
888# returns an array containing "language" and "encoding"
889sub get_language_encoding {
890 my $self = shift (@_);
891 my ($filename) = @_;
892 my $outhandle = $self->{'outhandle'};
893 my $unicode_format = "";
894 # read in file
895 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";
896 undef $/;
897 my $text = <FILE>;
898 $/ = "\n";
899 close FILE;
900
901 # check if first few bytes have a Byte Order Marker
902 my $bom=substr($text,0,2); # check 16bit unicode
903 if ($bom eq "\xff\xfe") { # little endian 16bit unicode
904 $unicode_format="unicode";
905 } elsif ($bom eq "\xfe\xff") { # big endian 16bit unicode
906 $unicode_format="unicode";
907 } else {
908 $bom=substr($text,0,3); # check utf-8
909 if ($bom eq "\xef\xbb\xbf") { # utf-8 coded FEFF bom
910 $unicode_format="utf8";
911# } elsif ($bom eq "\xef\xbf\xbe") { # utf-8 coded FFFE bom. Error!?
912# $unicode_format="utf8";
913 }
914 }
915
916
917 # remove <title>stuff</title> -- as titles tend often to be in English
918 # for foreign language documents
919 $text =~ s/<title>(.|\n)*?<\/title>//i;
920
921 # remove all HTML tags
922 # XXX this doesn't match plugins derived from HTMLPlug (except ConvertTo)
923 if (ref($self) eq 'HTMLPlug' ||
924 (exists $self->{'converted_to'} && $self->{'converted_to'} eq 'HTML')){
925 $text =~ s/<[^>]*>//sg;
926 }
927
928 # get the language/encoding
929 my $results = $self->{'textcat'}->classify(\$text);
930
931 # if textcat returns 3 or less possibilities we'll use the
932 # first one in the list - otherwise use the defaults
933 if (scalar @$results > 3) {
934 my $best_encoding="";
935 if ($unicode_format) { # in case the first had a BOM
936 $best_encoding=$unicode_format;
937 } else {
938 my %guessed_encodings = ();
939 foreach my $result (@$results) {
940 $result =~ /([^\-]+)$/;
941 my $enc=$1;
942 if (!defined($guessed_encodings{$enc})) {
943 $guessed_encodings{$enc}=0;
944 }
945 $guessed_encodings{$enc}++;
946 }
947
948 $guessed_encodings{""}=-1; # for default best_encoding of ""
949 foreach my $enc (keys %guessed_encodings) {
950 if ($guessed_encodings{$enc} >
951 $guessed_encodings{$best_encoding}){
952 $best_encoding=$enc;
953 }
954 }
955 }
956
957 if ($self->{'input_encoding'} ne 'auto') {
958 if ($self->{'extract_language'} && ($self->{'verbosity'}>2)) {
959 gsprintf($outhandle,
960 "BasPlug: {BasPlug.could_not_extract_language}\n",
961 $filename, $self->{'default_language'});
962 }
963 return ($self->{'default_language'}, $self->{'input_encoding'});
964
965 } else {
966 if ($self->{'verbosity'}>2) {
967 gsprintf($outhandle,
968 "BasPlug: {BasPlug.could_not_extract_language}\n",
969 $filename, $self->{'default_language'});
970 }
971 return ($self->{'default_language'}, $best_encoding);
972 }
973 }
974
975 # format language/encoding
976 my ($language, $encoding) = $results->[0] =~ /^([^-]*)(?:-(.*))?$/;
977 if (!defined $language) {
978 if ($self->{'verbosity'}>2) {
979 gsprintf($outhandle,
980 "BasPlug: {BasPlug.could_not_extract_language}\n",
981 $filename, $self->{'default_language'});
982 }
983 $language = $self->{'default_language'};
984 }
985 if (!defined $encoding) {
986 if ($self->{'verbosity'}>2) {
987 gsprintf($outhandle,
988 "BasPlug: {BasPlug.could_not_extract_encoding}\n",
989 $filename, $self->{'default_encoding'});
990 }
991 $encoding = $self->{'default_encoding'};
992 }
993
994
995 # check for equivalents where textcat doesn't have some encodings...
996 # eg MS versions of standard encodings
997 if ($encoding =~ /^iso_8859_(\d+)/) {
998 my $iso = $1; # which variant of the iso standard?
999 # iso-8859 sets don't use chars 0x80-0x9f, windows codepages do
1000 if ($text =~ /[\x80-\x9f]/) {
1001 # Western Europe
1002 if ($iso == 1 or $iso == 15) { $encoding = 'windows_1252' }
1003 elsif ($iso == 2) { $encoding = 'windows_1250' } # Central Europe
1004 elsif ($iso == 5) { $encoding = 'windows_1251' } # Cyrillic
1005 elsif ($iso == 6) { $encoding = 'windows_1256' } # Arabic
1006 elsif ($iso == 7) { $encoding = 'windows_1253' } # Greek
1007 elsif ($iso == 8) { $encoding = 'windows_1255' } # Hebrew
1008 elsif ($iso == 9) { $encoding = 'windows_1254' } # Turkish
1009 }
1010 }
1011
1012 if ($encoding !~ /^(ascii|utf8|unicode)$/ &&
1013 !defined $encodings::encodings->{$encoding}) {
1014 if ($self->{'verbosity'}) {
1015 gsprintf($outhandle, "BasPlug: {BasPlug.unsupported_encoding}\n",
1016 $filename, $encoding, $self->{'default_encoding'});
1017 }
1018 $encoding = $self->{'default_encoding'};
1019 }
1020
1021 return ($language, $encoding);
1022}
1023
1024# add any extra metadata that's been passed around from one
1025# plugin to another.
1026# extra_metadata uses add_utf8_metadata so it expects metadata values
1027# to already be in utf8
1028sub extra_metadata {
1029 my $self = shift (@_);
1030 my ($doc_obj, $cursection, $metadata) = @_;
1031
1032 foreach my $field (keys(%$metadata)) {
1033 # $metadata->{$field} may be an array reference
1034 if ($field eq "gsdlassocfile_tobe") {
1035 # 'gsdlassocfile_tobe' is artificially introduced metadata
1036 # that is used to signal that certain additional files should
1037 # be tied to this document. Useful in situations where a
1038 # metadata pass in the plugin pipeline works out some files
1039 # need to be associated with a document, but the document hasn't
1040 # been formed yet.
1041
1042 my $equiv_form = "";
1043 foreach my $gaf (@{$metadata->{$field}}) {
1044 my ($full_filename,$mimetype) = ($gaf =~ m/^(.*):(.*):$/);
1045 my ($tail_filename) = ($full_filename =~ /^.*[\/\\](.+?)$/);
1046 my $filename = $full_filename;
1047
1048 $doc_obj->associate_file($full_filename,$tail_filename,$mimetype);
1049
1050 my ($doc_ext) = ($tail_filename =~ m/^.*\.(.*)$/);
1051 my $start_doclink = "<a href=\"_httpcollection_/index/assoc/{Or}{[parent(Top):archivedir],[archivedir]}/$tail_filename\">";
1052 my $srcicon = "_icon".$doc_ext."_";
1053 my $end_doclink = "</a>";
1054
1055 $equiv_form .= " $start_doclink\{If\}{$srcicon,$srcicon,$doc_ext\}$end_doclink";
1056 }
1057 $doc_obj->add_utf8_metadata ($cursection, "equivlink", $equiv_form);
1058 }
1059 elsif (ref ($metadata->{$field}) eq "ARRAY") {
1060 map {
1061 $doc_obj->add_utf8_metadata ($cursection, $field, $_);
1062 } @{$metadata->{$field}};
1063 } else {
1064 $doc_obj->add_utf8_metadata ($cursection, $field, $metadata->{$field});
1065 }
1066 }
1067}
1068
1069# initialise metadata extractors
1070sub initialise_extractors {
1071 my $self = shift (@_);
1072
1073 if ($self->{'extract_acronyms'} || $self->{'markup_acronyms'}) {
1074 &acronym::initialise_acronyms();
1075 }
1076}
1077
1078# finalise metadata extractors
1079sub finalise_extractors {
1080 my $self = shift (@_);
1081
1082 if ($self->{'extract_acronyms'} || $self->{'markup_acronyms'}) {
1083 &acronym::finalise_acronyms();
1084 }
1085}
1086
1087# FIRSTNNN: extract the first NNN characters as metadata
1088sub extract_first_NNNN_characters {
1089 my $self = shift (@_);
1090 my ($textref, $doc_obj, $thissection) = @_;
1091
1092 foreach my $size (split /,/, $self->{'first'}) {
1093 my $tmptext = $$textref;
1094 $tmptext =~ s/^\s+//;
1095 $tmptext =~ s/\s+$//;
1096 $tmptext =~ s/\s+/ /gs;
1097 $tmptext = substr ($tmptext, 0, $size);
1098 $tmptext =~ s/\s\S*$/&#8230;/;
1099 $doc_obj->add_utf8_metadata ($thissection, "First$size", $tmptext);
1100 }
1101}
1102
1103sub extract_email {
1104 my $self = shift (@_);
1105 my ($textref, $doc_obj, $thissection) = @_;
1106 my $outhandle = $self->{'outhandle'};
1107
1108 gsprintf($outhandle, " {BasPlug.extracting_emails}...\n")
1109 if ($self->{'verbosity'} > 2);
1110
1111 my @email = ($$textref =~ m/([-a-z0-9\.@+_=]+@(?:[-a-z0-9]+\.)+(?:com|org|edu|mil|int|net|[a-z][a-z]))/g);
1112 @email = sort @email;
1113
1114 my @email2 = ();
1115 foreach my $address (@email) {
1116 if (!(join(" ",@email2) =~ m/$address/ )) {
1117 push @email2, $address;
1118 $doc_obj->add_utf8_metadata ($thissection, "emailAddress", $address);
1119 gsprintf($outhandle, " {BasPlug.extracting} $address\n")
1120 if ($self->{'verbosity'} > 3);
1121 }
1122 }
1123 gsprintf($outhandle, " {BasPlug.done_email_extract}\n")
1124 if ($self->{'verbosity'} > 2);
1125}
1126
1127# extract metadata
1128sub auto_extract_metadata {
1129
1130 my $self = shift (@_);
1131 my ($doc_obj) = @_;
1132
1133 if ($self->{'extract_email'}) {
1134 my $thissection = $doc_obj->get_top_section();
1135 while (defined $thissection) {
1136 my $text = $doc_obj->get_text($thissection);
1137 $self->extract_email (\$text, $doc_obj, $thissection) if $text =~ /./;
1138 $thissection = $doc_obj->get_next_section ($thissection);
1139 }
1140 }
1141 if ($self->{'extract_placenames'}) {
1142 my $thissection = $doc_obj->get_top_section();
1143 while (defined $thissection) {
1144 my $text = $doc_obj->get_text($thissection);
1145 $self->extract_placenames (\$text, $doc_obj, $thissection) if $text =~ /./;
1146 $thissection = $doc_obj->get_next_section ($thissection);
1147 }
1148 }
1149
1150 # adding kea keyphrases
1151 if ($self->{'kea'}) {
1152
1153 my $thissection = $doc_obj->get_top_section();
1154 my $text = "";
1155 my $list;
1156
1157 #loop through sections to gather whole doc
1158 while (defined $thissection) {
1159 my $sectiontext = $doc_obj->get_text($thissection);
1160 $text = $text.$sectiontext;
1161 $thissection = $doc_obj->get_next_section ($thissection);
1162 }
1163
1164 if ($self->{'kea_options'}) {
1165 #if kea options flag is set, call Kea with specified options
1166 $list = &Kea::extract_KeyPhrases ($text, $self->{'kea_options'});
1167 } else {
1168 #otherwise call Kea with no options
1169 $list = &Kea::extract_KeyPhrases ($text);
1170 }
1171 if ($list){
1172 # if a list of kea keyphrases was returned (ie not empty)
1173 if ($self->{'verbosity'}) {
1174 gsprintf(STDERR, "{BasPlug.keyphrases}: $list\n");
1175 }
1176
1177 #add metadata to top section
1178 $thissection = $doc_obj->get_top_section();
1179
1180 # add all key phrases as one metadata
1181 $doc_obj->add_metadata($thissection, "Keyphrases", $list);
1182
1183 # add individual key phrases as multiple metadata
1184 foreach my $keyphrase (split(',', $list)) {
1185 $keyphrase =~ s/^\s+|\s+$//g;
1186 $doc_obj->add_metadata($thissection, "Keyphrase", $keyphrase);
1187 }
1188 }
1189 } #end of kea
1190
1191 if ($self->{'first'}) {
1192 my $thissection = $doc_obj->get_top_section();
1193 while (defined $thissection) {
1194 my $text = $doc_obj->get_text($thissection);
1195 $self->extract_first_NNNN_characters (\$text, $doc_obj, $thissection) if $text =~ /./;
1196 $thissection = $doc_obj->get_next_section ($thissection);
1197 }
1198 }
1199
1200 if ($self->{'extract_acronyms'}) {
1201 my $thissection = $doc_obj->get_top_section();
1202 while (defined $thissection) {
1203 my $text = $doc_obj->get_text($thissection);
1204 $self->extract_acronyms (\$text, $doc_obj, $thissection) if $text =~ /./;
1205 $thissection = $doc_obj->get_next_section ($thissection);
1206 }
1207 }
1208
1209 if ($self->{'markup_acronyms'}) {
1210 my $thissection = $doc_obj->get_top_section();
1211 while (defined $thissection) {
1212 my $text = $doc_obj->get_text($thissection);
1213 $text = $self->markup_acronyms ($text, $doc_obj, $thissection);
1214 $doc_obj->delete_text($thissection);
1215 $doc_obj->add_text($thissection, $text);
1216 $thissection = $doc_obj->get_next_section ($thissection);
1217 }
1218 }
1219
1220 if($self->{'date_extract'}) {
1221 my $thissection = $doc_obj->get_top_section();
1222 while (defined $thissection) {
1223
1224 my $text = $doc_obj->get_text($thissection);
1225 &DateExtract::get_date_metadata($text, $doc_obj,
1226 $thissection,
1227 $self->{'no_biblio'},
1228 $self->{'max_year'},
1229 $self->{'max_century'});
1230 $thissection = $doc_obj->get_next_section ($thissection);
1231 }
1232 }
1233}
1234
1235# extract acronyms from a section in a document. progress is
1236# reported to outhandle based on the verbosity. both the Acronym
1237# and the AcronymKWIC metadata items are created.
1238
1239sub extract_acronyms {
1240 my $self = shift (@_);
1241 my ($textref, $doc_obj, $thissection) = @_;
1242 my $outhandle = $self->{'outhandle'};
1243
1244 # print $outhandle " extracting acronyms ...\n"
1245 gsprintf($outhandle, " {BasPlug.extracting_acronyms}...\n")
1246 if ($self->{'verbosity'} > 2);
1247
1248 my $acro_array = &acronym::acronyms($textref);
1249
1250 foreach my $acro (@$acro_array) {
1251
1252 #check that this is the first time ...
1253 my $seen_before = "false";
1254 my $previous_data = $doc_obj->get_metadata($thissection, "Acronym");
1255 foreach my $thisAcro (@$previous_data) {
1256 if ($thisAcro eq $acro->to_string()) {
1257 $seen_before = "true";
1258 if ($self->{'verbosity'} >= 4) {
1259 gsprintf($outhandle, " {BasPlug.already_seen} " .
1260 $acro->to_string() . "\n");
1261 }
1262 }
1263 }
1264
1265 if ($seen_before eq "false") {
1266 #write it to the file ...
1267 $acro->write_to_file();
1268
1269 #do the normal acronym
1270 $doc_obj->add_utf8_metadata($thissection, "Acronym", $acro->to_string());
1271 gsprintf($outhandle, " {BasPlug.adding} ".$acro->to_string()."\n")
1272 if ($self->{'verbosity'} > 3);
1273 }
1274 }
1275
1276 gsprintf($outhandle, " {BasPlug.done_acronym_extract}\n")
1277 if ($self->{'verbosity'} > 2);
1278}
1279
1280sub markup_acronyms {
1281 my $self = shift (@_);
1282 my ($text, $doc_obj, $thissection) = @_;
1283 my $outhandle = $self->{'outhandle'};
1284
1285 gsprintf($outhandle, " {BasPlug.marking_up_acronyms}...\n")
1286 if ($self->{'verbosity'} > 2);
1287
1288 #self is passed in to check for verbosity ...
1289 $text = &acronym::markup_acronyms($text, $self);
1290
1291 gsprintf($outhandle, " {BasPlug.done_acronym_markup}\n")
1292 if ($self->{'verbosity'} > 2);
1293
1294 return $text;
1295}
1296
1297sub compile_stats {
1298 my $self = shift(@_);
1299 my ($stats) = @_;
1300
1301 $stats->{'num_processed'} += $self->{'num_processed'};
1302 $stats->{'num_not_processed'} += $self->{'num_not_processed'};
1303 $stats->{'num_archives'} += $self->{'num_archives'};
1304
1305}
1306
1307sub associate_cover_image {
1308 my $self = shift(@_);
1309 my ($doc_obj, $filename) = @_;
1310
1311 my $top_section=$doc_obj->get_top_section();
1312
1313 $filename =~ s/\.[^\\\/\.]+$/\.jpg/;
1314 if (-e $filename) {
1315 $doc_obj->associate_file($filename, "cover.jpg", "image/jpeg");
1316 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1317 } else {
1318 $filename =~ s/jpg$/JPG/;
1319 if (-e $filename) {
1320 $doc_obj->associate_file($filename, "cover.jpg", "image/jpeg");
1321 $doc_obj->add_utf8_metadata($top_section, "hascover", 1);
1322 }
1323 }
1324}
1325
13261;
Note: See TracBrowser for help on using the repository browser.