source: trunk/gsdl/perllib/classify/phind.pm@ 2481

Last change on this file since 2481 was 2481, checked in by kjm18, 23 years ago

changed mgpp system calls to use the new executable names

  • Property svn:keywords set to Author Date Id Revision
File size: 38.9 KB
Line 
1###########################################################################
2#
3# phind.pm -- the Phind classifier
4#
5# Copyright (C) 2000 Gordon W. Paynter
6# Copyright (C) 2000 New Zealand Digital Library Project
7#
8#
9# A component of the Greenstone digital library software
10# from the New Zealand Digital Library Project at the
11# University of Waikato, New Zealand.
12#
13# This program is free software; you can redistribute it and/or modify
14# it under the terms of the GNU General Public License as published by
15# the Free Software Foundation; either version 2 of the License, or
16# (at your option) any later version.
17#
18# This program is distributed in the hope that it will be useful,
19# but WITHOUT ANY WARRANTY; without even the implied warranty of
20# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21# GNU General Public License for more details.
22#
23# You should have received a copy of the GNU General Public License
24# along with this program; if not, write to the Free Software
25# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26#
27###########################################################################
28
29# The phind clasifier plugin.
30# Options are dexcribed in the print_usage function.
31# Type "classinfo.pl phind" at the command line for a summary.
32
33package phind;
34
35use BasClas;
36use util;
37use ghtml;
38use unicode;
39
40sub BEGIN {
41 @ISA = ('BasClas');
42}
43
44
45sub print_usage {
46 print STDERR "
47 usage: classify phind [options]
48
49 options:
50 -text Fields The text used to build the phrase hierarchy.
51 (default: 'section:Title,section:text')
52
53 -title Title The metadata field used to describe each document.
54 (default: 'Title')
55
56 -button Name The label for the classifier screen and button in
57 navigation bar.
58 (default: 'Phrase')
59
60 -language Regex Language or languages to use building hierarchy.
61 Languages are identified by two-letter country codes
62 like en (English), es (Spanish), and fr (French).
63 Language is a regular expression, so 'en|fr' (English or
64 French) and '..' (match any language) are valid.
65 (default: 'en'.)
66
67 -savephrases File If set, the phrase infomation will be stored in
68 the given file as text. It is probably a good idea
69 to use an absolute path.
70 (defualt: not set)
71
72 -suffixmode N The smode parameter to the phrase extraction program. A
73 value of 0 means that stopwords are ignored, and of 1
74 means that stopwords are used.
75 (default: 1)
76
77 -thesaurus Name Name of a thesaurus stored in phind format in the
78 collection's etc directory.
79 (default: not set)
80
81 -untidy Don't remove working files.
82
83"; }
84
85
86# Phrase delimiter symbols - these should be abstracted out someplace
87
88my $colstart = "COLLECTIONSTART";
89my $colend = "COLLECTIONEND";
90my $doclimit = "DOCUMENTLIMIT";
91my $senlimit = "SENTENCELIMIT";
92my @delimiters = ($colstart, $colend, $doclimit, $senlimit);
93
94
95# Create a new phind browser based on collect.cfg
96
97sub new {
98 my $class = shift (@_);
99 my $self = new BasClas($class, @_);
100
101 my $out = $self->{'outhandle'};
102
103
104 # Phind installation check
105 # The phind phrase browser is research software and is not installed
106 # by defualt. If the user attepts to use it we warn them that it's a
107 # bit dodgy, then tell them how to install it. If they can do that
108 # and get all the files in place, then we let them proceed.
109
110 print $out "Checking Phind phrase browser requirements...\n";
111
112 # Make sure we're not in windows
113 if ($ENV{'GSDLOS'} =~ /windows/i) {
114 print STDERR "Sorry - Phind currently only works under Unix";
115 exit(1);
116 }
117
118 # Ensure the Phind generate scripts are in place
119 my $file1 = &util::filename_cat($ENV{'GSDLHOME'}, "bin", $ENV{'GSDLOS'}, "suffix");
120 my $src = &util::filename_cat($ENV{'GSDLHOME'}, "src", "phind", "generate");
121
122 if (!(-e $file1)) {
123 print STDERR "The phind \"suffix\" program is not installed. ";
124 print STDERR "To install it, change to the directory\n";
125 print STDERR " $src\n";
126 print STDERR "and type \"make install-phind\".\n\n";
127 exit(1);
128 }
129
130 # Ensure the Phind CGI script is in place
131 $file1 = &util::filename_cat($ENV{'GSDLHOME'}, "cgi-bin", "phindcgi");
132 $src = &util::filename_cat($ENV{'GSDLHOME'}, "src", "phind", "host");
133
134 if (!(-e $file1)) {
135 print STDERR "The phind CGI program is not installed. ";
136 print STDERR "To install it, change to the directory\n";
137 print STDERR " $src\n";
138 print STDERR "and type \"make install-phind\".\n\n";
139 exit(1);
140 }
141
142 # Ensure the Phind Java applet is in place
143 $src = &util::filename_cat($ENV{'GSDLHOME'}, "src", "phind", "client");
144 $file1 = &util::filename_cat($src, "Phind.class");
145
146 if (!(-e $file1)) {
147 print STDERR "The phind Java classes are not compiled. ";
148 print STDERR "To compile them, change to the directory\n";
149 print STDERR " $src\n";
150 print STDERR "and use your Java compiler to compile Phind.java.\n";
151 print STDERR "(if you have Java 1.2 installed, type \"javac Phind.java\")\n\n";
152 exit(1);
153 }
154
155 # Parse classifier arguments
156 my $builddir = "";
157 if (!parsargv::parse(\@_,
158 q^text/.*/section:Title,section:text^, \$self->{'indexes'},
159 q^title/.*/Title^, \$self->{'titlefield'},
160 q^button/.*/Phrase^, \$self->{'buttonname'},
161 q^language/.*/en^, \$language,
162 q^builddir/.*/^, \$builddir,
163 q^savephrases/\d/0^, \$self->{'savephrases'},
164 q^suffixmode/\d/1^, \$self->{'suffixmode'},
165 q^thesaurus/.*/^, \$self->{'thesaurus'},
166 q^untidy^, \$self->{'untidy'},
167 "allow_extra_options")) {
168
169 print STDERR "\nIncorrect options passed to $class, check your collect.cfg file\n";
170 &print_usage();
171 die "\n";
172 }
173
174 # classifier information
175 $self->{'collection'} = $ENV{'GSDLCOLLECTION'};
176
177 # limit languages
178 $self->{'language_exp'} = $language;
179
180 # collection directories
181 $self->{'collectiondir'} = $ENV{'GSDLCOLLECTDIR'};
182 if (!$builddir) {
183 $builddir = &util::filename_cat($ENV{'GSDLCOLLECTDIR'}, "building");
184 }
185 $self->{'builddir'} = $builddir;
186
187 return bless $self, $class;
188}
189
190
191# Initialise the phind classifier
192
193sub init {
194 my $self = shift (@_);
195
196 # ensure we have a build directory
197 my $builddir = $self->{'builddir'};
198 die unless (-e "$builddir");
199
200 # create phind directory
201 my $phnumber = 1;
202 my $phinddir = &util::filename_cat($builddir, "phind1");
203 while (-e "$phinddir") {
204 $phnumber++;
205 $phinddir = &util::filename_cat($builddir, "phind$phnumber");
206 }
207 &util::mk_dir("$phinddir");
208 $self->{'phinddir'} = $phinddir;
209 $self->{'phindnumber'} = $phnumber;
210
211 # open filehandles for documents and text
212 my $clausefile = &util::filename_cat("$phinddir", "clauses");
213 &util::rm($clausefile) if (-e $clausefile);
214
215 my $txthandle = 'TEXT' . $phnumber;
216 open($txthandle, ">$clausefile") || die "Cannot open $clausefile: $!";
217 $self->{'txthandle'} = $txthandle;
218
219 my $docfile = &util::filename_cat("$phinddir", "docs.txt");
220 &util::rm($docfile) if (-e $docfile);
221
222 my $dochandle = 'DOC' . $phnumber;
223 open($dochandle, ">$docfile") || die "Cannot open $docfile: $!";
224 $self->{'dochandle'} = $dochandle;
225
226}
227
228
229# Classify each document.
230#
231# Each document is passed here in turn. The classifier extracts the
232# text of each and stores it in the clauses file. Document details are
233# stored in the docs.txt file.
234
235sub classify {
236 my $self = shift (@_);
237 my $doc_obj = shift @_;
238
239 my $verbosity = $self->{'verbosity'};
240 my $top_section = $doc_obj->get_top_section();
241
242 my $titlefield = $self->{'titlefield'};
243
244 my $title = $doc_obj->get_metadata_element ($top_section, $titlefield);
245 print "process: $title\n" if ($verbosity > 2);
246
247 # Only consider the file if it is in the correct language
248 my $doclanguage = $doc_obj->get_metadata_element ($top_section, "Language");
249 my $phrlanguage = $self->{'language_exp'};
250 return if ($doclanguage && ($doclanguage !~ /$phrlanguage/i));
251
252 # record this file
253 my $total++;
254 print "file $total: $file\n" if ($self->{'$verbosity'});
255
256
257 # Store document details
258 my $OID = $doc_obj->get_OID();
259 $OID = "NULL" unless defined $OID;
260 my $dochandle = $self->{'dochandle'};
261 print $dochandle "<Document>\t$OID\t$title\n";
262
263 # Store the text occuring in this object
264
265 # output the document delimiter
266 my $txthandle = $self->{'txthandle'};
267 print $txthandle "$doclimit\n";
268
269 # iterarate over the required indexes and store their text
270 my $indexes = $self->{'indexes'};
271 my $text = "";
272 my ($part, $level, $field, $section, $data, $dataref);
273
274 foreach $part (split(/,/, $indexes)) {
275
276 # Each field has a level and a data element ((e.g. document:Title)
277 ($level, $field) = split(/:/, $part);
278 die unless ($level && $field);
279
280 # Extract the text from every section
281 # (In phind, document:text and section:text are equivalent)
282 if ($field eq "text") {
283 $data = "";
284 $section = $doc_obj->get_top_section();
285 while (defined($section)) {
286 $data .= $doc_obj->get_text($section) . "\n";
287 $section = $doc_obj->get_next_section($section);
288 }
289 $text .= convert_gml_to_tokens($phrlanguage, $data) . "\n";
290 }
291
292 # Extract a metadata field from a document
293 # (If ther eis more than one element of the given type, get them all.)
294 elsif ($level eq "document") {
295 $dataref = $doc_obj->get_metadata($doc_obj->get_top_section(), $field);
296 foreach $data (@$dataref) {
297 $text .= convert_gml_to_tokens($phrlanguage, $data) . "\n";
298 }
299 }
300
301 # Extract metadata from every section in a document
302 elsif ($level eq "section") {
303 $data = "";
304 $section = $doc_obj->get_top_section();
305 while (defined($section)) {
306 $dataref = $doc_obj->get_metadata($section, $field);
307 $data .= join("\n", @$dataref) . "\n";
308 $section = $doc_obj->get_next_section($section);
309 }
310 $text .= convert_gml_to_tokens($phrlanguage, $data) . "\n";
311 }
312
313 # Some sort of specification which I don't understand
314 else {
315 die "Unknown level ($level) in phind index ($part)\n";
316 }
317
318 }
319
320 # output the text
321 $text =~ tr/\n//s;
322 print $txthandle "$text";
323}
324
325
326# Construct the classifier from the information already gathered
327#
328# When get_classify_info is called, the clauses and docs.txt files have
329# already been constructed in the phind directory. This function will
330# translate them into compressed, indexed MGPP files that can be read by
331# the phindcgi script. It will also register our classifier so that it
332# shows up in the navigation bar.
333
334sub get_classify_info {
335 my $self = shift (@_);
336
337 close $self->{'txthandle'};
338 my $verbosity = $self->{'verbosity'};
339 my $out = $self->{'outhandle'};
340 my $phinddir = $self->{'phinddir'};
341 my $exe = &util::get_os_exe ();
342
343 if ($verbosity) {
344 print $out "\n*** phind.pm generating indexes for ", $self->{'indexes'}, "\n";
345 print $out "*** in", $self->{'phinddir'}, "\n";
346 }
347
348 # Construct phind indexes
349 my $suffixmode = $self->{'suffixmode'};
350 my ($command, $status);
351
352 # Generate the vocabulary, symbol statistics, and numbers file
353 # from the clauses file
354 print $out "\nExtracting vocabulary and statistics\n" if $verbosity;
355 &extract_vocabulary($self);
356
357 # Use the suffix program to generate the phind/phrases file
358 print $out "\nExtracting phrases from processed text (with suffix)\n" if $verbosity;
359 &execute("suffix $phinddir $suffixmode $verbosity", $verbosity, $out);
360
361 # Create the phrase file and put phrase numbers in phind/phrases
362 print $out "\nSorting and renumbering phrases for input to mgpp\n" if $verbosity;
363 &renumber_phrases($self);
364
365 # Create the mg phrase database
366
367 print $out "\nCreating phrase databases\n";
368 my $mg_input = &util::filename_cat($phinddir, "pdata.txt");
369 my $mg_stem = "pdata";
370
371 &execute("mgpp_passes$exe -d $phinddir -f $mg_stem -T1 $mg_input", $verbosity, $out);
372 &execute("mgpp_compression_dict$exe -d $phinddir -f $mg_stem", $verbosity, $out);
373 &execute("mgpp_passes$exe -d $phinddir -f $mg_stem -T2 $mg_input", $verbosity, $out);
374
375 # create the mg index of words
376 print $out "\nCreating word-level search indexes\n";
377 $mg_input = &util::filename_cat($phinddir, "pword.txt");
378 $mg_stem = "pword";
379
380 &execute("mgpp_passes$exe -d $phinddir -f $mg_stem -T1 -I1 $mg_input", $verbosity, $out);
381 &execute("mgpp_compression_dict$exe -d $phinddir -f $mg_stem", $verbosity, $out);
382 &execute("mgpp_perf_hash_build$exe -d $phinddir -f $mg_stem", $verbosity, $out);
383 &execute("mgpp_passes$exe -d $phinddir -f $mg_stem -T2 -I2 $mg_input", $verbosity, $out);
384 &execute("mgpp_weights_build$exe -d $phinddir -f $mg_stem", $verbosity, $out);
385 &execute("mgpp_invf_dict$exe -d $phinddir -f $mg_stem", $verbosity, $out);
386
387 &execute("mgpp_stem_idx$exe -d $phinddir -f $mg_stem -s 1", $verbosity, $out);
388 &execute("mgpp_stem_idx$exe -d $phinddir -f $mg_stem -s 2", $verbosity, $out);
389 &execute("mgpp_stem_idx$exe -d $phinddir -f $mg_stem -s 3", $verbosity, $out);
390
391 # create the mg document information database
392 print $out "\nCreating document information databases\n";
393 $mg_input = &util::filename_cat($phinddir, "docs.txt");
394 $mg_stem = "docs";
395
396 &execute("mgpp_passes$exe -d $phinddir -f $mg_stem -T1 $mg_input", $verbosity, $out);
397 &execute("mgpp_compression_dict$exe -d $phinddir -f $mg_stem", $verbosity, $out);
398 &execute("mgpp_passes$exe -d $phinddir -f $mg_stem -T2 $mg_input", $verbosity, $out);
399
400
401 # Tidy up stray files
402 if (!$self->{'untidy'}) {
403 print $out "\nCleaning up\n" if ($verbosity > 2);
404 &util::rm("$phinddir/clauses", "$phinddir/clauses.numbers",
405 "$phinddir/clauses.vocab", "$phinddir/clauses.stats",
406 "$phinddir/phrases", "$phinddir/phrases.3", "$phinddir/docs.txt",
407 "$phinddir/pdata.txt", "$phinddir/pword.txt");
408 my $outfile = 1;
409 while (-e "$phinddir/outPhrase.$outfile") {
410 &util::rm("$phinddir/outPhrase.$outfile");
411 $outfile++;
412 }
413 }
414
415
416 # Return the information about the classifier that we'll later want to
417 # use to create macros when the Phind classifier document is displayed.
418 my %classifyinfo = ('thistype'=>'Invisible',
419 'childtype'=>'Phind',
420 'Title'=>$self->{'buttonname'},
421 'parameters'=>"phindnumber=$self->{'phindnumber'}",
422 'contains'=>[]);
423
424 my $collection = $self->{'collection'};
425 my $url = "library?a=p&p=phind&c=$collection";
426 push (@{$classifyinfo{'contains'}}, {'OID'=>$url});
427
428 return \%classifyinfo;
429}
430
431
432
433sub convert_gml_to_tokens {
434
435 my ($language_exp, $text) = @_;
436
437 if ($language_exp =~ /en/) {
438 return &convert_gml_to_tokens_EN($text);
439 }
440
441 $_ = $text;
442
443 # 1. remove GML tags
444
445 # Remove everything that is in a tag
446 s/\s*<p>\s*/ PARAGRAPHBREAK /isgo;
447 s/\s*<br>\s*/ LINEBREAK /isgo;
448 s/<[^>]*>/ /sgo;
449
450 # Now we have the text, but it may contain HTML
451 # elements coded as &gt; etc. Remove these tags.
452 s/&amp;/&/sgo;
453 s/&lt;/</sgo;
454 s/&gt;/>/sgo;
455 s/\s*<p>\s*/ PARAGRAPHBREAK /isgo;
456 s/\s*<br>\s*/ LINEBREAK /isgo;
457 s/<[^>]*>/ /sgo;
458
459 # replace<p> and <br> placeholders with clause break symbol (\n)
460 s/\s+/ /gso;
461 s/PARAGRAPHBREAK/\n/sgo;
462 s/LINEBREAK/\n/sgo;
463
464
465
466
467 # 2. Split the remaining text into space-delimited tokens
468
469 # Convert any HTML special characters (like &quot;) to their UTF8 equivalent
470 s/&([^;]+);/&unicode::ascii2utf8(\&ghtml::getcharequiv($1,1))/gse;
471
472 # Split text at word boundaries
473 s/\b/ /go;
474
475 # 3. Convert the remaining text to "clause format"
476
477 # Insert newline if the end of a sentence is detected
478 # (delimter is: "[\.\?\!]\s")
479 # s/\s*[\.\?\!]\s+/\n/go;
480
481 # remove unnecessary punctuation and replace with clause break symbol (\n)
482 s/[^\w ]/\n/go;
483
484 # remove extraneous whitespace
485 s/ +/ /sgo;
486 s/^\s+//mgo;
487 s/\s*$/\n/mgo;
488
489 # remove lines that contain one word or less
490 s/^\S*$//mgo;
491 s/^\s*$//mgo;
492 tr/\n//s;
493
494 return $_;
495}
496
497# A version of convert_gml_to_tokens that is fine-tuned to the English language.
498
499sub convert_gml_to_tokens_EN {
500 $_ = shift @_;
501
502 # FIRST, remove GML tags
503
504 # Replace all whitespace with a simple space
505 s/\s+/ /gs;
506
507 # Remove everything that is in a tag
508 s/\s*<p>\s*/ PARAGRAPHBREAK /isg;
509 s/\s*<br>\s*/ LINEBREAK /isg;
510 s/<[^>]*>/ /sg;
511
512 # Now we have the text, but it may contain HTML
513 # elements coded as &gt; etc. Remove these tags.
514 s/&lt;/</sg;
515 s/&gt;/>/sg;
516
517 s/\s+/ /sg;
518 s/\s*<p>\s*/ PARAGRAPHBREAK /isg;
519 s/\s*<br>\s*/ LINEBREAK /isg;
520 s/<[^>]*>/ /sg;
521
522 # remove &amp; and other miscellaneous markup tags
523 s/&amp;/&/sg;
524 s/&lt;/</sg;
525 s/&gt;/>/sg;
526 s/&amp;/&/sg;
527
528 # replace<p> and <br> placeholders with carriage returns
529 s/PARAGRAPHBREAK/\n/sg;
530 s/LINEBREAK/\n/sg;
531
532
533 # Exceptional punctuation
534 #
535 # We make special cases of some punctuation
536
537 # remove any apostrophe that indicates omitted letters
538 s/(\w+)\'(\w*\s)/ $1$2 /g;
539
540 # remove period that appears in a person's initals
541 s/\s([A-Z])\./ $1 /g;
542
543 # replace hyphens in hypheanted words and names with a space
544 s/([A-Za-z])-\s*([A-Za-z])/$1 $2/g;
545
546 # Convert the remaining text to "clause format",
547 # This means removing all excess punctuation and garbage text,
548 # normalising valid punctuation to fullstops and commas,
549 # then putting one cluse on each line.
550
551 # Insert newline when the end of a sentence is detected
552 # (delimter is: "[\.\?\!]\s")
553 s/\s*[\.\?\!]\s+/\n/g;
554
555 # split numbers after four digits
556 s/(\d\d\d\d)/$1 /g;
557
558 # split words after 32 characters
559
560 # squash repeated punctuation
561 tr/A-Za-z0-9 //cs;
562
563 # save email addresses
564 # s/\w+@\w+\.[\w\.]+/EMAIL/g;
565
566 # normalise clause breaks (mostly punctuation symbols) to commas
567 s/[^A-Za-z0-9 \n]+/ , /g;
568
569 # Remove repeated commas, and replace with newline
570 s/\s*,[, ]+/\n/g;
571
572 # remove extra whitespace
573 s/ +/ /sg;
574 s/^\s+//mg;
575 s/\s*$/\n/mg;
576
577 # remove lines that contain one word or less
578 s/^\w*$//mg;
579 s/^\s*$//mg;
580 tr/\n//s;
581
582 return $_;
583
584}
585
586
587
588# Execute a system command
589
590sub execute {
591 my ($command, $verbosity, $outhandle) = @_;
592 print $outhandle "Executing: $command\n" if ($verbosity > 2);
593 my $status = system($command);
594 if ($status != 0) {
595 print STDERR "phind - Error executing $command: $!\n";
596 exit($status);
597 }
598}
599
600
601# Generate the vocabulary, symbol statistics, and numbers file from the
602# clauses file. This is legacy code, so is a bit messy and probably wont
603# run under windows.
604
605sub extract_vocabulary {
606 my ($self) = @_;
607
608 my $verbosity = $self->{'verbosity'};
609 my $out = $self->{'outhandle'};
610
611 my $collectiondir = $self->{'collectiondir'};
612 my $phinddir = $self->{'phinddir'};
613
614 my $language_exp = $self->{'language_exp'};
615
616 my ($w, $l, $line, $word);
617
618 my ($first_delimiter, $last_delimiter,
619 $first_stopword, $last_stopword,
620 $first_extractword, $last_extractword,
621 $first_contentword, $last_contentword,
622 $phrasedelimiter);
623
624 my $thesaurus = $self->{'thesaurus'};
625 my ($thesaurus_links, $thesaurus_terms,
626 %thesaurus, $first_thesaurusword, $last_thesaurusword);
627
628 my %symbol;
629 my (%freq);
630
631 print $out "Calculating vocabulary\n" if ($verbosity > 1);
632
633 # Read and store the stopwords
634 my $stopdir = &util::filename_cat($ENV{'GSDLHOME'}, "etc", "stopwords");
635 my $stopword_files = ();
636 my ($language, $language_dir, $file, $file_name);
637 my %stopwords;
638
639 # Examine each directory in the stopword directory
640 opendir(STOPDIR, $stopdir);
641 foreach $language (readdir STOPDIR) {
642
643 # Ignore entries that do not match the classifier's language
644 next unless ($language =~ /$language_exp/);
645 $language_dir = &util::filename_cat($stopdir, $language);
646 next unless (-d "$language_dir");
647
648 opendir(LANGDIR, $language_dir);
649 foreach $file (readdir LANGDIR) {
650
651 # Ignore entries that are not stopword files
652 next unless ($file =~ /sw$/);
653 $file_name = &util::filename_cat($language_dir, $file);
654 next unless (-f "$file_name");
655
656 # Read the stopwords
657 open(STOPFILE, "<$file_name");
658 while (<STOPFILE>) {
659 s/^\s+//;
660 s/\s.*//;
661 $word = $_;
662 $l = lc($word);
663 $stopwords{$l} = $word;
664 }
665 close STOPFILE;
666
667 }
668 closedir LANGDIR;
669 }
670 closedir STOPDIR;
671
672 # Read thesaurus information
673 if ($thesaurus) {
674
675 # link file exists
676 $thesaurus_links = &util::filename_cat($collectiondir, "etc", "$thesaurus.lnk");
677 die "Cannot find thesaurus link file" unless (-e "$thesaurus_links");
678
679 # ensure term file exists in the correct language
680 if ($language_exp =~ /^([a-z][a-z])/) {
681 $language = $1;
682 } else {
683 $language = 'en';
684 }
685 $thesaurus_terms = &util::filename_cat($collectiondir, "etc", "$thesaurus.$language");
686 die "Cannot find thesaurus term file" unless (-e "$thesaurus_terms");
687
688
689 # Read the thesaurus terms
690 open(TH, "<$thesaurus_terms");
691 while(<TH>) {
692 s/^\d+ //;
693 s/\(.*\)//;
694 foreach $w (split(/\s+/, $_)) {
695 $thesaurus{lc($w)} = $w;
696 }
697 }
698 close TH;
699 }
700
701 # Read words in the text and count occurences
702 open(TXT, "<$phinddir/clauses");
703 my @words;
704
705 while(<TXT>) {
706 $line = $_;
707 next unless ($line =~ /./);
708
709 @words = split(/\s+/, $line);
710 foreach $w (@words) {
711 $l = lc($w);
712 $w = $l if ((defined $stopwords{$l}) || (defined $thesaurus{$l}));
713 $freq{$w}++;
714 }
715 $freq{$senlimit}++;
716 }
717
718 close TXT;
719
720 # Calculate the "best" form of each word
721 my (%bestform, %totalfreq, %bestfreq);
722
723 foreach $w (sort (keys %freq)) {
724 $l = lc($w);
725
726 # totalfreq is the number of times a term appears in any form
727 $totalfreq{$l} += $freq{$w};
728
729 if (defined $stopwords{$l}) {
730 $bestform{$l} = $stopwords{$l};
731
732 } elsif (defined $thesaurus{$l}) {
733 $bestform{$l} = $thesaurus{$l};
734
735 } elsif (!$bestform{$l} || ($freq{$w} > $bestfreq{$l})) {
736 $bestfreq{$l} = $freq{$w};
737 $bestform{$l} = $w;
738 }
739 }
740
741 undef %freq;
742 undef %bestfreq;
743
744
745 # Assign symbol numbers to tokens
746 my $nextsymbol = 1;
747 my (@vocab);
748
749 # Delimiters
750 $first_delimiter = 1;
751
752 foreach $word (@delimiters) {
753
754 $word = lc($word);
755 $bestform{$word} = uc($word);
756 $vocab[$nextsymbol] = $word;
757 $symbol{$word} = $nextsymbol;
758 $nextsymbol++;
759 }
760 $last_delimiter = $nextsymbol - 1;
761
762 # Stopwords
763 $first_stopword = $nextsymbol;
764
765 foreach my $word (sort keys %stopwords) {
766
767 # don't incluse stopword unless it occurs in the text
768 $word = lc($word);
769 next unless ($totalfreq{$word});
770 next if ($symbol{$word});
771
772 $vocab[$nextsymbol] = $word;
773 $symbol{$word} = $nextsymbol;
774 $nextsymbol++;
775 }
776 $last_stopword = $nextsymbol - 1;
777 $first_contentword = $nextsymbol;
778
779 # Thesaurus terms
780 if ($thesaurus) {
781 $first_thesaurusword = $nextsymbol;
782
783 foreach my $word (sort keys %thesaurus) {
784
785 $word = lc($word);
786 next if ($symbol{$word});
787 $bestform{$word} = $thesaurus{$word};
788
789 $vocab[$nextsymbol] = $word;
790 $symbol{$word} = $nextsymbol;
791 $nextsymbol++;
792
793 }
794 $last_thesaurusword = $nextsymbol - 1;
795 }
796
797 # Other content words
798 $first_extractword = $nextsymbol;
799
800 foreach my $word (sort (keys %bestform)) {
801
802 next if ($symbol{$word});
803
804 $vocab[$nextsymbol] = $word;
805 $symbol{$word} = $nextsymbol;
806 $nextsymbol++;
807 }
808 $last_extractword = $nextsymbol - 1;
809 $last_contentword = $nextsymbol - 1;
810
811
812 # Outut the words
813 print $out "Saving vocabulary in $phinddir/clauses.vocab\n" if ($verbosity > 1);
814 open(VOC, ">$phinddir/clauses.vocab");
815
816 for (my $i = 1; $i < $nextsymbol; $i++) {
817 $w = $vocab[$i];
818
819 print VOC "$bestform{$w}\n";
820 $totalfreq{$w} = 0 unless ($totalfreq{$w});
821 }
822 close VOC;
823
824
825 # Create statistics file
826 # Output statistics about the vocablary
827 print $out "Saving statistics in $phinddir/clauses.stats\n" if ($verbosity > 1);
828 &util::rm("$phinddir/clauses.stats") if (-e "$phinddir/clauses.stats");
829
830 open(STAT, ">$phinddir/clauses.stats")
831 || die "Cannot open $phinddir/clauses.stats: $!";
832
833 print STAT "first_delimiter $first_delimiter\n";
834 print STAT "last_delimiter $last_delimiter\n";
835 print STAT "first_stopword $first_stopword\n";
836 print STAT "last_stopword $last_stopword\n";
837 if ($thesaurus) {
838 print STAT "first_thesaurusword $first_thesaurusword\n";
839 print STAT "last_thesaurusword $last_thesaurusword\n";
840 }
841 print STAT "first_extractword $first_extractword\n";
842 print STAT "last_extractword $last_extractword\n";
843 print STAT "first_contentword $first_contentword\n";
844 print STAT "last_contentword $last_contentword\n";
845 print STAT "first_symbol $first_delimiter\n";
846 print STAT "last_symbol $last_contentword\n";
847 print STAT "first_word $first_stopword\n";
848 print STAT "last_word $last_contentword\n";
849 close STAT;
850
851 undef @vocab;
852
853
854 # Create numbers file
855 # Save text as symbol numbers
856 print $out "Saving text as numbers in $phinddir/clauses.numbers\n" if ($verbosity > 1);
857
858 open(TXT, "<$phinddir/clauses");
859 open(NUM, ">$phinddir/clauses.numbers");
860
861 $phrasedelimiter = $symbol{lc($senlimit)};
862 print NUM "$symbol{lc($colstart)}\n";
863
864 # set up the special symbols that delimit documents and sentences
865 while(<TXT>) {
866
867 # split sentence into a list of tokens
868 $line = $_;
869 next unless ($line =~ /./);
870 @words = split(/\s+/, $line);
871
872 # output one token at a time
873 foreach $word (@words) {
874 $word = lc($word);
875 print NUM "$symbol{$word}\n";
876 }
877
878 # output phrase delimiter
879 print NUM "$phrasedelimiter\n";
880 }
881
882 close TXT;
883 print NUM "$symbol{lc($colend)}\n";
884 close NUM;
885
886 # Save thesaurus data in one convienient file
887 if ($thesaurus) {
888
889 my $thesaurusfile = &util::filename_cat($phinddir, "$thesaurus.numbers");
890
891
892 print $out "Saving thesaurus as numbers in $thesaurusfile\n"
893 if ($verbosity > 1);
894
895 # Read the thesaurus terms
896 my ($num, $text, %thes_symbols);
897
898 open(TH, "<$thesaurus_terms");
899 while(<TH>) {
900 chomp;
901 @words = split(/\s+/, $_);
902 $num = shift @words;
903 $text = "";
904
905 # translate words into symbol numbers
906 foreach $word (@words) {
907 $word = lc($word);
908 if ($symbol{$word}) {
909 $text .= "s$symbol{$word} ";
910 } elsif ($verbosity) {
911 print $out "phind: No thesaurus symbol, ignoring \"$word\"\n";
912 }
913 }
914 $text =~ s/ $//;
915 $thes_symbols{$num} = $text;
916 }
917 close TH;
918
919 # Read the thesaurus links and write the corresponding data
920 open(TH, "<$thesaurus_links");
921 open(THOUT, ">$thesaurusfile");
922
923 while(<TH>) {
924 chomp;
925 ($num, $text) = split(/:/, $_);
926
927 if (defined($thes_symbols{$num})) {
928 print THOUT "$num:$thes_symbols{$num}:$text\n";
929 } else {
930 print THOUT "$num:untranslated:$text\n";
931 }
932 }
933 close TH;
934 close THOUT;
935 }
936
937
938
939
940}
941
942
943# renumber_phrases
944#
945# Prepare the phrases file to be input to mgpp. The biggest problem is
946# reconciling the phrase identifiers used by the suffix program (which
947# we'll call suffix-id numbers) with the numbers used in the thesaurus
948# (theesaurus-id) to create a ciommon set of phind id numbers (phind-id).
949# Phind-id numbers must be sorted by frequency of occurance.
950#
951# Start creating a set of phind-id numbers from the sorted suffix-id
952# numbers and (if required) the thesaurus-id numbers. Then add any other
953# phrases occuring in the thesaurus.
954#
955# The last thing we have to do is restore the vocabulary information to the
956# phrase file so that the phrases are stored as words, not as symbol
957# numbers.
958
959# The original phrases file looks something like this:
960# 159396-1:s5175:4:1:116149-2:3:d2240,2;d2253;d2254
961# 159409-1:s5263:6:1:159410-2:6:d2122;d2128;d2129;d2130;d2215;d2380
962# 159415-1:s5267:9:1:159418-2:8:d3,2;d632;d633;d668;d1934;d2010;d2281;d2374
963# 159426-1:s5273:5:2:159429-2,115168-17:5:d252;d815;d938;d939;d2361
964
965
966sub renumber_phrases {
967 my ($self) = @_;
968
969 renumber_suffix_data($self);
970 renumber_thesaurus_data($self);
971 restore_vocabulary_data($self);
972
973}
974
975
976
977# renumber_suffix_data
978#
979# Translate phrases file to phrases.2 using phind keys instead
980# of suffix keys and sorting the expansion data.
981
982sub renumber_suffix_data {
983 my ($self) = @_;
984
985 my $verbosity = $self->{'verbosity'};
986 my $out = $self->{'outhandle'};
987 print $out "Translate phrases: suffix-ids become phind-id's\n"
988 if ($verbosity);
989
990 my $phinddir = $self->{'phinddir'};
991 my $infile = &util::filename_cat($phinddir, 'phrases');
992 my $outfile = &util::filename_cat($phinddir, 'phrases.2');
993
994 # Read the phrase file. Calculate initial set of phind-id
995 # numbers and store (suffixid -> frequency) relation.
996
997 my %suffixtophind;
998 my @phindfrequency;
999 my (@fields, $suffixid);
1000 my $nextphind = 1;
1001
1002 open(IN, "<$infile");
1003 while(<IN>) {
1004
1005 chomp;
1006 @fields = split(/:/, $_);
1007
1008 # get next suffixid and phindid
1009 $suffixid = shift @fields;
1010 $suffixtophind{$suffixid} = $nextphind;
1011
1012 # store total frequency
1013 shift @fields;
1014 $totalfrequency[$nextphind] = shift @fields;
1015
1016 $nextphind++;
1017 }
1018 close IN;
1019
1020
1021 # Translate phrases file to phrases.2. Use phind keys (not suffix
1022 # keys), sort expansion and document occurance data in order of
1023 # descending frequency..
1024 open(IN, "<$infile");
1025 open(OUT, ">$outfile");
1026
1027 my ($phindid, $text, $tf, $countexp, $expansions, $countdocs, $documents);
1028 my (@documwents, @newexp, $k, $n);
1029 my $linenumber = 0;
1030
1031 while(<IN>) {
1032
1033 # read the line
1034 chomp;
1035 @fields = split(/:/, $_);
1036
1037 # get a phrase number for this line
1038 $suffixid = shift @fields;
1039 die unless (defined($suffixtophind{$suffixid}));
1040 $phindid = $suffixtophind{$suffixid};
1041
1042 # get the symbols in the phrase
1043 $text = shift @fields;
1044
1045 # output status information
1046 $linenumber++;
1047 if ($verbosity > 2) {
1048 if ($linenumber % 1000 == 0) {
1049 print $out "line $linenumber:\t$phindid\t$suffixid\t($text)\n";
1050 }
1051 print $out "$num: $key\t($text)\n" if ($verbosity > 3);
1052 }
1053
1054 # get the phrase frequency
1055 $tf = shift @fields;
1056
1057 # get the number of expansions
1058 $countexp = shift @fields;
1059
1060 # get the expansions, convert them into phind-id numbers, and sort them
1061 $expansions = shift @fields;
1062 @newexp = ();
1063 foreach $k (split(/,/, $expansions)) {
1064 die "ERROR - no phindid for: $k" unless (defined($suffixtophind{$k}));
1065 $n = $suffixtophind{$k};
1066 push @newexp, $n;
1067 }
1068 @newexp = sort {$totalfrequency[$b] <=> $totalfrequency[$a]} @newexp;
1069
1070 # get the number of documents
1071 $countdocs = shift @fields;
1072
1073 # get the documents and sort them
1074 $documents = shift @fields;
1075 $documents =~ s/d//g;
1076 @documents = split(/;/, $documents);
1077 @documents = sort by_doc_frequency @documents;
1078
1079 # output the phrase data
1080 print OUT "$phindid:$text:$tf:$countexp:$countdocs:";
1081 print OUT join(",", @newexp), ",:", join(";", @documents), ";\n";
1082
1083 }
1084
1085 close IN;
1086 close OUT;
1087}
1088
1089
1090# renumber_thesaurus_data
1091#
1092# Translate phrases.2 to phrases.3, adding thesaurus data if available.
1093
1094sub renumber_thesaurus_data {
1095 my ($self) = @_;
1096
1097 my $out = $self->{'outhandle'};
1098 my $verbosity = $self->{'verbosity'};
1099 my $thesaurus = $self->{'thesaurus'};
1100
1101 my $phinddir = $self->{'phinddir'};
1102 my $infile = &util::filename_cat($phinddir, "phrases.2");
1103 my $outfile = &util::filename_cat($phinddir, "phrases.3");
1104
1105
1106 # If no thesaurus is defined, simply move the phrases file.
1107 if (!$thesaurus) {
1108 print $out "Translate phrases.2: no thesaurus data\n"
1109 if ($verbosity);
1110 &util::mv($infile, $outfile);
1111 return;
1112 }
1113
1114 print $out "Translate phrases.2: add thesaurus data\n"
1115 if ($verbosity);
1116
1117 # 1.
1118 # Read thesaurus file and store (symbols->thesaurusid) mapping
1119 my $thesaurusfile = &util::filename_cat($phinddir, "$thesaurus.numbers");
1120 my %symbolstothesid;
1121 my (@fields, $thesid, $symbols);
1122
1123 open(TH, "<$thesaurusfile");
1124
1125 while (<TH>) {
1126
1127 chomp;
1128 @fields = split(/:/, $_);
1129
1130 # get id and text
1131 $thesid = shift @fields;
1132 $symbols = shift @fields;
1133 $symbolstothesid{$symbols} = $thesid;
1134 }
1135 close TH;
1136
1137 # 2.
1138 # Read phrases file to find thesaurus entries that already
1139 # have a phindid. Store their phind-ids for later translation,
1140 # and store their frequency for later sorting.
1141 my %thesaurustophindid;
1142 my %phindidtofrequency;
1143 my ($phindid, $freq);
1144
1145 open(IN, "<$infile");
1146
1147 while(<IN>) {
1148
1149 chomp;
1150 @fields = split(/:/, $_);
1151
1152 # phindid and symbols for this line
1153 $phindid = shift @fields;
1154 $symbols = shift @fields;
1155 $freq = shift @fields;
1156
1157 # do we have a thesaurus id corresponding to this phrase?
1158 if (defined($symbolstothesid{$symbols})) {
1159 $thesid = $symbolstothesid{$symbols};
1160 $thesaurustophindid{$thesid} = $phindid;
1161 $phindidtofrequency{$phindid} = $freq;
1162 }
1163 }
1164 close IN;
1165
1166 undef %symbolstothesid;
1167
1168 # 3.
1169 # Create phind-id numbers for remaining thesaurus entries,
1170 # and note that their frequency is 0 for later sorting.
1171 my $nextphindid = $phindid + 1;
1172
1173 open(TH, "<$thesaurusfile");
1174 while(<TH>) {
1175
1176 chomp;
1177 @fields = split(/:/, $_);
1178
1179 # read thesaurus-id and ensure it has a corresponding phind-id
1180 $thesid = shift @fields;
1181 if (!defined($thesaurustophindid{$thesid})) {
1182 $thesaurustophindid{$thesid} = $nextphindid;
1183 $phindidtofrequency{$nextphindid} = 0;
1184 $nextphindid++;
1185 }
1186 }
1187 close TH;
1188
1189 # 4.
1190 # Translate thesaurus file, replacing thesaurus-id numbers with
1191 # phind-id numbers.
1192 my $newthesaurusfile = &util::filename_cat($phinddir, "$thesaurus.phindid");
1193 my ($relations, $linkcounter, $linktext, $linktype, @linkdata);
1194 my (@links, $linkid, %linkidtotype, $newrelation);
1195
1196 open(TH, "<$thesaurusfile");
1197 open(TO, ">$newthesaurusfile");
1198 while(<TH>) {
1199
1200 chomp;
1201 @fields = split(/:/, $_);
1202
1203 # phindid and symbols for this line
1204 ($thesid, $symbols, $relations) = @fields;
1205
1206 die unless ($thesid && $symbols);
1207 die unless $thesaurustophindid{$thesid};
1208 $phindid = $thesaurustophindid{$thesid};
1209
1210 # convert each part of the relation string to use phind-id numbers
1211 # at the same time, we want to sort the list by frequency.
1212 undef %linkidtotype;
1213
1214 foreach $linktext (split(/;/, $relations)) {
1215 @linkdata = split(/,/, $linktext);
1216
1217 # remember the linktype (e.g. BT, NT)
1218 $linktype = shift @linkdata;
1219
1220 # store the type of each link
1221 foreach $thesid (@linkdata) {
1222 die unless (defined($thesaurustophindid{$thesid}));
1223 $linkidtotype{$thesaurustophindid{$thesid}} = $linktype;
1224 }
1225 }
1226
1227 # sort the list of links, first by frequency, then by type.
1228 @links = sort { ($phindidtofrequency{$b} <=> $phindidtofrequency{$a})
1229 or ($linkidtotype{$a} cmp $linkidtotype{$b}) } (keys %linkidtotype);
1230 $linkcounter = (scalar @links);
1231
1232 # create a string describing the link information
1233 $linktype = $linkidtotype{$links[0]};
1234 $newrelation = $linktype;
1235 foreach $linkid (@links) {
1236 if ($linkidtotype{$linkid} ne $linktype) {
1237 $linktype = $linkidtotype{$linkid};
1238 $newrelation .= ";" . $linktype;
1239 }
1240 $newrelation .= "," . $linkid;
1241 }
1242 $newrelation .= ";";
1243
1244
1245 # output the new line
1246 print TO "$phindid:$symbols:$linkcounter:$newrelation:\n";
1247 }
1248 close TH;
1249 close TO;
1250
1251 undef %thesaurustophindid;
1252 undef %linkidtotype;
1253 undef %phindidtofrequency;
1254
1255 # 5.
1256 # Read thesaurus data (in phind-id format) into memory
1257 my %thesaurusdata;
1258
1259 open(TH, "<$newthesaurusfile");
1260 while(<TH>) {
1261 chomp;
1262 ($phindid, $symbols, $linkcounter, $relations) = split(/:/, $_);
1263 die unless ($phindid && $symbols);
1264 $thesaurusdata{$phindid} = "$symbols:$linkcounter:$relations";
1265 }
1266
1267 # 6.
1268 # Add thesaurus data to phrases file
1269 my ($text, $tf, $countexp, $expansions, $countdocs, $documents);
1270 my (@documwents, @newexp, $k, $n);
1271 my $linenumber = 0;
1272
1273 open(IN, "<$infile");
1274 open(OUT, ">$outfile");
1275
1276 # Update existing phrases
1277 while(<IN>) {
1278
1279 chomp;
1280 @fields = split(/:/, $_);
1281
1282 # get data for this line
1283 $phindid = shift @fields;
1284
1285 # output the phrase data, with thesaurus information
1286 print OUT "$phindid:", join(":", @fields);
1287
1288 # add thesaurus data
1289 if (defined($thesaurusdata{$phindid})) {
1290 @fields = split(/:/, $thesaurusdata{$phindid});
1291 shift @fields;
1292 $linkcounter = shift @fields;
1293 $relations = shift @fields;
1294
1295 print OUT ":$linkcounter:$relations";
1296 $thesaurusdata{$phindid} = "";
1297 }
1298 print OUT "\n";
1299 }
1300 close IN;
1301
1302 # Add phrases that aren't already in the file
1303 foreach $phindid (sort numerically keys %thesaurusdata) {
1304 next unless ($thesaurusdata{$phindid});
1305
1306 @fields = split(/:/, $thesaurusdata{$phindid});
1307 $symbols = shift @fields;
1308 $linkcounter = shift @fields;
1309 $relations = shift @fields;
1310
1311 print OUT "$phindid:$symbols:0:0:0:::$linkcounter:$relations\n";
1312 }
1313 close OUT;
1314
1315}
1316
1317# restore_vocabulary_data
1318#
1319# Read phrases.3 and restore vocabulary information. Then write
1320# this data to the MGPP input files (pwrod.txt and pdata.txt) and
1321# (if requested) to the saved phrases file.
1322
1323sub restore_vocabulary_data {
1324 my ($self) = @_;
1325
1326 my $out = $self->{'outhandle'};
1327 my $verbosity = $self->{'verbosity'};
1328 print $out "Translate phrases.3: restore vocabulary\n" if ($verbosity);
1329
1330 my $phinddir = $self->{'phinddir'};
1331 my $infile = &util::filename_cat($phinddir, 'phrases.3');
1332 my $vocabfile = &util::filename_cat($phinddir, 'clauses.vocab');
1333 my $datafile = &util::filename_cat($phinddir, 'pdata.txt');
1334 my $wordfile = &util::filename_cat($phinddir, 'pword.txt');
1335
1336 my $savephrases = $self->{'savephrases'};
1337
1338 # 1.
1339 # Read the vocabulary file
1340 open(V, "<$vocabfile")
1341 || die "Cannot open $vocabfile: $!";
1342 my @symbol;
1343 my $i = 1;
1344 while(<V>) {
1345 chomp;
1346 $symbol[$i++] = $_;
1347 }
1348
1349
1350 # 2.
1351 # Translate phrases.3 to MGPP input files
1352 my ($key, $text, $word, $isThesaurus);
1353 my @fields;
1354 my $linenumber = 0;
1355
1356 open(IN, "<$infile");
1357 open(DATA, ">$datafile");
1358 open(WORD, ">$wordfile");
1359
1360 # Save the phrases in a separate text file
1361 if ($savephrases) {
1362 print $out "Saving phrases in $savephrases\n" if ($verbosity);
1363 open(SAVE, ">$savephrases");
1364 }
1365
1366 while(<IN>) {
1367
1368 # read the line
1369 chomp;
1370 $line = $_;
1371 @fields = split(/:/, $line);
1372
1373 # get a phrase number for this line
1374 $key = shift @fields;
1375
1376 # restore the text of the phrase
1377 $text = shift @fields;
1378 $text =~ s/s(\d+)/$symbol[$1]/g;
1379 if ($text =~ / /) {
1380 $word = "";
1381 } elsif ($text ne 'untranslated') {
1382 $word = $text;
1383 }
1384
1385 # output the phrase data
1386 print DATA "<Document>";
1387 print DATA "$key:$text:", join(":", @fields), ":\n";
1388
1389 # output the word index search data
1390 print WORD "<Document>$word\n";
1391
1392 # output the phrases to a text file
1393 if ($savephrases) {
1394 if ((scalar @fields) == 7) {
1395 $isThesaurus = 1;
1396 } else {
1397 $isThesaurus = 0;
1398 }
1399 print SAVE $fields[0], "\t", $fields[2], "\t$isThesaurus\t$text\n";
1400 }
1401 }
1402 close IN;
1403 close WORD;
1404 close DATA;
1405 close SAVE if ($savephrases);
1406
1407}
1408
1409
1410
1411# sort routines used to renumber phrases
1412
1413sub numerically { $a <=> $b }
1414
1415sub by_doc_frequency {
1416 my $fa = 1;
1417 if ($a =~ /,/) {
1418 $fa = $a;
1419 $fa =~ s/\d+,//;
1420 }
1421 my $fb = 1;
1422 if ($b =~ /,/) {
1423 $fb = $b;
1424 $fb =~ s/\d+,//;
1425 }
1426
1427 return ($fb <=> $fa);
1428}
1429
14301;
Note: See TracBrowser for help on using the repository browser.