source: gsdl/trunk/perllib/plugins/PagedImagePlugin.pm@ 16009

Last change on this file since 16009 was 16009, checked in by kjdon, 16 years ago

changed some string keys, added a check for imagemagick before calling generate_images

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 20.5 KB
Line 
1###########################################################################
2#
3# PagedImagePlugin.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# PagedImagePlugin
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.txt">
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 '-create_thumbnail' option.
116# To have it create medium size images for display, use the '-create_screenview'
117# option. As usual, running
118# 'perl -S pluginfo.pl PagedImagePlugin' 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 -create_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 PagedImagePlugin;
135
136use ReadXMLFile;
137use ReadTextFile;
138use ImageConverter;
139
140use strict;
141no strict 'refs'; # allow filehandles to be variables and viceversa
142
143sub BEGIN {
144 @PagedImagePlugin::ISA = ('ReadXMLFile', 'ReadTextFile', 'ImageConverter');
145}
146
147my $type_list =
148 [ { 'name' => "paged",
149 'desc' => "{PagedImagePlugin.documenttype.paged}" },
150 { 'name' => "hierarchy",
151 'desc' => "{PagedImagePlugin.documenttype.hierarchy}" } ];
152
153my $arguments =
154 [ { 'name' => "process_exp",
155 'desc' => "{BasePlugin.process_exp}",
156 'type' => "string",
157 'deft' => &get_default_process_exp(),
158 'reqd' => "no" },
159 { 'name' => "block_exp",
160 'desc' => "{BasePlugin.block_exp}",
161 'type' => "string",
162 'deft' => &get_default_block_exp(),
163 'reqd' => "no" },
164 { 'name' => "title_sub",
165 'desc' => "{HTMLPlugin.title_sub}",
166 'type' => "string",
167 'deft' => "" },
168 { 'name' => "headerpage",
169 'desc' => "{PagedImagePlugin.headerpage}",
170 'type' => "flag",
171 'reqd' => "no" },
172 { 'name' => "documenttype",
173 'desc' => "{PagedImagePlugin.documenttype}",
174 'type' => "enum",
175 'list' => $type_list,
176 'deft' => "paged",
177 'reqd' => "no" } ];
178
179
180my $options = { 'name' => "PagedImagePlugin",
181 'desc' => "{PagedImagePlugin.desc}",
182 'abstract' => "no",
183 'inherits' => "yes",
184 'args' => $arguments };
185
186sub new {
187 my ($class) = shift (@_);
188 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
189 push(@$pluginlist, $class);
190
191 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
192 push(@{$hashArgOptLists->{"OptList"}},$options);
193
194 new ImageConverter($pluginlist, $inputargs, $hashArgOptLists);
195 new ReadTextFile($pluginlist, $inputargs, $hashArgOptLists, 1);
196 my $self = new ReadXMLFile($pluginlist, $inputargs, $hashArgOptLists);
197
198 return bless $self, $class;
199}
200
201
202sub init {
203 my $self = shift (@_);
204 my ($verbosity, $outhandle, $failhandle) = @_;
205
206 $self->SUPER::init(@_);
207 $self->ImageConverter::init();
208}
209
210sub get_default_process_exp {
211 my $self = shift (@_);
212
213 return q^\.item$^;
214}
215
216sub get_doctype {
217 my $self = shift(@_);
218
219 return "PagedDocument";
220}
221
222
223# want to block everything except the .item ones
224# but instead we will block images and txt files
225sub get_default_block_exp {
226 my $self = shift (@_);
227
228 return q^(?i)(\.jpe?g|\.gif|\.png|\.tif?f|\.te?xt|\.html?|~)$^
229}
230
231# we want to use BasePlugin's read, not ReadXMLFile's
232sub read
233{
234 my $self = shift (@_);
235 $self->BasePlugin::read(@_);
236}
237
238
239sub read_into_doc_obj {
240 my $self = shift (@_);
241 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
242 my $outhandle = $self->{'outhandle'};
243
244 my ($filename_full_path, $filename_no_path) = $self->get_full_filenames($base_dir, $file);
245
246 print $outhandle "PagedImagePlugin processing \"$filename_full_path\"\n"
247 if $self->{'verbosity'} > 1;
248 print STDERR "<Processing n='$file' p='PagedImagePlugin'>\n" if ($gli);
249
250
251 # here we need to decide if we have an old text .item file, or a new xml
252 # .item file
253 my $xml_version = $self->is_xml_item_file($filename_full_path);
254
255 $self->tidy_item_file($filename_full_path);
256
257 my $doc_obj;
258 if ($xml_version) {
259 # careful checking needed here!! are we using local xml handlers or super ones
260 $self->ReadXMLFile::read($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli);
261 $doc_obj = $self->{'doc_obj'};
262 } else {
263 my ($dir);
264 ($dir, $file) = $filename_full_path =~ /^(.*?)([^\/\\]*)$/;
265
266 #process the .item file
267 $doc_obj = $self->process_item($filename_full_path, $dir, $file, $processor);
268
269 }
270
271 my $section = $doc_obj->get_top_section();
272
273 $doc_obj->add_utf8_metadata($section, "Plugin", "$self->{'plugin_type'}");
274 $doc_obj->add_metadata($section, "FileFormat", "PagedImage");
275
276 # include any metadata passed in from previous plugins
277 # note that this metadata is associated with the top level section
278 $self->add_associated_files($doc_obj, $filename_full_path);
279 $self->extra_metadata ($doc_obj, $section, $metadata);
280 $self->auto_extract_metadata ($doc_obj);
281
282 # if we haven't found any Title so far, assign one
283 $self->title_fallback($doc_obj,$section,$filename_no_path);
284
285 $self->add_OID($doc_obj);
286 return (1,$doc_obj);
287}
288
289# for now, the test is if the first non-empty line is <PagedDocument>, then its xml
290sub is_xml_item_file {
291 my $self = shift(@_);
292 my ($filename) = @_;
293
294 my $xml_version = 0;
295 open (ITEMFILE, $filename) || die "couldn't open $filename\n";
296
297 my $line = "";
298 my $num = 0;
299 $line = <ITEMFILE>;
300 while ($line !~ /\w/) {
301 $line = <ITEMFILE>;
302 }
303 chomp $line;
304 if ($line =~ /<PagedDocument/) {
305 $xml_version = 1;
306 }
307 close ITEMFILE;
308 return $xml_version;
309}
310
311sub tidy_item_file {
312 my $self = shift(@_);
313 my ($filename) = @_;
314
315 open (ITEMFILE, $filename) || die "couldn't open $filename\n";
316 my $backup_filename = "backup.item";
317 open (BACKUP,">$backup_filename")|| die "couldn't write to $backup_filename\n";
318 my $line = "";
319 $line = <ITEMFILE>;
320 $line =~ s/^\xEF\xBB\xBF//; # strip BOM
321 $line =~ s/\x0B+//ig;
322 $line =~ s/&/&amp;/g;
323 print BACKUP ($line);
324 #Tidy up the item file some metadata title contains \vt-vertical tab
325 while ($line = <ITEMFILE>) {
326 $line =~ s/\x0B+//ig;
327 $line =~ s/&/&amp;/g;
328 print BACKUP ($line);
329 }
330 close ITEMFILE;
331 close BACKUP;
332 &File::Copy::copy ($backup_filename, $filename);
333 &util::rm($backup_filename);
334
335}
336
337sub rotate_image {
338 my $self = shift (@_);
339 my ($filename_full_path) = @_;
340
341 my ($this_filetype) = $filename_full_path =~ /\.([^\.]*)$/;
342 my $result = $self->convert($filename_full_path, $this_filetype, "-rotate 180", "ROTATE");
343 my ($new_filename) = ($result =~ /=>(.*\.$this_filetype)/);
344 if (-e "$new_filename") {
345 return $new_filename;
346 }
347 # somethings gone wrong
348 return $filename_full_path;
349
350}
351
352sub process_image {
353 my $self = shift(@_);
354 my ($filename_full_path, $filename_no_path, $doc_obj, $section, $rotate) = @_;
355 # do rotation
356 if ($rotate eq "r") {
357 # check the filenames
358 return 0 if ($filename_no_path eq "" || !-f $filename_full_path);
359
360 # we get a new temporary file which is rotated
361 $filename_full_path = $self->rotate_image($filename_full_path);
362 }
363
364 # do generate images
365 my $result = 0;
366 if ($self->{'image_conversion_available'} == 1) {
367 $result = $self->generate_images($filename_full_path, $filename_no_path, $doc_obj, $section);
368 }
369 #overwrite one set in ImageConverter
370 $doc_obj->set_metadata_element ($section, "FileFormat", "PagedImage");
371 return $result;
372}
373
374
375sub xml_start_tag {
376 my $self = shift(@_);
377 my ($expat, $element) = @_;
378 $self->{'element'} = $element;
379
380 my $doc_obj = $self->{'doc_obj'};
381 if ($element eq "PagedDocument") {
382 $self->{'current_section'} = $doc_obj->get_top_section();
383 } elsif ($element eq "PageGroup" || $element eq "Page") {
384 # create a new section as a child
385 $self->{'current_section'} = $doc_obj->insert_section($doc_obj->get_end_child($self->{'current_section'}));
386 $self->{'num_pages'}++;
387 # assign pagenum as what??
388 my $pagenum = $_{'pagenum'}; #TODO!!
389 if (defined $pagenum) {
390 $doc_obj->set_utf8_metadata_element($self->{'current_section'}, 'PageNum', $pagenum);
391 }
392 my ($imgfile) = $_{'imgfile'};
393 if (defined $imgfile) {
394 $self->process_image($self->{'base_dir'}.$imgfile, $imgfile, $doc_obj, $self->{'current_section'});
395 }
396 my ($txtfile) = $_{'txtfile'};
397 if (defined($txtfile)&& $txtfile ne "") {
398 $self->process_text ($self->{'base_dir'}.$txtfile, $txtfile, $doc_obj, $self->{'current_section'});
399 } else {
400 $self->add_dummy_text($doc_obj, $self->{'current_section'});
401 }
402 } elsif ($element eq "Metadata") {
403 $self->{'metadata_name'} = $_{'name'};
404 }
405}
406
407sub xml_end_tag {
408 my $self = shift(@_);
409 my ($expat, $element) = @_;
410
411 my $doc_obj = $self->{'doc_obj'};
412 if ($element eq "Page" || $element eq "PageGroup") {
413 # if Title hasn't been assigned, set PageNum as Title
414 if (!defined $doc_obj->get_metadata_element ($self->{'current_section'}, "Title") && defined $doc_obj->get_metadata_element ($self->{'current_section'}, "PageNum" )) {
415 $doc_obj->add_utf8_metadata ($self->{'current_section'}, "Title", $doc_obj->get_metadata_element ($self->{'current_section'}, "PageNum" ));
416 }
417 # move the current section back to the parent
418 $self->{'current_section'} = $doc_obj->get_parent_section($self->{'current_section'});
419 } elsif ($element eq "Metadata") {
420
421 $doc_obj->add_utf8_metadata ($self->{'current_section'}, $self->{'metadata_name'}, $self->{'metadata_value'});
422 $self->{'metadata_name'} = "";
423 $self->{'metadata_value'} = "";
424
425 }
426 # otherwise we ignore the end tag
427}
428
429
430sub xml_text {
431 my $self = shift(@_);
432 my ($expat) = @_;
433
434 if ($self->{'element'} eq "Metadata" && $self->{'metadata_name'}) {
435 $self->{'metadata_value'} .= $_;
436 }
437}
438
439sub xml_doctype {
440}
441
442sub open_document {
443 my $self = shift(@_);
444
445 # create a new document
446 $self->{'doc_obj'} = new doc ($self->{'filename'}, "indexed_doc");
447 # TODO is file filenmae_no_path??
448 $self->set_initial_doc_fields($self->{'doc_obj'}, $self->{'file'}, $self->{'processor'});
449
450 my ($dir, $file) = $self->{'filename'} =~ /^(.*?)([^\/\\]*)$/;
451 $self->{'base_dir'} = $dir;
452 $self->{'num_pages'} = 0;
453
454}
455
456sub close_document {
457 my $self = shift(@_);
458 my $doc_obj = $self->{'doc_obj'};
459
460 # add numpages metadata
461 $doc_obj->set_utf8_metadata_element ($doc_obj->get_top_section(), 'NumPages', $self->{'num_pages'});
462
463
464}
465
466
467sub set_initial_doc_fields {
468 my $self = shift(@_);
469 my ($doc_obj, $filename_no_path, $processor) = @_;
470
471 $doc_obj->set_OIDtype ($processor->{'OIDtype'}, $processor->{'OIDmetadata'});
472 my $topsection = $doc_obj->get_top_section();
473
474 if ($self->{'documenttype'} eq 'paged') {
475 # set the gsdlthistype metadata to Paged - this ensures this document will
476 # be treated as a Paged doc, even if Titles are not numeric
477 $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Paged");
478 } else {
479 $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Hierarchy");
480 }
481
482 $self->set_Source_metadata($doc_obj, $filename_no_path);
483
484 # if we want a header page, we need to add some text into the top section, otherwise this section will become invisible
485 if ($self->{'headerpage'}) {
486 $self->add_dummy_text($doc_obj, $topsection);
487 }
488
489
490}
491
492
493sub process_item {
494 my $self = shift (@_);
495 my ($filename_full_path, $dir, $filename_no_path, $processor) = @_;
496
497 my $doc_obj = new doc ($filename_full_path, "indexed_doc");
498 $self->set_initial_doc_fields($doc_obj, $filename_no_path, $processor);
499 my $topsection = $doc_obj->get_top_section();
500 open (ITEMFILE, $filename_full_path) || die "couldn't open $filename_full_path\n";
501 my $line = "";
502 my $num = 0;
503 while (defined ($line = <ITEMFILE>)) {
504 next unless $line =~ /\w/;
505 chomp $line;
506 next if $line =~ /^#/; # ignore comment lines
507 if ($line =~ /^<([^>]*)>\s*(.*?)\s*$/) {
508 $doc_obj->set_utf8_metadata_element ($topsection, $1, $2);
509 #$meta->{$1} = $2;
510 } else {
511 $num++;
512 # line should be like page:imagefilename:textfilename:r - the r is optional -> means rotate the image 180 deg
513 $line =~ s/^\s+//; #remove space at the front
514 $line =~ s/\s+$//; #remove space at the end
515 my ($pagenum, $imgname, $txtname, $rotate) = split /:/, $line;
516
517 # create a new section for each image file
518 my $cursection = $doc_obj->insert_section($doc_obj->get_end_child($topsection));
519 # the page number becomes the Title
520 $doc_obj->set_utf8_metadata_element($cursection, 'Title', $pagenum);
521
522 # process the image for this page if there is one
523 if (defined $imgname && $imgname ne "") {
524 my $result1 = $self->process_image($dir.$imgname, $imgname, $doc_obj, $cursection, $rotate);
525
526 if (!defined $result1)
527 {
528 print "PagedImagePlugin: couldn't process image \"$dir.$imgname\" for item \"$filename_full_path\"\n";
529 }
530 }
531 # process the text file if one is there
532 if (defined $txtname && $txtname ne "") {
533 my $result2 = $self->process_text ($dir.$txtname, $txtname, $doc_obj, $cursection);
534
535 if (!defined $result2) {
536 print "PagedImagePlugin: couldn't process text file \"$dir.$txtname\" for item \"$filename_full_path\"\n";
537 $self->add_dummy_text($doc_obj, $cursection);
538 }
539 } else {
540 # otherwise add in some dummy text
541 $self->add_dummy_text($doc_obj, $cursection);
542 }
543 }
544 }
545
546 close ITEMFILE;
547
548 # add numpages metadata
549 $doc_obj->set_utf8_metadata_element ($topsection, 'NumPages', "$num");
550 return $doc_obj;
551}
552
553sub process_text {
554 my $self = shift (@_);
555 my ($filename_full_path, $file, $doc_obj, $cursection) = @_;
556
557 # check that the text file exists!!
558 if (!-f $filename_full_path) {
559 print "PagedImagePlugin: ERROR: File $filename_full_path does not exist, skipping\n";
560 return 0;
561 }
562
563 # Do encoding stuff
564 my ($language, $encoding) = $self->textcat_get_language_encoding ($filename_full_path);
565
566 my $text="";
567 &ReadTextFile::read_file($self, $filename_full_path, $encoding, $language, \$text);
568 if (!length ($text)) {
569 # It's a bit unusual but not out of the question to have no text, so just give a warning
570 print "PagedImagePlugin: WARNING: $filename_full_path contains no text\n";
571 }
572
573 # we need to escape the escape character, or else mg will convert into
574 # eg literal newlines, instead of leaving the text as '\n'
575 $text =~ s/\\/\\\\/g; # macro language
576 $text =~ s/_/\\_/g; # macro language
577
578
579 if ($text =~ m/<html.*?>\s*<head.*?>.*<\/head>\s*<body.*?>(.*)<\/body>\s*<\/html>\s*$/s) {
580 # looks like HTML input
581 # no need to escape < and > or put in <pre> tags
582
583 $text = $1;
584
585 # insert preformat tags and add text to document object
586 $doc_obj->add_utf8_text($cursection, "$text");
587 }
588 else {
589 $text =~ s/</&lt;/g;
590 $text =~ s/>/&gt;/g;
591
592 # insert preformat tags and add text to document object
593 $doc_obj->add_utf8_text($cursection, "<pre>\n$text\n</pre>");
594 }
595
596
597 return 1;
598}
599
600
601sub clean_up_after_doc_obj_processing {
602 my $self = shift(@_);
603
604 $self->ImageConverter::clean_up_temporary_files();
605}
606
6071;
Note: See TracBrowser for help on using the repository browser.