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

Last change on this file since 11414 was 11333, checked in by mdewsnip, 18 years ago

Now consistently sets $self->{'gli'} in plugin::begin.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 31.8 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' => "title_sub",
162 'desc' => "{HTMLPlug.title_sub}",
163 'type' => "string",
164 'deft' => "" },
165 { 'name' => "noscaleup",
166 'desc' => "{ImagePlug.noscaleup}",
167 'type' => "flag",
168 'reqd' => "no" },
169 { 'name' => "thumbnail",
170 'desc' => "{PagedImgPlug.thumbnail}",
171 'type' => "flag",
172 'reqd' => "no" },
173 { 'name' => "thumbnailsize",
174 'desc' => "{ImagePlug.thumbnailsize}",
175 'type' => "int",
176 'deft' => "100",
177 'range' => "1,",
178 'reqd' => "no" },
179 { 'name' => "thumbnailtype",
180 'desc' => "{ImagePlug.thumbnailtype}",
181 'type' => "string",
182 'deft' => "gif",
183 'reqd' => "no" },
184 { 'name' => "screenview",
185 'desc' => "{PagedImgPlug.screenview}",
186 'type' => "flag",
187 'reqd' => "no" },
188 { 'name' => "screenviewsize",
189 'desc' => "{PagedImgPlug.screenviewsize}",
190 'type' => "int",
191 'deft' => "500",
192 'range' => "1,",
193 'reqd' => "no" },
194 { 'name' => "screenviewtype",
195 'desc' => "{PagedImgPlug.screenviewtype}",
196 'type' => "string",
197 'deft' => "jpg",
198 'reqd' => "no" },
199 { 'name' => "converttotype",
200 'desc' => "{ImagePlug.converttotype}",
201 'type' => "string",
202 'deft' => "",
203 'reqd' => "no" },
204 { 'name' => "minimumsize",
205 'desc' => "{ImagePlug.minimumsize}",
206 'type' => "int",
207 'deft' => "100",
208 'range' => "1,",
209 'reqd' => "no" },
210 { 'name' => "headerpage",
211 'desc' => "{PagedImgPlug.headerpage}",
212 'type' => "flag",
213 'reqd' => "no" },
214 { 'name' => "documenttype",
215 'desc' => "{PagedImgPlug.documenttype}",
216 'type' => "enum",
217 'list' => $type_list,
218 'deft' => "paged",
219 'reqd' => "no" } ];
220
221
222my $options = { 'name' => "PagedImgPlug",
223 'desc' => "{PagedImgPlug.desc}",
224 'inherits' => "yes",
225 'args' => $arguments };
226
227sub new {
228 my ($class) = shift (@_);
229 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
230 push(@$pluginlist, $class);
231
232 if(defined $arguments){ push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});}
233 if(defined $options) { push(@{$hashArgOptLists->{"OptList"}},$options)};
234
235 my $self = (defined $hashArgOptLists)? new XMLPlug($pluginlist,$inputargs,$hashArgOptLists): new XMLPlug($pluginlist,$inputargs);
236
237 return bless $self, $class;
238}
239
240sub get_default_process_exp {
241 my $self = shift (@_);
242
243 return q^\.item$^;
244}
245
246# want to block everything except the .item ones
247# but instead we will block images and txt files
248sub get_default_block_exp {
249 my $self = shift (@_);
250
251 return q^(?i)(\.jpe?g|\.gif|\.png|\.tif?f|\.te?xt|~)$^
252}
253
254# Create the thumbnail and screenview images, and discover the Image's
255# size, width, and height using the convert utility.
256sub process_image {
257 my $self = shift (@_);
258 my $filename = shift (@_); # filename with full path
259 my $srcfile = shift (@_); # filename without path
260 my $doc_obj = shift (@_);
261 my $section = shift (@_); #the current section
262 my $rotate = shift (@_); # whether to rotate the image or not
263 $rotate = 0 unless defined $rotate;
264
265 # check that the image file exists!!
266 if (!-f $filename) {
267 print "PagedImgPlug: ERROR: File $filename does not exist, skipping\n";
268 return 0;
269 }
270
271 my $top=0;
272 if ($section eq $doc_obj->get_top_section()) {
273 $top=1;
274 }
275 my $verbosity = $self->{'verbosity'};
276 my $outhandle = $self->{'outhandle'};
277
278 # check the filename is okay
279 return 0 if ($srcfile eq "" || $filename eq "");
280
281 my $minimumsize = $self->{'minimumsize'};
282 if (defined $minimumsize && (-s $filename < $minimumsize)) {
283 print $outhandle "PagedImgPlug: \"$filename\" too small, skipping\n"
284 if ($verbosity > 1);
285 }
286
287 # Convert the image to a new type (if required), and rotate if required.
288 my $converttotype = $self->{'converttotype'};
289 my $originalfilename = ""; # only set if we do a conversion
290 my $type = "unknown";
291 my $converted = 0;
292 my $rotated=0;
293
294 if ($converttotype ne "" && $filename !~ /$converttotype$/) {
295 $converted=1;
296 $originalfilename = $filename;
297 my $filehead = &util::get_tmp_filename();
298 $filename = $filehead . ".$converttotype";
299 my $n = 1;
300 while (-e $filename) {
301 $filename = "$filehead$n\.$converttotype";
302 $n++;
303 }
304 $self->{'tmp_filename1'} = $filename;
305
306 my $rotate_option = "";
307 if ($rotate eq "r") {
308 $rotate_option = "-rotate 180 ";
309 }
310
311 my $command = "convert -verbose \"$originalfilename\" $rotate_option \"$filename\"";
312 print $outhandle "CONVERT: $command\n" if ($verbosity > 2);
313 my $result = '';
314 $result = `$command`;
315 print $outhandle "CONVERT RESULT = $result\n" if ($verbosity > 2);
316
317 $type = $converttotype;
318 } elsif ($rotate eq "r") {
319 $rotated=1;
320 $originalfilename = $filename;
321 $filename = &util::get_tmp_filename();
322
323 my $command = "convert \"$originalfilename\" -rotate 180 \"$filename\"";
324 print $outhandle "ROTATE: $command\n" if ($verbosity > 2);
325 my $result = '';
326 $result = `$command`;
327 print $outhandle "ROTATE RESULT = $result\n" if ($verbosity > 2);
328
329 }
330
331
332 # Add the image metadata
333 my $file; # the new file name
334 my $id = $srcfile;
335 $id =~ s/\.([^\.]*)$//; # the new file name without an extension
336 if ($converted) {
337 # we have converted the image
338 # add on the new extension
339 $file .= "$id.$converttotype";
340 } else {
341 $file = $srcfile;
342 }
343
344 my $url =$file; # the new file name prepared for a url
345 my $srcurl = $srcfile;
346 $url =~ s/ /%20/g;
347 $srcurl =~ s/ /%20/g;
348
349 $doc_obj->add_metadata ($section, "Image", $url);
350
351 # Also want to set filename as 'Source' metadata to be
352 # consistent with other plugins
353 $doc_obj->add_metadata ($section, "Source", $srcurl);
354
355 my ($image_type, $image_width, $image_height, $image_size)
356 = &identify($filename, $outhandle, $verbosity);
357
358 $doc_obj->add_metadata ($section, "ImageType", $image_type);
359 $doc_obj->add_metadata ($section, "ImageWidth", $image_width);
360 $doc_obj->add_metadata ($section, "ImageHeight", $image_height);
361 $doc_obj->add_metadata ($section, "ImageSize", $image_size);
362 $doc_obj->add_metadata ($section, "FileFormat", "PagedImg");
363
364 if ($type eq "unknown" && $image_type) {
365 $type = $image_type;
366 }
367
368 if ($top) {
369 $doc_obj->add_metadata ($section, "srclink",
370 "<a href=\"_httpcollection_/index/assoc/[assocfilepath]/[Image]\">");
371 $doc_obj->add_metadata ($section, "srcicon", "<img src=\"_httpcollection_/index/assoc/[assocfilepath]/[Image]\">");
372
373 } else {
374 $doc_obj->add_metadata ($section, "srclink",
375 "<a href=\"_httpcollection_/index/assoc/[parent(Top):assocfilepath]/[Image]\">");
376 $doc_obj->add_metadata ($section, "srcicon", "<img src=\"_httpcollection_/index/assoc/[parent(Top):assocfilepath]/[Image]\">");
377
378 }
379 $doc_obj->add_metadata ($section, "/srclink", "</a>");
380
381
382 # Add the image as an associated file
383 $doc_obj->associate_file($filename,$file,"image/$type",$section);
384 print $outhandle "associating file $filename as name $file\n" if ($verbosity > 2);
385
386 if ($self->{'thumbnail'}) {
387 # Make the thumbnail image
388 my $thumbnailsize = $self->{'thumbnailsize'} || 100;
389 my $thumbnailtype = $self->{'thumbnailtype'} || 'gif';
390
391 my $filehead = &util::get_tmp_filename();
392 my $thumbnailfile = $filehead . ".$thumbnailtype";
393 my $n=1;
394 while (-e $thumbnailfile) {
395 $thumbnailfile = $filehead . $n . ".$thumbnailtype";
396 $n++;
397 }
398
399 $self->{'tmp_filename2'} = $thumbnailfile;
400
401 # Generate the thumbnail with convert
402 my $command = "convert -verbose -geometry $thumbnailsize"
403 . "x$thumbnailsize \"$filename\" \"$thumbnailfile\"";
404 print $outhandle "THUMBNAIL: $command\n" if ($verbosity > 2);
405 my $result = '';
406 $result = `$command 2>&1` ;
407 print $outhandle "THUMB RESULT: $result\n" if ($verbosity > 2);
408
409 # Add the thumbnail as an associated file ...
410 if (-e "$thumbnailfile") {
411 $doc_obj->associate_file("$thumbnailfile", $id."thumb.$thumbnailtype", "image/$thumbnailtype",$section);
412 $doc_obj->add_metadata ($section, "ThumbType", $thumbnailtype);
413 $doc_obj->add_metadata ($section, "Thumb", $id."thumb.$thumbnailtype");
414 if ($top) {
415 $doc_obj->add_metadata ($section, "thumbicon", "<img src=\"_httpcollection_/index/assoc/[assocfilepath]/[Thumb]\" width=[ThumbWidth] height=[ThumbHeight]>");
416 } else {
417 $doc_obj->add_metadata ($section, "thumbicon", "<img src=\"_httpcollection_/index/assoc/[parent(Top):assocfilepath]/[Thumb]\" width=[ThumbWidth] height=[ThumbHeight]>");
418 }
419 }
420
421 # Extract Thumnail metadata from convert output
422 if ($result =~ m/[0-9]+x[0-9]+=>([0-9]+)x([0-9]+)/) {
423 $doc_obj->add_metadata ($section, "ThumbWidth", $1);
424 $doc_obj->add_metadata ($section, "ThumbHeight", $2);
425 }
426 }
427 # Make a screen-sized version of the picture if requested
428 if ($self->{'screenview'}) {
429
430 # To do: if the actual image is smaller than the screenview size,
431 # we should use the original !
432
433 my $screenviewsize = $self->{'screenviewsize'} || 500;
434 my $screenviewtype = $self->{'screenviewtype'} || 'jpeg';
435 my $filehead = &util::get_tmp_filename();
436 my $screenviewfilename = $filehead . ".$screenviewtype";
437 my $n=1;
438 while (-e $screenviewfilename) {
439 $screenviewfilename = "$filehead$n\.$screenviewtype";
440 $n++;
441 }
442 $self->{'tmp_filename3'} = $screenviewfilename;
443
444 # make the screenview image
445 my $command = "convert -verbose -geometry $screenviewsize"
446 . "x$screenviewsize \"$filename\" \"$screenviewfilename\"";
447 print $outhandle "SCREENVIEW: $command\n" if ($verbosity > 2);
448 my $result = "";
449 $result = `$command 2>&1` ;
450 print $outhandle "SCREENVIEW RESULT: $result\n" if ($verbosity > 3);
451
452 # get screenview dimensions, size and type
453 if ($result =~ m/[0-9]+x[0-9]+=>([0-9]+)x([0-9]+)/) {
454 $doc_obj->add_metadata ($section, "ScreenWidth", $1);
455 $doc_obj->add_metadata ($section, "ScreenHeight", $2);
456 }elsif ($result =~ m/([0-9]+)x([0-9]+)/) {
457 #if the image hasn't changed size, the previous regex doesn't match
458 $doc_obj->add_metadata ($section, "ScreenWidth", $1);
459 $doc_obj->add_metadata ($section, "ScreenHeight", $2);
460 }
461
462 #add the screenview as an associated file ...
463 if (-e "$screenviewfilename") {
464 $doc_obj->associate_file("$screenviewfilename", $id."sv.$screenviewtype",
465 "image/$screenviewtype",$section);
466 print $outhandle "associating screen file $screenviewfilename as name $id sv.$screenviewtype\n" if ($verbosity > 2);
467
468 $doc_obj->add_metadata ($section, "ScreenType", $screenviewtype);
469 $doc_obj->add_metadata ($section, "Screen", $id."sv.$screenviewtype");
470
471 if ($top) {
472 $doc_obj->add_metadata ($section, "screenicon", "<img src=\"_httpcollection_/index/assoc/[assocfilepath]/[Screen]\" width=[ScreenWidth] height=[ScreenHeight]>");
473 } else {
474 $doc_obj->add_metadata ($section, "screenicon", "<img src=\"_httpcollection_/index/assoc/[parent(Top):assocfilepath]/[Screen]\" width=[ScreenWidth] height=[ScreenHeight]>");
475
476 }
477 } else {
478 print $outhandle "PagedImgPlug: couldn't find \"$screenviewfilename\"\n";
479 }
480 }
481
482 return $type;
483
484
485}
486
487
488
489# Discover the characteristics of an image file with the ImageMagick
490# "identify" command.
491
492sub identify {
493 my ($image, $outhandle, $verbosity) = @_;
494
495 # Use the ImageMagick "identify" command to get the file specs
496 my $command = "identify \"$image\" 2>&1";
497 print $outhandle "$command\n" if ($verbosity > 2);
498 my $result = '';
499 $result = `$command`;
500 print $outhandle "$result\n" if ($verbosity > 3);
501
502 # Read the type, width, and height
503 my $type = 'unknown';
504 my $width = 'unknown';
505 my $height = 'unknown';
506
507 my $image_safe = quotemeta $image;
508 if ($result =~ /^$image_safe (\w+) (\d+)x(\d+)/) {
509 $type = $1;
510 $width = $2;
511 $height = $3;
512 }
513
514 # Read the size
515 my $size = "unknown";
516 if ($result =~ m/^.* ([0-9]+)b/) {
517 $size = $1;
518 } elsif ($result =~ m/^.* ([0-9]+)kb/) {
519 $size = 1024 * $1;
520 }
521
522 print $outhandle "file: $image:\t $type, $width, $height, $size\n"
523 if ($verbosity > 3);
524
525 # Return the specs
526 return ($type, $width, $height, $size);
527}
528
529
530# The PagedImgPlug read() function. This function does all the right things
531# to make general options work for a given plugin. It calls the process()
532# function which does all the work specific to a plugin (like the old
533# read functions used to do). Most plugins should define their own
534# process() function and let this read() function keep control.
535#
536# PagedImgPlug overrides read() because there is no need to read the actual
537# text of the file in, because the contents of the file is not text...
538#
539# Return number of files processed, undef if can't process
540# Note that $base_dir might be "" and that $file might
541# include directories
542
543sub read_into_doc_obj {
544 my $self = shift (@_);
545 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
546 my $outhandle = $self->{'outhandle'};
547
548 #check process and block exps, smart block, etc
549 my ($block_status,$filename) = $self->read_block(@_);
550 return $block_status if ((!defined $block_status) || ($block_status==0));
551
552 print $outhandle "PagedImgPlug processing \"$filename\"\n"
553 if $self->{'verbosity'} > 1;
554 print STDERR "<Processing n='$file' p='PagedImgPlug'>\n" if ($gli);
555
556 # here we need to decide if we have an old text .item file, or a new xml
557 # .item file - for now the test is if the first non-empty line is
558 # <PagedDocument> then its xml
559 my $xml_version = 0;
560 open (ITEMFILE, $filename) || die "couldn't open $filename\n";
561
562 my $backup_filename = "backup.item";
563 open (BACKUP,">$backup_filename")|| die "couldn't write to $backup_filename\n";
564 my $line = "";
565 my $num = 0;
566 $line = <ITEMFILE>;
567 while ($line !~ /\w/) {
568 $line = <ITEMFILE>;
569 }
570 chomp $line;
571 if ($line =~ /<PagedDocument/) {
572 $xml_version = 1;
573 }
574 close ITEMFILE;
575 open (ITEMFILE, $filename) || die "couldn't open $filename\n";
576 #Tidy up the item file some metadata title contains \vt-vertical tab
577 while ($line = <ITEMFILE>) {
578 $line =~ s/\x0B+//ig;
579 $line =~ s/&/&amp;/g;
580 print BACKUP ($line);
581 }
582 close ITEMFILE;
583 close BACKUP;
584 &File::Copy::copy ($backup_filename, $filename);
585 &util::rm($backup_filename);
586 #print STDERR "xml version = $xml_version\n";
587 my $doc_obj;
588 if ($xml_version) {
589 $file =~ s/^[\/\\]+//; # $file often begins with / so we'll tidy it up
590 $self->{'file'} = $file;
591 $self->{'filename'} = $filename;
592 $self->{'processor'} = $processor;
593 $self->{'metadata'} = $metadata;
594
595 eval {
596 $@ = "";
597 my $xslt = $self->{'xslt'};
598 if (defined $xslt && ($xslt ne "")) {
599 # perform xslt
600 my $transformed_xml = $self->apply_xslt($xslt,$filename);
601
602 # feed transformed file (now in memory as string) into XML parser
603 #$self->{'parser'}->parse($transformed_xml);
604 $self->parse_string($transformed_xml);
605 }
606 else {
607 #$self->{'parser'}->parsefile($filename);
608 $self->parse_file($filename);
609 }
610 };
611
612
613
614 if ($@) {
615
616 # parsefile may either croak somewhere in XML::Parser (e.g. because
617 # the document is not well formed) or die somewhere in XMLPlug or a
618 # derived plugin (e.g. because we're attempting to process a
619 # document whose DOCTYPE is not meant for this plugin). For the
620 # first case we'll print a warning and continue, for the second
621 # we'll just continue quietly
622
623 print STDERR "**** XML Parse Error is: $@\n";
624
625 my ($msg) = $@ =~ /Carp::croak\(\'(.*?)\'\)/;
626 if (defined $msg) {
627 my $outhandle = $self->{'outhandle'};
628 my $plugin_name = ref ($self);
629 print $outhandle "$plugin_name failed to process $file ($msg)\n";
630 }
631
632 # reset ourself for the next document
633 $self->{'section_level'}=0;
634 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
635 return -1; # error during processing
636 }
637 $doc_obj = $self->{'doc_obj'};
638 } else {
639 my ($dir);
640 ($dir, $file) = $filename =~ /^(.*?)([^\/\\]*)$/;
641
642 #process the .item file
643 $doc_obj = $self->process_item($filename, $dir, $file, $processor);
644
645 }
646
647 if ($self->{'cover_image'}) {
648 $self->associate_cover_image($doc_obj, $filename);
649 }
650
651 # include any metadata passed in from previous plugins
652 # note that this metadata is associated with the top level section
653 my $section = $doc_obj->get_top_section();
654 $self->extra_metadata ($doc_obj, $section, $metadata);
655 #my $text="";
656 # do plugin specific processing of doc_obj
657 #unless (defined ($self->process(\$text, $pluginfo, $base_dir, $file, $metadata, $doc_obj))) {
658 #print STDERR "<ProcessingError n='$file'>\n" if ($gli);
659 #return -1;
660 #}
661 # do any automatic metadata extraction
662 $self->auto_extract_metadata ($doc_obj);
663
664 $self->{'num_processed'}++;
665 return (1,$doc_obj);
666}
667
668sub read
669{
670 my $self = shift (@_);
671 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
672
673 my ($process_status,$doc_obj) = $self->read_into_doc_obj(@_);
674
675 if ((defined $process_status) && ($process_status == 1)) {
676 # process the document
677 $processor->process($doc_obj);
678
679 #if(defined($self->{'places_filename'})){
680 # &util::rm($self->{'places_filename'});
681 # $self->{'places_filename'} = undef;
682 #}
683 #$self->{'num_processed'} ++;
684 undef $doc_obj;
685 }
686
687 # clean up temporary files - we do this here instead of in
688 # process_image becuase associated files aren't actually copied
689 # until after process has been run.
690 if (defined $self->{'tmp_filename1'} &&
691 -e $self->{'tmp_filename1'}) {
692 &util::rm($self->{'tmp_filename1'})
693 }
694 if (defined $self->{'tmp_filename2'} &&
695 -e $self->{'tmp_filename2'}) {
696 &util::rm($self->{'tmp_filename2'})
697 }
698 if (defined $self->{'tmp_filename3'} &&
699 -e $self->{'tmp_filename3'}) {
700 &util::rm($self->{'tmp_filename3'})
701 }
702 # if process_status == 1, then the file has been processed.
703 return $process_status;
704}
705
706sub xml_start_tag {
707 my $self = shift(@_);
708 my ($expat, $element) = @_;
709 $self->{'element'} = $element;
710
711 my $doc_obj = $self->{'doc_obj'};
712 if ($element eq "PagedDocument") {
713 $self->{'current_section'} = $doc_obj->get_top_section();
714 } elsif ($element eq "PageGroup" || $element eq "Page") {
715 # create a new section as a child
716 $self->{'current_section'} = $doc_obj->insert_section($doc_obj->get_end_child($self->{'current_section'}));
717 $self->{'num_pages'}++;
718 # assign pagenum as what??
719 my $pagenum = $_{'pagenum'}; #TODO!!
720 if (defined $pagenum) {
721 $doc_obj->set_utf8_metadata_element($self->{'current_section'}, 'PageNum', $pagenum);
722 }
723 my ($imgfile) = $_{'imgfile'};
724 if (defined $imgfile) {
725 $self->process_image($self->{'base_dir'}.$imgfile, $imgfile, $doc_obj, $self->{'current_section'});
726 }
727 my ($txtfile) = $_{'txtfile'};
728 if (defined($txtfile)&& $txtfile ne "") {
729 $self->process_text ($self->{'base_dir'}.$txtfile, $txtfile, $doc_obj, $self->{'current_section'});
730 } else {
731 # otherwise add in some dummy text
732 $doc_obj->add_text($self->{'current_section'}, &gsprintf::lookup_string("{BasPlug.dummy_text}"));
733 }
734 } elsif ($element eq "Metadata") {
735 $self->{'metadata_name'} = $_{'name'};
736 }
737}
738
739sub xml_end_tag {
740 my $self = shift(@_);
741 my ($expat, $element) = @_;
742
743 my $doc_obj = $self->{'doc_obj'};
744 if ($element eq "Page" || $element eq "PageGroup") {
745 # if Title hasn't been assigned, set PageNum as Title
746 if (!defined $doc_obj->get_metadata_element ($self->{'current_section'}, "Title") && defined $doc_obj->get_metadata_element ($self->{'current_section'}, "PageNum" )) {
747 $doc_obj->add_utf8_metadata ($self->{'current_section'}, "Title", $doc_obj->get_metadata_element ($self->{'current_section'}, "PageNum" ));
748 }
749 # move the current section back to the parent
750 $self->{'current_section'} = $doc_obj->get_parent_section($self->{'current_section'});
751 } elsif ($element eq "Metadata") {
752
753 $doc_obj->add_utf8_metadata ($self->{'current_section'}, $self->{'metadata_name'}, $self->{'metadata_value'});
754 $self->{'metadata_name'} = "";
755 $self->{'metadata_value'} = "";
756
757 }
758 # otherwise we ignore the end tag
759}
760
761
762sub xml_text {
763 my $self = shift(@_);
764 my ($expat) = @_;
765
766 if ($self->{'element'} eq "Metadata") {
767 $self->{'metadata_value'} .= $_;
768 }
769}
770
771sub xml_doctype {
772}
773
774sub open_document {
775 my $self = shift(@_);
776
777 # create a new document
778 $self->{'doc_obj'} = new doc ($self->{'filename'}, "indexed_doc");
779 my $doc_obj = $self->{'doc_obj'};
780 $doc_obj->set_OIDtype ($self->{'processor'}->{'OIDtype'});
781 my ($dir, $file) = $self->{'filename'} =~ /^(.*?)([^\/\\]*)$/;
782 $self->{'base_dir'} = $dir;
783 $self->{'num_pages'} = 0;
784 my $topsection = $doc_obj->get_top_section();
785 if ($self->{'documenttype'} eq 'paged') {
786 # set the gsdlthistype metadata to Paged - this ensures this document will
787 # be treated as a Paged doc, even if Titles are not numeric
788
789 $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Paged");
790 } else {
791 $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Hierarchy");
792 }
793
794 $doc_obj->add_metadata ($topsection, "Source", $file);
795 if ($self->{'headerpage'}) {
796 $doc_obj->add_text($topsection, &gsprintf::lookup_string("{BasPlug.dummy_text}"));
797 }
798
799}
800
801sub close_document {
802 my $self = shift(@_);
803 my $doc_obj = $self->{'doc_obj'};
804
805 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
806 $doc_obj->add_metadata($doc_obj->get_top_section(), "FileFormat", "PagedImg");
807
808 # add numpages metadata
809 $doc_obj->set_utf8_metadata_element ($doc_obj->get_top_section(), 'NumPages', $self->{'num_pages'});
810
811 # add an OID
812 $doc_obj->set_OID();
813
814}
815
816sub process_item {
817 my $self = shift (@_);
818 my ($filename, $dir, $file, $processor) = @_;
819
820 my $doc_obj = new doc ($filename, "indexed_doc");
821 $doc_obj->set_OIDtype ($processor->{'OIDtype'});
822 my $topsection = $doc_obj->get_top_section();
823 $doc_obj->add_utf8_metadata($topsection, "Plugin", "$self->{'plugin_type'}");
824 $doc_obj->add_metadata($topsection, "FileFormat", "PagedImg");
825
826 if ($self->{'documenttype'} eq 'paged') {
827 # set the gsdlthistype metadata to Paged - this ensures this document will
828 # be treated as a Paged doc, even if Titles are not numeric
829 $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Paged");
830 } else {
831 $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Hierarchy");
832 }
833
834 $doc_obj->add_metadata ($topsection, "Source", $file);
835
836 open (ITEMFILE, $filename) || die "couldn't open $filename\n";
837 my $line = "";
838 my $num = 0;
839 while (defined ($line = <ITEMFILE>)) {
840 next unless $line =~ /\w/;
841 chomp $line;
842 next if $line =~ /^#/; # ignore comment lines
843 if ($line =~ /^<([^>]*)>\s*(.*?)\s*$/) {
844 $doc_obj->set_utf8_metadata_element ($topsection, $1, $2);
845 #$meta->{$1} = $2;
846 } else {
847 $num++;
848 # line should be like page:imagefilename:textfilename:r - the r is optional -> means rotate the image 180 deg
849 $line =~ s/^\s+//; #remove space at the front
850 $line =~ s/\s+$//; #remove space at the end
851 my ($pagenum, $imgname, $txtname, $rotate) = split /:/, $line;
852
853 # create a new section for each image file
854 my $cursection = $doc_obj->insert_section($doc_obj->get_end_child($topsection));
855 # the page number becomes the Title
856 $doc_obj->set_utf8_metadata_element($cursection, 'Title', $pagenum);
857 # process the image for this page
858 my $result = $self->process_image($dir.$imgname, $imgname, $doc_obj, $cursection, $rotate);
859
860 if (!defined $result)
861 {
862 print "PagedImgPlug: couldn't process image \"$dir.$imgname\" for item \"$filename\"\n";
863 }
864
865 # process the text file if one is there
866 if (defined $txtname && $txtname ne "") {
867 $result = undef;
868 $result = $self->process_text ($dir.$txtname, $txtname, $doc_obj, $cursection);
869 if (!defined $result) {
870 print "PagedImgPlug: couldn't process text file \"$dir.$txtname\" for item \"$filename\"\n";
871 }
872 } else {
873 # otherwise add in some dummy text
874 $doc_obj->add_text($cursection, &gsprintf::lookup_string("{BasPlug.dummy_text}"));
875 }
876 }
877 }
878
879 close ITEMFILE;
880
881 # if we want a header page, we need to add some text into the top section, otherwise this section will become invisible
882 if ($self->{'headerpage'}) {
883 $doc_obj->add_text($topsection, &gsprintf::lookup_string("{BasPlug.dummy_text}"));
884 }
885 $file =~ s/\.item//i;
886 $doc_obj->set_OID ();
887 # add numpages metadata
888 $doc_obj->set_utf8_metadata_element ($topsection, 'NumPages', "$num");
889 return $doc_obj;
890}
891
892sub process_text {
893 my $self = shift (@_);
894 my ($fullpath, $file, $doc_obj, $cursection) = @_;
895
896 # check that the text file exists!!
897 if (!-f $fullpath) {
898 print "PagedImgPlug: ERROR: File $fullpath does not exist, skipping\n";
899 return 0;
900 }
901
902 # Do encoding stuff
903 my ($language, $encoding) = $self->textcat_get_language_encoding ($fullpath);
904
905 my $text="";
906 &BasPlug::read_file($self, $fullpath, $encoding, $language, \$text);
907 if (!length ($text)) {
908 my $plugin_name = ref ($self);
909 print "PagedImgPlug: ERROR: $fullpath contains no text\n" if $self->{'verbosity'};
910 return 0;
911 }
912
913 # we need to escape the escape character, or else mg will convert into
914 # eg literal newlines, instead of leaving the text as '\n'
915 $text =~ s/\\/\\\\/g; # macro language
916 $text =~ s/_/\\_/g; # macro language
917 $text =~ s/</&lt;/g;
918 $text =~ s/>/&gt;/g;
919
920 # insert preformat tags and add text to document object
921 $doc_obj->add_utf8_text($cursection, "<pre>\n$text\n</pre>");
922
923 return 1;
924}
925
926# do plugin specific processing of doc_obj
927sub process {
928 my $self = shift (@_);
929 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj) = @_;
930 my $outhandle = $self->{'outhandle'};
931
932 return 1;
933}
934
9351;
Note: See TracBrowser for help on using the repository browser.