source: main/trunk/greenstone2/perllib/plugins/HathiTrustMETSPlugin.pm

Last change on this file was 38801, checked in by kjdon, 2 months ago

standardising on top_section rather than section or topsection when we have a top section

  • Property svn:executable set to *
File size: 20.0 KB
Line 
1###########################################################################
2#
3# HathiTrustMETSPlugin.pm -- plugin for sets of HathiTrust METS OCR'd
4# text that make up a document
5#
6# A component of the Greenstone digital library software
7# from the New Zealand Digital Library Project at the
8# University of Waikato, New Zealand.
9#
10# Copyright (C) 1999 New Zealand Digital Library Project
11#
12# This program is free software; you can redistribute it and/or modify
13# it under the terms of the GNU General Public License as published by
14# the Free Software Foundation; either version 2 of the License, or
15# (at your option) any later version.
16#
17# This program is distributed in the hope that it will be useful,
18# but WITHOUT ANY WARRANTY; without even the implied warranty of
19# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20# GNU General Public License for more details.
21#
22# You should have received a copy of the GNU General Public License
23# along with this program; if not, write to the Free Software
24# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25#
26###########################################################################
27
28# HathiTrustMETSPlugin
29# processes HathiTrust METS files that are accompanied with page-by-page
30# OCR'd txt files
31#
32# All the supplemetary text files should be in a subfolder of the same
33# name as the METS file
34#
35# As usual, running
36# 'perl -S pluginfo.pl HathiTrustMETSPlugin' will list all the options.
37
38
39package HathiTrustMETSPlugin;
40
41use Encode;
42use ReadXMLFile;
43use ReadTextFile;
44# We don't currently work with the scanned image from HathiTrust METS
45# but leave it in for future proofing
46use ImageConverter;
47use MetadataRead;
48
49use JSON;
50
51use strict;
52no strict 'refs'; # allow filehandles to be variables and viceversa
53
54sub BEGIN {
55 @HathiTrustMETSPlugin::ISA = ('MetadataRead', 'ReadXMLFile', 'ReadTextFile', 'ImageConverter'
56 );
57}
58
59# One day HathiTrust might give more than page structure
60my $gs2_type_list =
61 [
62# { 'name' => "auto",
63# 'desc' => "{PagedImagePlugin.documenttype.auto2}" },
64# { 'name' => "paged",
65# 'desc' => "{PagedImagePlugin.documenttype.paged2}" },
66 { 'name' => "hierarchy",
67 'desc' => "{PagedImagePlugin.documenttype.hierarchy}" }
68 ];
69
70my $gs3_type_list =
71 [
72# { 'name' => "auto",
73# 'desc' => "{PagedImagePlugin.documenttype.auto3}" },
74# { 'name' => "paged",
75# 'desc' => "{PagedImagePlugin.documenttype.paged3}" },
76 { 'name' => "hierarchy",
77 'desc' => "{PagedImagePlugin.documenttype.hierarchy}" }
78# { 'name' => "pagedhierarchy",
79# 'desc' => "{PagedImagePlugin.documenttype.pagedhierarchy}" }
80 ];
81
82my $arguments =
83 [ { 'name' => "process_exp",
84 'desc' => "{BaseImporter.process_exp}",
85 'type' => "string",
86 'deft' => &get_default_process_exp(),
87 'reqd' => "no" },
88 { 'name' => "title_sub",
89 'desc' => "{HTMLPlugin.title_sub}",
90 'type' => "string",
91 'deft' => "" },
92 { 'name' => "headerpage",
93 'desc' => "{HathiTrustMETSPlugin.headerpage}",
94 'type' => "flag",
95 'reqd' => "no" },
96 {'name' => "processing_tmp_files",
97 'desc' => "{BaseImporter.processing_tmp_files}",
98 'type' => "flag",
99 'hiddengli' => "yes"}
100 ];
101
102my $doc_type_opt = { 'name' => "documenttype",
103 'desc' => "{PagedImagePlugin.documenttype}",
104 'type' => "enum",
105 'deft' => "hierarchy",
106 'reqd' => "no" };
107
108my $options = { 'name' => "HathiTrustMETSPlugin",
109 'desc' => "{HathiTrustMETSPlugin.desc}",
110 'abstract' => "no",
111 'inherits' => "yes",
112 'args' => $arguments };
113
114sub new {
115 my ($class) = shift (@_);
116 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
117 push(@$pluginlist, $class);
118
119 push(@{$hashArgOptLists->{"OptList"}},$options);
120
121 my $imc_self = new ImageConverter($pluginlist, $inputargs, $hashArgOptLists);
122
123 # we can use this plugin to check gs3 version
124 if ($imc_self->{'gs_version'} eq "3") {
125 $doc_type_opt->{'list'} = $gs3_type_list;
126 }
127 else {
128 $doc_type_opt->{'list'} = $gs2_type_list;
129 }
130 push(@$arguments,$doc_type_opt);
131 # now we add the args to the list for parsing
132 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
133
134 my $rtf_self = new ReadTextFile($pluginlist, $inputargs, $hashArgOptLists, 1);
135 my $rxf_self = new ReadXMLFile($pluginlist, $inputargs, $hashArgOptLists);
136
137 my $self = BaseImporter::merge_inheritance($imc_self,$rtf_self,$rxf_self);
138
139 # Update $self used by XML::Parser so it finds callback functions
140 # such as start_document here and not in ReadXMLFile (which is what
141 # $self was when new XML::Parser was done)
142 #
143 # If the $self returned by this constructor is the same as the one
144 # used in ReadXMLFile (e.g. in the GreenstoneXMLPlugin) then this step isn't necessary
145 #
146 # Consider embedding this type of assignment into merge_inheritance
147 # to help catch all cases?
148
149 $rxf_self->{'parser'}->{'PluginObj'} = $self;
150
151 return bless $self, $class;
152}
153
154
155sub init {
156 my $self = shift (@_);
157 my ($verbosity, $outhandle, $failhandle) = @_;
158
159 $self->SUPER::init(@_);
160 $self->ImageConverter::init();
161}
162
163sub begin {
164 my $self = shift (@_);
165 my ($pluginfo, $base_dir, $processor, $maxdocs) = @_;
166
167 $self->SUPER::begin(@_);
168 $self->ImageConverter::begin(@_);
169}
170
171sub get_default_process_exp {
172 my $self = shift (@_);
173
174 return q^\.mets.xml$^;
175}
176
177sub get_doctype {
178 my $self = shift(@_);
179
180 return "METS:mets";
181}
182
183
184# want to use BaseImporter's version of this, not ReadXMLFile's
185sub can_process_this_file {
186 my $self = shift(@_);
187 return $self->BaseImporter::can_process_this_file(@_);
188}
189
190# instead of a block exp, now we scan the file and record all text and img files mentioned there for blocking.
191sub store_block_files
192{
193 my $self = shift (@_);
194 my ($filename_full_path, $block_hash) = @_;
195
196 # do we need to do this?
197 # does BOM interfere just with XML parsing? In that case don't need it here
198 # if we do it here, we are modifying the file before we have worked out if
199 # its new or not, so it will always be reimported.
200 #$self->tidy_item_file($filename_full_path);
201
202 my ($dir, $file) = $filename_full_path =~ /^(.*?)([^\/\\]*)$/;
203
204 # do something
205 $self->scan_xml_for_files_to_block($filename_full_path, $dir, $block_hash);
206
207}
208
209# we want to use BaseImporter's read, not ReadXMLFile's
210sub read
211{
212 my $self = shift (@_);
213
214 $self->BaseImporter::read(@_);
215}
216
217
218
219sub read_into_doc_obj {
220 my $self = shift (@_);
221 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
222 my $outhandle = $self->{'outhandle'};
223 my $verbosity = $self->{'verbosity'};
224
225 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
226
227 print $outhandle "HathiTrustMETSPlugin processing \"$filename_full_path\"\n"
228 if $verbosity > 1;
229 print STDERR "<Processing n='$file' p='HathiTrustMETSPlugin'>\n" if ($gli);
230
231## $self->{'MaxImageWidth'} = 0;
232## $self->{'MaxImageHeight'} = 0;
233
234
235 ##$self->tidy_item_file($filename_full_path);
236
237 # careful checking needed here!! are we using local xml handlers or super ones
238 $self->ReadXMLFile::read($pluginfo, $base_dir, $file, $block_hash, $metadata, $processor, $maxdocs, $total_count, $gli);
239 my $doc_obj = $self->{'doc_obj'};
240
241
242 my $top_section = $doc_obj->get_top_section();
243
244 $doc_obj->add_utf8_metadata($top_section, "Plugin", "$self->{'plugin_type'}");
245 $doc_obj->add_metadata($top_section, "FileFormat", "HathiTrustMETS");
246
247 my $file_dirname = &File::Basename::dirname($file);
248 $doc_obj->add_utf8_metadata($top_section, "SourceDirectory", $file_dirname);
249
250 # include any metadata passed in from previous plugins
251 # note that this metadata is associated with the top level section
252 $self->add_associated_files($doc_obj, $filename_full_path);
253 $self->extra_metadata ($doc_obj, $top_section, $metadata);
254 $self->auto_extract_metadata ($doc_obj);
255 $self->plugin_specific_process($base_dir, $file, $doc_obj, $gli);
256 # if we haven't found any Title so far, assign one
257 $self->title_fallback($doc_obj,$top_section,$filename_no_path);
258
259 if ($self->{'metadata_mapping_rules'}) {
260 $self->apply_metadata_mapping_file($doc_obj);
261 }
262
263 $self->add_OID($doc_obj);
264
265 $self->post_process_doc_obj($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli);
266 return (1,$doc_obj);
267}
268
269
270sub parse_aux_json_metadata {
271 my $self = shift(@_);
272 my ($base_dir, $file, $doc_obj, $gli) = @_;
273
274 my ($filename_full_path, $filename_no_path) = &util::get_full_filenames($base_dir, $file);
275
276 my $top_section = $doc_obj->get_top_section();
277
278 my $json_metadata_filename = $filename_full_path;
279 $json_metadata_filename =~ s/\.mets.xml$/.json/;
280
281 my $json_text = "";
282 $self->ReadTextFile::read_file($json_metadata_filename,"utf8",undef,\$json_text);
283
284 my $json_rec = decode_json $json_text;
285 my $records = $json_rec->{'records'};
286 my @keys = keys %{$records};
287
288 my $key = shift @keys; # there should only be one
289 my $record = $records->{$key};
290
291 my @md_fields = ( "recordURL", "titles", "isbns", "issns", "oclcs", "lccns", "publishDates" );
292
293 foreach my $md_field (@md_fields) {
294 my $value_array = $record->{$md_field};
295
296 my $md_name = $md_field;
297 $md_name =~ s/s$//;
298
299 foreach my $md_value (@$value_array) {
300
301 if ($md_name eq "title") {
302 $doc_obj->set_utf8_metadata_element ($top_section, "Title", $md_value);
303 $doc_obj->set_utf8_metadata_element ($top_section, "dc.Title", $md_value);
304 }
305 else {
306 $doc_obj->set_utf8_metadata_element ($top_section, $md_name, $md_value);
307 }
308 }
309 }
310
311 my $htid = $json_rec->{'items'}->[0]->{'htid'};
312 my $docName = $htid;
313 my $docNameIE = $htid;
314 $docNameIE =~ s/^.*?\.//;
315
316 $doc_obj->set_utf8_metadata_element ($top_section, "docName", $docName);
317 $doc_obj->set_utf8_metadata_element ($top_section, "docNameIE", $docNameIE);
318
319}
320
321
322# override this for an inheriting plugin to add extra metadata etc
323sub plugin_specific_process {
324 my $self = shift(@_);
325 my ($base_dir, $file, $doc_obj, $gli) = @_;
326
327 $self->parse_aux_json_metadata($base_dir,$file,$doc_obj,$gli);
328}
329
330# sub tidy_item_file {
331# ... see PagedImagePlugin
332# }
333
334# sub rotate_image {
335# ... see PagedImagePlugin
336# }
337
338# sub process_image {
339# ... see PagedImagePlugin
340# }
341
342
343
344sub xml_start_tag {
345 my $self = shift(@_);
346 my ($expat, $element) = @_;
347 $self->{'element'} = $element;
348
349 my $doc_obj = $self->{'doc_obj'};
350 if ($element eq "METS:mets") {
351 $self->{'current_section'} = $doc_obj->get_top_section();
352# } elsif ($element eq "PageGroup" || $element eq "Page") {
353## if ($element eq "PageGroup") {
354## $self->{'has_internal_structure'} = 1;
355 }
356 elsif (($element eq "METS:FLocat") && ($_{'xlink:href'} =~ m/\.txt$/)) {
357 # e.g. <METS:FLocat LOCTYPE="OTHER" OTHERLOCTYPE="SYSTEM" xlink:href="00000000.txt"/>
358
359 # create a new section as a child
360 $self->{'current_section'} = $doc_obj->insert_section($doc_obj->get_end_child($self->{'current_section'}));
361 $self->{'num_pages'}++;
362 # assign pagenum as ... what?? => use page sequence number
363 my $txtfile = $_{'xlink:href'};
364 my ($pagenum) = ($txtfile =~ m/^(\d+)/);
365
366 if (defined $pagenum) {
367 my $pagenum_int = int($pagenum);
368 $doc_obj->set_utf8_metadata_element($self->{'current_section'}, "Title", "Page $pagenum_int");
369 }
370## my ($imgfile) = $_{'imgfile'};
371## if (defined $imgfile) {
372## # *****
373## # What about support for rotate image (e.g. old ':r' notation)?
374## $self->process_image($self->{'xml_file_dir'}.$imgfile, $imgfile, $doc_obj, $self->{'current_section'});
375## }
376
377## my ($txtfile) = $_{'txtfile'};
378 if (defined($txtfile)&& $txtfile ne "") {
379 my $full_txt_filename = &FileUtils::filenameConcatenate($self->{'xml_file_dir'},$txtfile);
380 $self->process_text ($full_txt_filename, $txtfile, $doc_obj, $self->{'current_section'});
381 } else {
382 $self->add_dummy_text($doc_obj, $self->{'current_section'});
383 }
384 }
385## elsif ($element eq "Metadata") {
386## $self->{'metadata_name'} = $_{'name'};
387## }
388}
389
390sub xml_end_tag {
391 my $self = shift(@_);
392 my ($expat, $element) = @_;
393
394 my $doc_obj = $self->{'doc_obj'};
395## if ($element eq "Page" || $element eq "PageGroup") {
396 if (($element eq "METS:FLocat") && ($_{'xlink:href'} =~ m/\.txt$/)) {
397 # if Title hasn't been assigned, set PageNum as Title
398 if (!defined $doc_obj->get_metadata_element ($self->{'current_section'}, "Title") && defined $doc_obj->get_metadata_element ($self->{'current_section'}, "PageNum" )) {
399 $doc_obj->add_utf8_metadata ($self->{'current_section'}, "Title", $doc_obj->get_metadata_element ($self->{'current_section'}, "PageNum" ));
400 }
401 # move the current section back to the parent
402 $self->{'current_section'} = $doc_obj->get_parent_section($self->{'current_section'});
403 } elsif ($element eq "Metadata") {
404
405 # text read in by XML::Parser is in Perl's binary byte value
406 # form ... need to explicitly make it UTF-8
407 my $meta_name = decode("utf-8",$self->{'metadata_name'});
408 my $metadata_value = decode("utf-8",$self->{'metadata_value'});
409
410 if ($meta_name =~ /\./) {
411 $meta_name = "ex.$meta_name";
412 }
413
414 $doc_obj->add_utf8_metadata ($self->{'current_section'}, $meta_name, $metadata_value);
415 $self->{'metadata_name'} = "";
416 $self->{'metadata_value'} = "";
417
418 }
419 # otherwise we ignore the end tag
420}
421
422
423sub xml_text {
424 my $self = shift(@_);
425 my ($expat) = @_;
426
427 if ($self->{'element'} eq "Metadata" && $self->{'metadata_name'}) {
428 $self->{'metadata_value'} .= $_;
429 }
430}
431
432sub xml_doctype {
433}
434
435sub open_document {
436 my $self = shift(@_);
437
438 # create a new document
439 $self->{'doc_obj'} = new doc ($self->{'filename'}, "indexed_doc", $self->{'file_rename_method'});
440 # TODO is file filenmae_no_path??
441 $self->set_initial_doc_fields($self->{'doc_obj'}, $self->{'filename'}, $self->{'processor'}, $self->{'metadata'});
442
443## my ($dir, $file) = $self->{'filename'} =~ /^(.*?)([^\/\\]*)$/;
444 my ($dir, $file_ext) = $self->{'filename'} =~ /^(.*?)(\.mets\.xml)$/;
445
446 $self->{'xml_file_dir'} = $dir;
447 $self->{'num_pages'} = 0;
448## $self->{'has_internal_structure'} = 0;
449
450}
451
452sub close_document {
453 my $self = shift(@_);
454 my $doc_obj = $self->{'doc_obj'};
455
456 my $topsection = $doc_obj->get_top_section();
457
458 # add numpages metadata
459 $doc_obj->set_utf8_metadata_element ($topsection, 'NumPages', $self->{'num_pages'}); # ##### !!!!
460
461 # set the document type
462 my $final_doc_type = "";
463## if ($self->{'documenttype'} eq "auto") {
464### if ($self->{'has_internal_structure'}) {
465### if ($self->{'gs_version'} eq "3") {
466### $final_doc_type = "pagedhierarchy";
467### }
468### else {
469### $final_doc_type = "hierarchy";
470### }
471### } else {
472### $final_doc_type = "paged";
473### }
474### } else {
475## # set to what doc type option was set to
476## $final_doc_type = $self->{'documenttype'};
477## }
478# $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", $final_doc_type); # #### !!!!!
479 ### capiatalisation????
480# if ($self->{'documenttype'} eq 'paged') {
481 # set the gsdlthistype metadata to Paged - this ensures this document will
482 # be treated as a Paged doc, even if Titles are not numeric
483# $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Paged");
484# } else {
485# $doc_obj->set_utf8_metadata_element ($topsection, "gsdlthistype", "Hierarchy");
486# }
487
488## $doc_obj->set_utf8_metadata_element($topsection,"MaxImageWidth",$self->{'MaxImageWidth'});
489## $doc_obj->set_utf8_metadata_element($topsection,"MaxImageHeight",$self->{'MaxImageHeight'});
490## $self->{'MaxImageWidth'} = undef;
491## $self->{'MaxImageHeight'} = undef;
492
493}
494
495
496sub set_initial_doc_fields {
497 my $self = shift(@_);
498 my ($doc_obj, $filename_full_path, $processor, $metadata) = @_;
499
500 my $topsection = $doc_obj->get_top_section();
501
502 my $plugin_filename_encoding = $self->{'filename_encoding'};
503 my $filename_encoding = $self->deduce_filename_encoding($filename_full_path,$metadata,$plugin_filename_encoding);
504 $self->set_Source_metadata($doc_obj, $filename_full_path, $filename_encoding);
505
506 # if we want a header page, we need to add some text into the top section, otherwise this section will become invisible
507 if ($self->{'headerpage'}) {
508 $self->add_dummy_text($doc_obj, $topsection);
509 }
510}
511
512sub scan_xml_for_files_to_block
513{
514 my $self = shift (@_);
515 my ($filename_full_path, $dir, $block_hash) = @_;
516
517 my ($file_root) = ($filename_full_path =~ m/^(.*)\.mets\.xml$/);
518
519 $self->block_raw_filename($block_hash,"$file_root.zip");
520 $self->block_raw_filename($block_hash,"$file_root.json");
521
522 my $page_dir = $file_root;
523
524 open (METSFILE, $filename_full_path) || die "couldn't open $filename_full_path to work out which files to block\n";
525 my $line = "";
526 while (defined ($line = <METSFILE>)) {
527 next unless $line =~ /\w/;
528
529 # Exaple of what we are looking for
530 # <METS:FLocat LOCTYPE="OTHER" OTHERLOCTYPE="SYSTEM" xlink:href="00000000.txt"/>
531
532 if ($line =~ /xlink:href=\"([^\"]+)\"/) {
533 my $txt_filename = &FileUtils::filenameConcatenate($page_dir,$1);
534 my $topics_filename = $txt_filename . ".topics";
535 $self->block_raw_filename($block_hash,$txt_filename);
536 $self->block_raw_filename($block_hash,$topics_filename);
537 }
538 }
539 close METSFILE;
540
541}
542
543
544sub process_text {
545 my $self = shift (@_);
546 my ($filename_full_path, $file, $doc_obj, $cursection) = @_;
547
548 # check that the text file exists!!
549 if (!-f $filename_full_path) {
550 print "HathiTrustMETSPlugin: ERROR: File $filename_full_path does not exist, skipping\n";
551 return 0;
552 }
553
554 # remember that this text file was one of our source files, but only
555 # if we are not processing a tmp file
556 if (!$self->{'processing_tmp_files'} ) {
557 $doc_obj->associate_source_file($filename_full_path);
558 }
559 # Do encoding stuff
560 my ($language, $encoding) = $self->textcat_get_language_encoding ($filename_full_path);
561
562 my $text="";
563 if ( -s $filename_full_path > 0 ) {
564 &ReadTextFile::read_file($self, $filename_full_path, $encoding, $language, \$text); # already decoded as utf8
565 }
566
567# HathiTrust often has empty files
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 "HathiTrustMETSPlugin: 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*$/is) {
580 # looks like HTML input
581 # no need to escape < and > or put in <pre> tags
582
583 $text = $1;
584
585 # 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 my $topics_filename = $filename_full_path . ".topics";
597 if ( -s $topics_filename > 0 ) {
598
599 my $topics_text = "";
600 $self->ReadTextFile::read_file($topics_filename,"utf8",undef,\$topics_text);
601
602 my @topics_array = split(/\|/,$topics_text);
603 foreach my $topic (@topics_array) {
604 if ($topic ne "") {
605 $doc_obj->set_utf8_metadata_element ($cursection, "concept", $topic);
606 }
607 }
608 }
609
610 return 1;
611}
612
613
614sub clean_up_after_doc_obj_processing {
615 my $self = shift(@_);
616
617 $self->ImageConverter::clean_up_temporary_files();
618}
619
6201;
Note: See TracBrowser for help on using the repository browser.