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

Last change on this file since 11072 was 11069, checked in by mdewsnip, 18 years ago

Added an option to use Kea 4.0 -- this isn't included with Greenstone, but it will tell you where to get it.

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