source: main/tags/2.71/gsdl/perllib/plugins/PagedImgPlug.pm@ 25326

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

check for a byte order marker and strip it

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