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

Last change on this file since 11090 was 11090, checked in by kjdon, 18 years ago

made all plugins that implement read() call read_block to check process_exp, block_exp, smart blocking, cover image blocking etc

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