source: trunk/gsdl/perllib/plugins/PagedImgPlug.pm@ 10280

Last change on this file since 10280 was 10276, checked in by chi, 19 years ago

Add a read_into_doc_obj() for enabling secondary_pluging function. Also, a numer of minor modifications
to identify undefined variable or text file contains no text.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 30.7 KB
Line 
1###########################################################################
2#
3# PagedImgPlug.pm -- plugin for sets of images and OCR text that
4# make up a document
5# A component of the Greenstone digital library software
6# from the New Zealand Digital Library Project at the
7# University of Waikato, New Zealand.
8#
9# Copyright (C) 1999 New Zealand Digital Library Project
10#
11# This program is free software; you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation; either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with this program; if not, write to the Free Software
23# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24#
25###########################################################################
26
27# PagedImgPlug
28# processes sequences of images, with optional OCR text
29#
30# This plugin takes *.item files, which contain metadata and lists of image
31# files, and produces a document containing sections, one for each page.
32# The files should be named something.item, then you can have more than one
33# book in a directory. You will need to create these files, one for each
34# document/book.
35#
36#There are two formats for the item files: a plain text format, and an xml
37#format. You can use either format, and can have both formats in the same
38#collection if you like. If you use the plain format, you must not start the
39#file off with <PagedDocument>
40
41#### PLAIN FORMAT
42# The format of the xxx.item file is as follows:
43# The first lines contain any metadata for the whole document
44# <metadata-name>metadata-value
45# eg.
46# <Title>Snail farming
47# <Date>19230102
48# Then comes a list of pages, one page per line, each line has the format
49#
50# pagenum:imagefile:textfile:r
51#
52# page num and imagefile are required. pagenum is used for the Title
53# of the section, and in the display is shown as page <pagenum>.
54# imagefile is the image for the page. textfile is an optional text
55# file containing the OCR (or any) text for the page - this gets added
56# as the text for the section. r is optional, and signals that the image
57# should be rotated 180deg. Eg use this if the image has been made upside down.
58# So an example item file looks like:
59# <Title>Snail farming
60# <Date>19960403
61# 1:p1.gif:p1.txt:
62# 2:p2.gif::
63# 3:p3.gif:p3.txt:
64# 3b:p3b.gif:p3b.txt:r
65# The second page has no text, the fourth page is a back page, and
66# should be rotated.
67#
68
69#### XML FORMAT
70# The xml format looks like the following
71#<PagedDocument>
72#<Metadata name="Title">The Title of the entire document</Metadata>
73#<Page pagenum="1" imgfile="xxx.jpg" txtfile="yyy.jpg">
74#<Metadata name="Title">The Title of this page</Metadata>
75#</Page>
76#... more pages
77#</PagedDocument>
78#PagedDocument contains a list of Pages, Metadata and PageGroups. Any metadata
79#that is not inside another tag will belong to the document.
80#Each Page has a pagenum (not used at the moment), an imgfile and/or a txtfile.
81#These are both optional - if neither is used, the section will have no content.
82#Pages can also have metadata associated with them.
83#PageGroups can be introduced at any point - they can contain Metadata and Pages and other PageGroups. They are used to introduce hierarchical structure into the document.
84#For example
85#<PagedDocument>
86#<PageGroup>
87#<Page>
88#<Page>
89#</PageGroup>
90#<Page>
91#</PagedDocument>
92#would generate a structure like
93#X
94#--X
95# --X
96# --X
97#--X
98#PageGroup tags can also have imgfile/textfile metadata if you like - this way they get some content themselves.
99
100#Currently the XML structure doesn't work very well with the paged document type, unless you use numerical Titles for each section.
101#There is still a bit of work to do on this format:
102#* enable other text file types, eg html, pdf etc
103#* make the document paging work properly
104#* add pagenum as Title unless a Title is present?
105
106# All the supplemetary image amd text files should be in the same folder as
107# the .item file.
108#
109# To display the images instead of the document text, you can use [srcicon]
110# in the DocumentText format statement.
111# For example,
112#
113# format DocumentText "<center><table width=_pagewidth_><tr><td>[srcicon]</td></tr></table></center>"
114#
115# To have it create thumbnail size images, use the '-thumbnail' option.
116# To have it create medium size images for display, use the '-screenview'
117# option. As usual, running
118# 'perl -S pluginfo.pl PagedImgPlug' will list all the options.
119
120# If you want the resulting documents to be presented with a table of
121# contents, use '-documenttype hierarchy', otherwise they will have
122# next and previous arrows, and a goto page X box.
123
124# If you have used -screenview, you can also use [screenicon] in the format
125# statement to display the smaller image. Here is an example that switches
126# between the two:
127#
128# format DocumentText "<center><table width=_pagewidth_><tr><td>{If}{_cgiargp_ eq full,<a href='_httpdocument_&d=_cgiargd_&p=small'>Switch to small version.</a>,<a href='_httpdocument_&d=_cgiargd_&p=full'>Switch to fullsize version</a>}</td></tr><tr><td>{If}{_cgiargp_ eq full,<a href='_httpdocument_&d=_cgiargd_&p=small' title='Switch to small version'>[srcicon]</a>,<a href='_httpdocument_&d=_cgiargd_&p=full' title='Switch to fullsize version'>[screenicon]</a>}</td></tr></table></center>"
129#
130# Additional metadata can be added into the .item files, alternatively you can
131# use normal metadata.xml files, with the name of the xxx.item file as the
132# FileName (only for document level metadata).
133
134package PagedImgPlug;
135
136use XMLPlug;
137use strict;
138no strict 'refs'; # allow filehandles to be variables and viceversa
139
140sub BEGIN {
141 @PagedImgPlug::ISA = ('XMLPlug');
142}
143
144my $type_list =
145 [ { 'name' => "paged",
146 'desc' => "{PagedImgPlug.documenttype.paged}" },
147 { 'name' => "hierarchy",
148 'desc' => "{PagedImgPlug.documenttype.hierarchy}" } ];
149
150my $arguments =
151 [ { 'name' => "process_exp",
152 'desc' => "{BasPlug.process_exp}",
153 'type' => "string",
154 'deft' => &get_default_process_exp(),
155 'reqd' => "no" },
156 { 'name' => "block_exp",
157 'desc' => "{BasPlug.block_exp}",
158 'type' => "string",
159 'deft' => &get_default_block_exp(),
160 'reqd' => "no" },
161 { 'name' => "noscaleup",
162 'desc' => "{ImagePlug.noscaleup}",
163 'type' => "flag",
164 'reqd' => "no" },
165 { 'name' => "thumbnail",
166 'desc' => "{PagedImgPlug.thumbnail}",
167 'type' => "flag",
168 'reqd' => "no" },
169 { 'name' => "thumbnailsize",
170 'desc' => "{ImagePlug.thumbnailsize}",
171 'type' => "int",
172 'deft' => "100",
173 'range' => "1,",
174 'reqd' => "no" },
175 { 'name' => "thumbnailtype",
176 'desc' => "{ImagePlug.thumbnailtype}",
177 'type' => "string",
178 'deft' => "gif",
179 'reqd' => "no" },
180 { 'name' => "screenview",
181 'desc' => "{PagedImgPlug.screenview}",
182 'type' => "flag",
183 'reqd' => "no" },
184 { 'name' => "screenviewsize",
185 'desc' => "{PagedImgPlug.screenviewsize}",
186 'type' => "int",
187 'deft' => "500",
188 'range' => "1,",
189 'reqd' => "no" },
190 { 'name' => "screenviewtype",
191 'desc' => "{PagedImgPlug.screenviewtype}",
192 'type' => "string",
193 'deft' => "jpg",
194 'reqd' => "no" },
195 { 'name' => "converttotype",
196 'desc' => "{ImagePlug.converttotype}",
197 'type' => "string",
198 'deft' => "",
199 'reqd' => "no" },
200 { 'name' => "minimumsize",
201 'desc' => "{ImagePlug.minimumsize}",
202 'type' => "int",
203 'deft' => "100",
204 'range' => "1,",
205 'reqd' => "no" },
206 { 'name' => "headerpage",
207 'desc' => "{PagedImgPlug.headerpage}",
208 'type' => "flag",
209 'reqd' => "no" },
210 { 'name' => "documenttype",
211 'desc' => "{PagedImgPlug.documenttype}",
212 'type' => "enum",
213 'list' => $type_list,
214 'deft' => "paged",
215 'reqd' => "no" } ];
216
217
218my $options = { 'name' => "PagedImgPlug",
219 'desc' => "{PagedImgPlug.desc}",
220 'inherits' => "yes",
221 'args' => $arguments };
222
223sub new {
224 my ($class) = shift (@_);
225 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
226 push(@$pluginlist, $class);
227
228 if(defined $arguments){ push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});}
229 if(defined $options) { push(@{$hashArgOptLists->{"OptList"}},$options)};
230
231 my $self = (defined $hashArgOptLists)? new XMLPlug($pluginlist,$inputargs,$hashArgOptLists): new XMLPlug($pluginlist,$inputargs);
232
233 return bless $self, $class;
234}
235
236sub get_default_process_exp {
237 my $self = shift (@_);
238
239 return q^\.item$^;
240}
241
242# want to block everything except the .item ones
243# but instead we will block images and txt files
244sub get_default_block_exp {
245 my $self = shift (@_);
246
247 return q^(?i)(\.jpe?g|\.gif|\.png|\.tif?f|\.te?xt|~)$^
248}
249# Create the thumbnail and screenview images, and discover the Image's
250# size, width, and height using the convert utility.
251sub process_image {
252 my $self = shift (@_);
253 my $filename = shift (@_); # filename with full path
254 my $srcfile = shift (@_); # filename without path
255 my $doc_obj = shift (@_);
256 my $section = shift (@_); #the current section
257 my $rotate = shift (@_); # whether to rotate the image or not
258 $rotate = 0 unless defined $rotate;
259
260 my $top=0;
261 if ($section eq $doc_obj->get_top_section()) {
262 $top=1;
263 }
264 my $verbosity = $self->{'verbosity'};
265 my $outhandle = $self->{'outhandle'};
266
267 # check the filename is okay
268 return 0 if ($srcfile eq "" || $filename eq "");
269
270 my $minimumsize = $self->{'minimumsize'};
271 if (defined $minimumsize && (-s $filename < $minimumsize)) {
272 print $outhandle "PagedImgPlug: \"$filename\" too small, skipping\n"
273 if ($verbosity > 1);
274 }
275
276 # Convert the image to a new type (if required), and rotate if required.
277 my $converttotype = $self->{'converttotype'};
278 my $originalfilename = ""; # only set if we do a conversion
279 my $type = "unknown";
280 my $converted = 0;
281 my $rotated=0;
282
283 if ($converttotype ne "" && $filename !~ /$converttotype$/) {
284 $converted=1;
285 $originalfilename = $filename;
286 my $filehead = &util::get_tmp_filename();
287 $filename = $filehead . ".$converttotype";
288 my $n = 1;
289 while (-e $filename) {
290 $filename = "$filehead$n\.$converttotype";
291 $n++;
292 }
293 $self->{'tmp_filename1'} = $filename;
294
295 my $rotate_option = "";
296 if ($rotate eq "r") {
297 $rotate_option = "-rotate 180 ";
298 }
299
300 my $command = "convert -verbose \"$originalfilename\" $rotate_option \"$filename\"";
301 print $outhandle "CONVERT: $command\n" if ($verbosity > 2);
302 my $result = '';
303 $result = `$command`;
304 print $outhandle "CONVERT RESULT = $result\n" if ($verbosity > 2);
305
306 $type = $converttotype;
307 } elsif ($rotate eq "r") {
308 $rotated=1;
309 $originalfilename = $filename;
310 $filename = &util::get_tmp_filename();
311
312 my $command = "convert \"$originalfilename\" -rotate 180 \"$filename\"";
313 print $outhandle "ROTATE: $command\n" if ($verbosity > 2);
314 my $result = '';
315 $result = `$command`;
316 print $outhandle "ROTATE RESULT = $result\n" if ($verbosity > 2);
317
318 }
319
320
321 # Add the image metadata
322 my $file; # the new file name
323 my $id = $srcfile;
324 $id =~ s/\.([^\.]*)$//; # the new file name without an extension
325 if ($converted) {
326 # we have converted the image
327 # add on the new extension
328 $file .= "$id.$converttotype";
329 } else {
330 $file = $srcfile;
331 }
332
333 my $url =$file; # the new file name prepared for a url
334 my $srcurl = $srcfile;
335 $url =~ s/ /%20/g;
336 $srcurl =~ s/ /%20/g;
337
338 $doc_obj->add_metadata ($section, "Image", $url);
339
340 # Also want to set filename as 'Source' metadata to be
341 # consistent with other plugins
342 $doc_obj->add_metadata ($section, "Source", $srcurl);
343
344 my ($image_type, $image_width, $image_height, $image_size)
345 = &identify($filename, $outhandle, $verbosity);
346
347 $doc_obj->add_metadata ($section, "ImageType", $image_type);
348 $doc_obj->add_metadata ($section, "ImageWidth", $image_width);
349 $doc_obj->add_metadata ($section, "ImageHeight", $image_height);
350 $doc_obj->add_metadata ($section, "ImageSize", $image_size);
351 $doc_obj->add_metadata ($section, "FileFormat", "PagedImg");
352
353 if ($type eq "unknown" && $image_type) {
354 $type = $image_type;
355 }
356
357 if ($top) {
358 $doc_obj->add_metadata ($section, "srclink",
359 "<a href=\"_httpcollection_/index/assoc/[assocfilepath]/[Image]\">");
360 $doc_obj->add_metadata ($section, "srcicon", "<img src=\"_httpcollection_/index/assoc/[assocfilepath]/[Image]\">");
361
362 } else {
363 $doc_obj->add_metadata ($section, "srclink",
364 "<a href=\"_httpcollection_/index/assoc/[parent(Top):assocfilepath]/[Image]\">");
365 $doc_obj->add_metadata ($section, "srcicon", "<img src=\"_httpcollection_/index/assoc/[parent(Top):assocfilepath]/[Image]\">");
366
367 }
368 $doc_obj->add_metadata ($section, "/srclink", "</a>");
369
370
371 # Add the image as an associated file
372 $doc_obj->associate_file($filename,$file,"image/$type",$section);
373 print $outhandle "associating file $filename as name $file\n" if ($verbosity > 2);
374
375 if ($self->{'thumbnail'}) {
376 # Make the thumbnail image
377 my $thumbnailsize = $self->{'thumbnailsize'} || 100;
378 my $thumbnailtype = $self->{'thumbnailtype'} || 'gif';
379
380 my $filehead = &util::get_tmp_filename();
381 my $thumbnailfile = $filehead . ".$thumbnailtype";
382 my $n=1;
383 while (-e $thumbnailfile) {
384 $thumbnailfile = $filehead . $n . ".$thumbnailtype";
385 $n++;
386 }
387
388 $self->{'tmp_filename2'} = $thumbnailfile;
389
390 # Generate the thumbnail with convert
391 my $command = "convert -verbose -geometry $thumbnailsize"
392 . "x$thumbnailsize \"$filename\" \"$thumbnailfile\"";
393 print $outhandle "THUMBNAIL: $command\n" if ($verbosity > 2);
394 my $result = '';
395 $result = `$command 2>&1` ;
396 print $outhandle "THUMB RESULT: $result\n" if ($verbosity > 2);
397
398 # Add the thumbnail as an associated file ...
399 if (-e "$thumbnailfile") {
400 $doc_obj->associate_file("$thumbnailfile", $id."thumb.$thumbnailtype", "image/$thumbnailtype",$section);
401 $doc_obj->add_metadata ($section, "ThumbType", $thumbnailtype);
402 $doc_obj->add_metadata ($section, "Thumb", $id."thumb.$thumbnailtype");
403 if ($top) {
404 $doc_obj->add_metadata ($section, "thumbicon", "<img src=\"_httpcollection_/index/assoc/[assocfilepath]/[Thumb]\" width=[ThumbWidth] height=[ThumbHeight]>");
405 } else {
406 $doc_obj->add_metadata ($section, "thumbicon", "<img src=\"_httpcollection_/index/assoc/[parent(Top):assocfilepath]/[Thumb]\" width=[ThumbWidth] height=[ThumbHeight]>");
407 }
408 }
409
410 # Extract Thumnail metadata from convert output
411 if ($result =~ m/[0-9]+x[0-9]+=>([0-9]+)x([0-9]+)/) {
412 $doc_obj->add_metadata ($section, "ThumbWidth", $1);
413 $doc_obj->add_metadata ($section, "ThumbHeight", $2);
414 }
415 }
416 # Make a screen-sized version of the picture if requested
417 if ($self->{'screenview'}) {
418
419 # To do: if the actual image is smaller than the screenview size,
420 # we should use the original !
421
422 my $screenviewsize = $self->{'screenviewsize'} || 500;
423 my $screenviewtype = $self->{'screenviewtype'} || 'jpeg';
424 my $filehead = &util::get_tmp_filename();
425 my $screenviewfilename = $filehead . ".$screenviewtype";
426 my $n=1;
427 while (-e $screenviewfilename) {
428 $screenviewfilename = "$filehead$n\.$screenviewtype";
429 $n++;
430 }
431 $self->{'tmp_filename3'} = $screenviewfilename;
432
433 # make the screenview image
434 my $command = "convert -verbose -geometry $screenviewsize"
435 . "x$screenviewsize \"$filename\" \"$screenviewfilename\"";
436 print $outhandle "SCREENVIEW: $command\n" if ($verbosity > 2);
437 my $result = "";
438 $result = `$command 2>&1` ;
439 print $outhandle "SCREENVIEW RESULT: $result\n" if ($verbosity > 3);
440
441 # get screenview dimensions, size and type
442 if ($result =~ m/[0-9]+x[0-9]+=>([0-9]+)x([0-9]+)/) {
443 $doc_obj->add_metadata ($section, "ScreenWidth", $1);
444 $doc_obj->add_metadata ($section, "ScreenHeight", $2);
445 }elsif ($result =~ m/([0-9]+)x([0-9]+)/) {
446 #if the image hasn't changed size, the previous regex doesn't match
447 $doc_obj->add_metadata ($section, "ScreenWidth", $1);
448 $doc_obj->add_metadata ($section, "ScreenHeight", $2);
449 }
450
451 #add the screenview as an associated file ...
452 if (-e "$screenviewfilename") {
453 $doc_obj->associate_file("$screenviewfilename", $id."sv.$screenviewtype",
454 "image/$screenviewtype",$section);
455 print $outhandle "associating screen file $screenviewfilename as name $id sv.$screenviewtype\n" if ($verbosity > 2);
456
457 $doc_obj->add_metadata ($section, "ScreenType", $screenviewtype);
458 $doc_obj->add_metadata ($section, "Screen", $id."sv.$screenviewtype");
459
460 if ($top) {
461 $doc_obj->add_metadata ($section, "screenicon", "<img src=\"_httpcollection_/index/assoc/[assocfilepath]/[Screen]\" width=[ScreenWidth] height=[ScreenHeight]>");
462 } else {
463 $doc_obj->add_metadata ($section, "screenicon", "<img src=\"_httpcollection_/index/assoc/[parent(Top):assocfilepath]/[Screen]\" width=[ScreenWidth] height=[ScreenHeight]>");
464
465 }
466 } else {
467 print $outhandle "PagedImgPlug: couldn't find \"$screenviewfilename\"\n";
468 }
469 }
470
471 return $type;
472
473
474}
475
476
477
478# Discover the characteristics of an image file with the ImageMagick
479# "identify" command.
480
481sub identify {
482 my ($image, $outhandle, $verbosity) = @_;
483
484 # Use the ImageMagick "identify" command to get the file specs
485 my $command = "identify \"$image\" 2>&1";
486 print $outhandle "$command\n" if ($verbosity > 2);
487 my $result = '';
488 $result = `$command`;
489 print $outhandle "$result\n" if ($verbosity > 3);
490
491 # Read the type, width, and height
492 my $type = 'unknown';
493 my $width = 'unknown';
494 my $height = 'unknown';
495
496 my $image_safe = quotemeta $image;
497 if ($result =~ /^$image_safe (\w+) (\d+)x(\d+)/) {
498 $type = $1;
499 $width = $2;
500 $height = $3;
501 }
502
503 # Read the size
504 my $size = "unknown";
505 if ($result =~ m/^.* ([0-9]+)b/) {
506 $size = $1;
507 } elsif ($result =~ m/^.* ([0-9]+)kb/) {
508 $size = 1024 * $1;
509 }
510
511 print $outhandle "file: $image:\t $type, $width, $height, $size\n"
512 if ($verbosity > 3);
513
514 # Return the specs
515 return ($type, $width, $height, $size);
516}
517
518
519# The PagedImgPlug read() function. This function does all the right things
520# to make general options work for a given plugin. It calls the process()
521# function which does all the work specific to a plugin (like the old
522# read functions used to do). Most plugins should define their own
523# process() function and let this read() function keep control.
524#
525# PagedImgPlug overrides read() because there is no need to read the actual
526# text of the file in, because the contents of the file is not text...
527#
528# Return number of files processed, undef if can't process
529# Note that $base_dir might be "" and that $file might
530# include directories
531
532sub read_into_doc_obj {
533 my $self = shift (@_);
534 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
535 my $outhandle = $self->{'outhandle'};
536 my $smart_block = $self->{'smart_block'};
537
538 my $filename = &util::filename_cat($base_dir, $file);
539
540 if ($self->associate_with($file,$filename,$metadata)) {
541 # a form of smart block
542 $self->{'num_blocked'} ++;
543 return 0; # blocked
544 }
545
546 if ($smart_block) {
547 if (defined $self->{'file_blocks'}->{$filename} && $self->{'file_blocks'}->{$filename} == 1){
548 $self->{'num_blocked'} ++;
549 return 0; # blocked
550 }
551 } elsif ($self->{'block_exp'} ne "" && $filename =~ /$self->{'block_exp'}/) {
552 $self->{'num_blocked'} ++;
553 return 0; # blocked
554 }
555
556 if ($filename !~ /$self->{'process_exp'}/ || !-f $filename) {
557 return undef;
558 }
559
560 print $outhandle "PagedImgPlug processing \"$filename\"\n"
561 if $self->{'verbosity'} > 1;
562 print STDERR "<Processing n='$file' p='PagedImgPlug'>\n" if ($gli);
563
564 # here we need to decide if we have an old text .item file, or a new xml
565 # .item file - for now the test is if the first non-empty line is
566 # <PagedDocument> then its xml
567 my $xml_version = 0;
568 open (ITEMFILE, $filename) || die "couldn't open $filename\n";
569 my $line = "";
570 my $num = 0;
571 $line = <ITEMFILE>;
572 while ($line !~ /\w/) {
573 $line = <ITEMFILE>;
574 }
575 chomp $line;
576 if ($line =~ /<PagedDocument/) {
577 $xml_version = 1;
578 }
579 close ITEMFILE;
580 #print STDERR "xml version = $xml_version\n";
581 my $doc_obj;
582 if ($xml_version) {
583 $file =~ s/^[\/\\]+//; # $file often begins with / so we'll tidy it up
584 $self->{'file'} = $file;
585 $self->{'filename'} = $filename;
586 $self->{'processor'} = $processor;
587 $self->{'metadata'} = $metadata;
588 $self->{'gli'} = $gli;
589 eval {
590 $@ = "";
591 my $xslt = $self->{'xslt'};
592 if (defined $xslt && ($xslt ne "")) {
593 # perform xslt
594 my $transformed_xml = $self->apply_xslt($xslt,$filename);
595
596 # feed transformed file (now in memory as string) into XML parser
597 #$self->{'parser'}->parse($transformed_xml);
598 $self->parse_string($transformed_xml);
599 }
600 else {
601 #$self->{'parser'}->parsefile($filename);
602 $self->parse_file($filename);
603 }
604 };
605
606 if ($@) {
607
608 # parsefile may either croak somewhere in XML::Parser (e.g. because
609 # the document is not well formed) or die somewhere in XMLPlug or a
610 # derived plugin (e.g. because we're attempting to process a
611 # document whose DOCTYPE is not meant for this plugin). For the
612 # first case we'll print a warning and continue, for the second
613 # we'll just continue quietly
614
615 print STDERR "**** XML Parse Error is: $@\n";
616
617 my ($msg) = $@ =~ /Carp::croak\(\'(.*?)\'\)/;
618 if (defined $msg) {
619 my $outhandle = $self->{'outhandle'};
620 my $plugin_name = ref ($self);
621 print $outhandle "$plugin_name failed to process $file ($msg)\n";
622 }
623
624 # reset ourself for the next document
625 $self->{'section_level'}=0;
626 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
627 return -1; # error during processing
628 }
629 $doc_obj = $self->{'doc_obj'};
630
631 } else {
632 my ($dir);
633 ($dir, $file) = $filename =~ /^(.*?)([^\/\\]*)$/;
634
635 #process the .item file
636 $doc_obj = $self->process_item($filename, $dir, $file, $processor);
637
638 }
639
640 if ($self->{'cover_image'}) {
641 $self->associate_cover_image($doc_obj, $filename);
642 }
643
644 # include any metadata passed in from previous plugins
645 # note that this metadata is associated with the top level section
646 my $section = $doc_obj->get_top_section();
647 $self->extra_metadata ($doc_obj, $section, $metadata);
648 #my $text="";
649 # do plugin specific processing of doc_obj
650 #unless (defined ($self->process(\$text, $pluginfo, $base_dir, $file, $metadata, $doc_obj))) {
651 #print STDERR "<ProcessingError n='$file'>\n" if ($gli);
652 #return -1;
653 #}
654 # do any automatic metadata extraction
655 $self->auto_extract_metadata ($doc_obj);
656
657 $self->{'num_processed'}++;
658 return (1,$doc_obj);
659}
660
661sub read
662{
663 my $self = shift (@_);
664 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
665
666 my ($process_status,$doc_obj) = $self->read_into_doc_obj(@_);
667
668 if ((defined $process_status) && ($process_status == 1)) {
669 # process the document
670 $processor->process($doc_obj);
671
672 #if(defined($self->{'places_filename'})){
673 # &util::rm($self->{'places_filename'});
674 # $self->{'places_filename'} = undef;
675 #}
676 #$self->{'num_processed'} ++;
677 undef $doc_obj;
678 }
679
680 # clean up temporary files - we do this here instead of in
681 # process_image becuase associated files aren't actually copied
682 # until after process has been run.
683 if (defined $self->{'tmp_filename1'} &&
684 -e $self->{'tmp_filename1'}) {
685 &util::rm($self->{'tmp_filename1'})
686 }
687 if (defined $self->{'tmp_filename2'} &&
688 -e $self->{'tmp_filename2'}) {
689 &util::rm($self->{'tmp_filename2'})
690 }
691 if (defined $self->{'tmp_filename3'} &&
692 -e $self->{'tmp_filename3'}) {
693 &util::rm($self->{'tmp_filename3'})
694 }
695 # if process_status == 1, then the file has been processed.
696 return $process_status;
697}
698
699sub xml_start_tag {
700 my $self = shift(@_);
701 my ($expat, $element) = @_;
702 $self->{'element'} = $element;
703
704 my $doc_obj = $self->{'doc_obj'};
705 if ($element eq "PagedDocument") {
706 $self->{'current_section'} = $doc_obj->get_top_section();
707 } elsif ($element eq "PageGroup" || $element eq "Page") {
708 # create a new section as a child
709 $self->{'current_section'} = $doc_obj->insert_section($doc_obj->get_end_child($self->{'current_section'}));
710 $self->{'num_pages'}++;
711 # assign pagenum as what??
712 my $pagenum = $_{'pagenum'}; #TODO!!
713 $doc_obj->set_utf8_metadata_element($self->{'current_section'}, 'PageNum', $pagenum);
714 my ($imgfile) = $_{'imgfile'};
715 if (defined $imgfile) {
716 $self->process_image($self->{'base_dir'}.$imgfile, $imgfile, $doc_obj, $self->{'current_section'});
717 }
718 my ($txtfile) = $_{'txtfile'};
719 if (defined($txtfile)&& $txtfile ne "") {
720 $self->process_text ($self->{'base_dir'}.$txtfile, $txtfile, $doc_obj, $self->{'current_section'});
721 } else {
722 # otherwise add in some dummy text
723 $doc_obj->add_text($self->{'current_section'}, &gsprintf::lookup_string("{BasPlug.dummy_text}"));
724 }
725 } elsif ($element eq "Metadata") {
726 $self->{'metadata_name'} = $_{'name'};
727 }
728}
729
730sub xml_end_tag {
731 my $self = shift(@_);
732 my ($expat, $element) = @_;
733
734 my $doc_obj = $self->{'doc_obj'};
735 if ($element eq "Page" || $element eq "PageGroup") {
736 # move the current section back to the parent
737 $self->{'current_section'} = $doc_obj->get_parent_section($self->{'current_section'});
738 } elsif ($element eq "Metadata") {
739
740 $doc_obj->add_utf8_metadata ($self->{'current_section'}, $self->{'metadata_name'}, $self->{'metadata_value'});
741 $self->{'metadata_name'} = "";
742 $self->{'metadata_value'} = "";
743
744 }
745 # otherwise we ignore the end tag
746}
747
748
749sub xml_text {
750 my $self = shift(@_);
751 my ($expat) = @_;
752
753 if ($self->{'element'} eq "Metadata") {
754 $self->{'metadata_value'} .= $_;
755 }
756}
757
758sub xml_doctype {
759}
760
761sub open_document {
762 my $self = shift(@_);
763
764 # create a new document
765 $self->{'doc_obj'} = new doc ($self->{'filename'}, "indexed_doc");
766 my $doc_obj = $self->{'doc_obj'};
767 $doc_obj->set_OIDtype ($self->{'processor'}->{'OIDtype'});
768 my ($dir, $file) = $self->{'filename'} =~ /^(.*?)([^\/\\]*)$/;
769 $self->{'base_dir'} = $dir;
770 $self->{'num_pages'} = 0;
771 my $topsection = $doc_obj->get_top_section();
772 if ($self->{'documenttype'} eq 'paged') {
773 # set the gsdlthistype metadata to Paged - this ensures this document will
774 # be treated as a Paged doc, even if Titles are not numeric
775
776 $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Paged");
777 } else {
778 $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Hierarchy");
779 }
780
781 $doc_obj->add_metadata ($topsection, "Source", $file);
782 if ($self->{'headerpage'}) {
783 $doc_obj->add_text($topsection, &gsprintf::lookup_string("{BasPlug.dummy_text}"));
784 }
785
786}
787
788sub close_document {
789 my $self = shift(@_);
790 my $doc_obj = $self->{'doc_obj'};
791
792 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
793 $doc_obj->add_metadata($doc_obj->get_top_section(), "FileFormat", "PagedImg");
794
795 # add numpages metadata
796 $doc_obj->set_utf8_metadata_element ($doc_obj->get_top_section(), 'NumPages', $self->{'num_pages'});
797
798 # add an OID
799 $doc_obj->set_OID();
800
801}
802
803sub process_item {
804 my $self = shift (@_);
805 my ($filename, $dir, $file, $processor) = @_;
806
807 my $doc_obj = new doc ($filename, "indexed_doc");
808 my $topsection = $doc_obj->get_top_section();
809
810 if ($self->{'documenttype'} eq 'paged') {
811 # set the gsdlthistype metadata to Paged - this ensures this document will
812 # be treated as a Paged doc, even if Titles are not numeric
813 $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Paged");
814 } else {
815 $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Hierarchy");
816 }
817
818 $doc_obj->add_metadata ($topsection, "Source", $file);
819
820 open (ITEMFILE, $filename) || die "couldn't open $filename\n";
821 my $line = "";
822 my $num = 0;
823 while (defined ($line = <ITEMFILE>)) {
824 next unless $line =~ /\w/;
825 chomp $line;
826 if ($line =~ /^<([^>]*)>(.*?)\s*$/) {
827 $doc_obj->set_utf8_metadata_element ($topsection, $1, $2);
828 #$meta->{$1} = $2;
829 } else {
830 $num++;
831 # line should be like page:imagefilename:textfilename:r - the r is optional -> means rotate the image 180 deg
832 $line =~ s/^\s+//; #remove space at the front
833 $line =~ s/\s+$//; #remove space at the end
834 my ($pagenum, $imgname, $txtname, $rotate) = split /:/, $line;
835
836 # create a new section for each image file
837 my $cursection = $doc_obj->insert_section($doc_obj->get_end_child($topsection));
838 # the page number becomes the Title
839 $doc_obj->set_utf8_metadata_element($cursection, 'Title', $pagenum);
840 # process the image for this page
841 my $result = $self->process_image($dir.$imgname, $imgname, $doc_obj, $cursection, $rotate);
842
843 if (!defined $result)
844 {
845 print "PagedImgPlug: couldn't process image \"$dir.$imgname\" for item \"$filename\"\n";
846 }
847
848 # process the text file if one is there
849 if (defined $txtname && $txtname ne "") {
850 $result = undef;
851 $result = $self->process_text ($dir.$txtname, $txtname, $doc_obj, $cursection);
852 if (!defined $result) {
853 print "PagedImgPlug: couldn't process text file \"$dir.$txtname\" for item \"$filename\"\n";
854 }
855 } else {
856 # otherwise add in some dummy text
857 $doc_obj->add_text($cursection, &gsprintf::lookup_string("{BasPlug.dummy_text}"));
858 }
859 }
860 }
861
862 close ITEMFILE;
863
864 # if we want a header page, we need to add some text into the top section, otherwise this section will become invisible
865 if ($self->{'headerpage'}) {
866 $doc_obj->add_text($topsection, &gsprintf::lookup_string("{BasPlug.dummy_text}"));
867 }
868 $file =~ s/\.item//i;
869 $doc_obj->set_OID ();
870 # add numpages metadata
871 $doc_obj->set_utf8_metadata_element ($topsection, 'NumPages', "$num");
872 return $doc_obj;
873}
874
875sub process_text {
876 my $self = shift (@_);
877 my ($fullpath, $file, $doc_obj, $cursection) = @_;
878
879 # Do encoding stuff
880 my ($language, $encoding) = $self->textcat_get_language_encoding ($fullpath);
881
882 my $text="";
883 &BasPlug::read_file($self, $fullpath, $encoding, $language, \$text);
884 if (!length ($text)) {
885 my $plugin_name = ref ($self);
886 print "PagedImgPlug: ERROR: $fullpath contains no text\n" if $self->{'verbosity'};
887 return 0;
888 }
889
890 # we need to escape the escape character, or else mg will convert into
891 # eg literal newlines, instead of leaving the text as '\n'
892 $text =~ s/\\/\\\\/g; # macro language
893 $text =~ s/_/\\_/g; # macro language
894 $text =~ s/</&lt;/g;
895 $text =~ s/>/&gt;/g;
896
897 # insert preformat tags and add text to document object
898 $doc_obj->add_utf8_text($cursection, "<pre>\n$text\n</pre>");
899
900 return 1;
901}
902
903# do plugin specific processing of doc_obj
904sub process {
905 my $self = shift (@_);
906 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj) = @_;
907 my $outhandle = $self->{'outhandle'};
908
909 return 1;
910}
911
9121;
Note: See TracBrowser for help on using the repository browser.