944a8dde497dae5c05171c77d37262c047704c81
[scpubgit/stemmatology.git] / lib / Text / Tradition / Parser / CollateText.pm
1 package Text::Tradition::Parser::CollateText;
2
3 use strict;
4 use warnings;
5
6 =head1 NAME
7
8 Text::Tradition::Parser::CollateText
9
10 =head1 DESCRIPTION
11
12 For an overview of the package, see the documentation for the
13 Text::Tradition module.
14
15 This module is meant for use with a set of text files saved from Word docs, 
16 which originated with the COLLATE collation program.  
17
18 =head1 SUBROUTINES
19
20 =over
21
22 =item B<parse>
23
24 parse( $graph, $opts );
25
26 Takes an initialized graph and a hashref of options, which must include:
27 - 'base' - the base text referenced by the variants
28 - 'format' - the format of the variant list
29 - 'data' - the variants, in the given format.
30
31 =cut
32
33 my %ALL_SIGLA;
34
35 sub parse {
36     my( $tradition, $opts ) = @_;
37     # String together the base text.
38     my $lineref_hash = read_stone_base( $opts->{'base'}, $tradition->collation );
39     # Note the sigla.
40     foreach my $sigil ( @{$opts->{'sigla'}} ) {
41         $ALL_SIGLA{$sigil} = 1;
42         $tradition->add_witness( 'sigil' => $sigil );
43     }
44     # Now merge on the apparatus entries.
45     merge_stone_apparatus( $tradition->collation, $lineref_hash, $opts->{'file'} );
46 }
47
48 =item B<read_stone_base>
49
50 my $text_list = read_base( 'reference.txt', $collation );
51
52 Takes a text file and a (presumed empty) collation object, adds the words
53 as simple linear readings to the collation, and returns a hash of texts
54 with line keys. This collation is now the starting point for application of
55 apparatus entries in merge_base, e.g. from a CSV file or a Classical Text
56 Editor file.
57
58 The hash is of the form 
59
60  { chapter_name => { line_ref => { start => node, end => node } } }
61
62 =cut
63
64 sub read_stone_base {
65     my( $base_file, $collation ) = @_;
66     
67     # This array gives the first reading for each line.  We put the
68     # common starting point in line zero.
69     my $last_reading = $collation->start();
70     my $lineref_hash = {};
71     my $last_lineref;
72
73     my $curr_text;
74     open( BASE, $base_file ) or die "Could not open file $base_file: $!";
75     binmode BASE, ':utf8';
76     my $i = 1;
77     while(<BASE>) {
78         # Make the readings, and connect them up for the base, but
79         # also save the first reading of each line in a hash for the
80         # purpose.
81         chomp;
82         next if /^\s+$/; # skip blank lines
83         s/^(\d)\x{589}/$1:/; # turn Armenian full stops into colons
84         if( /^TESTAMENT/ ) {
85             # Initialize the base hash for this section.
86             $lineref_hash->{$_} = {};
87             $curr_text = $lineref_hash->{$_};
88             next;
89         } 
90         my @words = split;
91         my $lineref;
92         if( /^\d/ ) {
93             # The first "word" is a line reference; keep it.
94             $lineref = shift @words;
95         } else {
96             # Assume we are dealing with the title.
97             $lineref = 'Title:';
98         }
99         
100         # Now turn the remaining words into readings.
101         my $wordref = 0;
102         foreach my $w ( @words ) {
103             my $readingref = join( ',', $lineref, ++$wordref );
104             my $reading = $collation->add_reading( $readingref );
105             $reading->text( $w );
106             unless( exists $curr_text->{$lineref}->{'start'} ) {
107                 $curr_text->{$lineref}->{'start'} = $reading;
108             }
109             # Add edge paths in the graph, for easier tracking when
110             # we start applying corrections.  These paths will be
111             # removed when we're done.
112             my $path = $collation->add_path( $last_reading, $reading, 
113                                              $collation->baselabel );
114             $last_reading = $reading;
115         }
116         $curr_text->{$lineref}->{'end'} = $last_reading;
117     }
118
119     close BASE;
120     # Ending point for all texts
121     $collation->add_path( $last_reading, $collation->end, $collation->baselabel );
122     return( $lineref_hash );
123 }
124
125 =item B<merge_stone_apparatus>
126
127 Read an apparatus as output (presumably) by Collate.  It should be reasonably
128 regular in form, I hope.  Merge the apparatus variants onto the appropriate 
129 lemma readings.
130
131 =cut
132
133 sub merge_stone_apparatus {
134     my( $c, $lineref_hash, $file ) = @_;
135     
136     my $text_apps = {};    
137     my $current_text;
138     open( APP, $file ) or die "Could not read apparatus file $file";
139     binmode APP, ':utf8';
140     while( <APP> ) {
141         chomp;
142         next if /^\s*$/;
143         if( /^TESTAMENT/ ) {
144             $current_text = $lineref_hash->{$_};
145             next;
146         }
147         
148         # Otherwise, the first word of the line is the base text line reference.
149         my $i = 0;
150         my $lineref;
151         if( s/^(\S+)\s+// ) {
152             $lineref = $1;
153         } else {
154             warn "Unrecognized line $_";
155         }
156         my $baseline = $current_text->{$lineref};
157         # The start and end readings for this line are now in $baseline->{start}
158         # and $baseline->{end}.
159             
160         # Now look at the apparatus entries for this line. They are
161         # split with |.
162         my @apps = split( /\s+\|\s+/ );
163         my $rdg_ctr = 0;
164         foreach my $app ( @apps ) { 
165             my( $lemma, $rest ) = split( /\s+\]\s+/, $app );
166             next unless $rest; # Skip lines e.g. 'Chapter 2'
167             # Find the lemma reading.
168             my( $lemma_start, $lemma_end ) = 
169                 _find_reading_on_line( $c, $lemma, $baseline );
170             unless( $lemma_start && $lemma_end ) {
171                 print STDERR "Lemma $lemma not found; skipping readings $rest\n";
172                 next;
173             }
174             my( $rdg_start, $rdg_end, @lemma_chain );
175             if( $lemma_start eq '__PRIOR__' ) {
176                 # Deal with 'inc' readings: lemma chain should be empty, rdg_start
177                 # is a placeholder, rdg_end is $lemma_end.
178                 $rdg_start = _add_reading_placeholders( $c, $lemma_end );
179                 $rdg_end = $lemma_end;
180             } else {           
181                 @lemma_chain = $c->reading_sequence( $lemma_start, $lemma_end );
182                 # Splice in "start" and "end" placeholders on either
183                 # side of the lemma.
184                 ( $rdg_start, $rdg_end ) =
185                     _add_reading_placeholders( $c, $lemma_start, $lemma_end );
186             }
187             # For each reading, attach it to the lemma.
188             my @indiv = split( /   /, $rest );
189             my $has_rel = 0;
190             my %seen_sigla;
191             map { $seen_sigla{$_} = 0 } keys %ALL_SIGLA;
192             foreach my $rdg ( @indiv ) {
193                 # Parse the string.
194                 my( $words, $sigla, $recurse ) = parse_app_entry( $rdg );
195                 
196                 # Do something really very dodgy indeed.
197                 if( exists $sigla->{'__REL__'} && !$has_rel ) {
198                     # Handling this has to be deferred until the end, so push it
199                     # back onto @indiv and note that we've done so.
200                     $has_rel = 1;
201                     push( @indiv, $rdg );
202                     next;
203                 }
204                 
205                 my @readings;
206                 foreach my $rdg_word ( @$words ) {
207                     next if $rdg_word =~ /^__/;
208                     my $reading_id = ref( $lemma_start ) 
209                         ? $lemma_start->name : $lemma_start;
210                     $reading_id .= '_' . $lemma_end->name . '/' . $rdg_ctr++;
211                     my $reading = $c->add_reading( $reading_id );
212                     $reading->text( $rdg_word );
213                     push( @readings, $reading );
214                 }
215                 
216                 # Deal with any specials.
217                 my $lemma_sequence;
218                 if( @$words && $words->[0] eq '__LEMMA__' 
219                     && $lemma_end ne $rdg_end ) {
220                     # It's an addition (unless lemma_end eq rdg_end, in which case
221                     # it's an 'inc'.) Start from lemma rather than from placeholder.
222                     $lemma_sequence = [ $lemma_end, $rdg_end ];
223                 } elsif ( @$words && $words->[0] eq '__TRANSPOSE__' ) {
224                     # Hope it is only two or three words in the lemma.
225                     # TODO figure out how we really want to handle this
226                     @readings = reverse @lemma_chain;
227                 }
228                 $lemma_sequence = [ $rdg_start, @lemma_chain, $rdg_end ]
229                     unless $lemma_sequence;
230                 
231                 # Note which sigla we are actually dealing with.
232                 if( $sigla->{'__REL__'} ) {
233                     delete $sigla->{'__REL__'};
234                     map { $sigla->{$_} = 1 } 
235                         grep { $seen_sigla{$_} == 0 } keys %seen_sigla;
236                 } else {
237                     map { $seen_sigla{$_} = 1 } keys %$sigla;
238                 }
239
240                 # Now hook up the paths.
241                 unshift( @readings, $lemma_sequence->[0] );
242                 push( @readings, $lemma_sequence->[-1] );
243                 foreach my $i ( 1 .. $#readings ) {
244                     if( $recurse->{$i} ) {
245                         my( $rwords, $rsig ) = parse_app_entry( $recurse->{$i} );
246                         # Get the local "lemma" sequence
247                         my $llseq = [ $readings[$i], $readings[$i+1] ];
248                         if( $rwords->[0] ne '__LEMMA__' ) {
249                             unshift( @$llseq, $readings[$i-1] );
250                         } # Otherwise treat it as an addition to the last word
251                         # Create the reading nodes in $rwords
252                         # TODO Hope we don't meet ~ in a recursion
253                         my $local_rdg = [];
254                         foreach my $i ( 0 .. $#$rwords ) {
255                             next if $i == 0 && $rwords->[$i] =~ /^__/;
256                             my $reading_id = $llseq->[0]->name . '_' . 
257                                 $llseq->[-1]->name . '/' . $i;
258                             $reading_id =~ s/ATTACH//g;
259                             my $reading = $c->add_reading( $reading_id );
260                             $reading->text( $rwords->[$i] );
261                             push( @$local_rdg, $reading );
262                         }
263                         unshift( @$local_rdg, $llseq->[0] );
264                         push( @$local_rdg, $llseq->[-1] );
265                         # Add the path(s) necessary
266                         _add_sigil_path( $c, $rsig, $llseq, $local_rdg );
267                     }
268                 }
269                 _add_sigil_path( $c, $sigla, $lemma_sequence, \@readings );
270             } # end processing of $app
271         } # end foreach my $app in line
272     } # end while <line>
273     $DB::single = 1;
274     
275     # Now reconcile all the paths in the collation, and delete our
276     # temporary anchor nodes.
277     expand_all_paths( $c );    
278     
279     # Finally, calculate the ranks we've got.
280     # $c->calculate_ranks;
281 }
282
283 sub _find_reading_on_line {
284     my( $c, $lemma, $baseline, $prior ) = @_;
285     
286     if( $lemma eq 'totum' ) {
287         # We want the whole line.
288         return( $baseline->{'start'}, $baseline->{'end'} );
289     } elsif( $lemma eq 'inc' ) {
290         # We want to shove things in before the line begins.
291         return( '__PRIOR__', $baseline->{'start'} );
292     }
293     
294     my $lemma_start = $baseline->{'start'};
295     my $lemma_end;
296     my $too_far = $c->next_reading( $baseline->{'end'} );
297     my @lemma_words = split( /\s+/, $lemma );
298     
299     my %seen;
300     my $scrutinize = '';   # DEBUG variable
301     my ( $lw, $seq ) = _get_seq( $lemma_words[0] );
302     while( $lemma_start ne $too_far ) {
303         # Loop detection
304         if( $seen{ $lemma_start->name() } ) {
305             warn "Detected loop at " . $lemma_start->name . " for lemma $lemma";
306             last;
307         }
308         $seen{ $lemma_start->name() } = 1;
309         
310         # Try to match the lemma.
311         # TODO move next/prior reading methods into the reading classes,
312         # to make this more self-contained and not need to pass $c.
313         my $unmatch = 0;
314         print STDERR "Matching ".$lemma_start->text." against $lw...\n" 
315             if $scrutinize;
316         if( _norm( $lemma_start->text ) eq _norm( $lw ) ) {
317             # Skip it if we need a match that is not the first.
318             if( --$seq < 1 ) {
319                 # Now we have to compare the rest of the words here.
320                 if( scalar( @lemma_words ) > 1 ) {
321                     my $next_reading = next_real_reading( $c, $lemma_start );
322                     my $wildcard = 0;
323                     foreach my $w ( @lemma_words[1..$#lemma_words] ) {
324                         if( $w eq '---' ) {
325                             $wildcard = 1;
326                             next;
327                         }
328                         if( $wildcard ) {
329                             # This should be the word after a --- now, and the
330                             # last lemma word.
331                             my( $wst, $wend ) = _find_reading_on_line( $c, $w, 
332                                 $baseline, $lemma_start );
333                             warn "Something unexpected" unless $wst eq $wend;
334                             $lemma_end = $wend;
335                             next;
336                         }
337                         
338                         # If we got this far, there is no wildcard.  We must
339                         # match each word in sequence.
340                         my( $nlw, $nseq ) = _get_seq( $w );
341                         printf STDERR "Now matching %s against %s\n", 
342                                 $next_reading->text, $nlw
343                             if $scrutinize;
344                         if( _norm( $nlw ) eq _norm( $next_reading->text ) ) {
345                             $lemma_end = $next_reading;
346                             $next_reading = $c->next_reading( $lemma_end );
347                         } else {
348                             $unmatch = 1;
349                             last;
350                         }
351                     }
352                 } else { # single-word match, easy.
353                     $lemma_end = $lemma_start;
354                 }
355             } else { # we need the Nth match and aren't there yet
356                 $unmatch = 1;
357             }
358             $unmatch = 1 if $prior && !$seen{$prior->name};
359         }
360         last unless ( $unmatch || !defined( $lemma_end ) );
361         $lemma_end = undef;
362         $lemma_start = $c->next_reading( $lemma_start );
363     }
364     
365     unless( $lemma_end ) {
366         warn "No match found for @lemma_words";
367         return undef;
368     }   
369     return( $lemma_start, $lemma_end );
370 }
371
372 sub _add_reading_placeholders {
373     my( $collation, $lemma_start, $lemma_end ) = @_;
374     # We will splice in a 'begin' and 'end' marker on either side of the 
375     # lemma, as sort of a double-endpoint attachment in the graph.
376     # Note that all of this assumes we have a linear base graph at this
377     # point, and no diverging readings on the lemmas.
378     
379     my $start_node = $collation->prior_reading( $lemma_start );
380     unless( $start_node->name =~ /ATTACH/ ) {
381         my $sn_id = '#ATTACH_' . $lemma_start->name . '_START#';
382         my $prior = $start_node;
383         $start_node = $collation->add_reading( $sn_id );
384         $start_node->is_meta( 1 );
385         $collation->graph->del_edge( $collation->graph->edge( $prior, $lemma_start ) );
386         $collation->add_path( $prior, $start_node, $collation->baselabel );
387         $collation->add_path( $start_node, $lemma_start, $collation->baselabel );
388     }
389     return $start_node unless $lemma_end;
390
391     # Now the converse for the end.
392     my $end_node = $collation->next_reading( $lemma_end );
393     unless( $end_node->name =~ /ATTACH/ ) {
394         my $en_id = '#ATTACH_' . $lemma_end->name . '_END#';
395         my $next = $end_node;
396         $end_node = $collation->add_reading( $en_id );
397         $end_node->is_meta( 1 );
398         $collation->graph->del_edge( $collation->graph->edge( $lemma_end, $next ) );
399         $collation->add_path( $lemma_end, $end_node, $collation->baselabel );
400         $collation->add_path( $end_node, $next, $collation->baselabel );
401     }
402     
403     return( $start_node, $end_node );
404 }
405
406 # Function to parse an apparatus reading string, with reference to no other
407 # data.  Need to do this separately as readings can include readings (ugh).
408 # Try to give whatever information we might need, including recursive app
409 # entries that might need to be parsed.
410
411 sub parse_app_entry {
412     my( $rdg, ) = @_;
413     $rdg =~ s/^\s+//;
414     $rdg =~ s/\s+$//;
415     next unless $rdg;  # just in case
416     my @words = split( /\s+/, $rdg );
417     # Zero or more sigils e.g. +, followed by Armenian, 
418     # followed by (possibly modified) sigla, followed by 
419     # optional : with note.
420     my $is_add;
421     my $is_omission;
422     my $is_transposition;
423     my $is_base;
424     my $skip;
425     my @reading;
426     my $reading_sigla = {};
427     my $recursed;
428     my $sig_regex = join( '|', sort { length $b <=> length $a } keys %ALL_SIGLA );
429     while( @words ) {
430         my $bit = shift @words;
431         if( $bit eq '+' ) {
432             $is_add = 1;
433         } elsif( $bit eq 'om' ) {
434             $is_omission = 1;
435         } elsif( $bit eq '~' ) {
436             $is_transposition = 1;
437         } elsif( $bit =~ /\p{Armenian}/ ) {
438             warn "Found text in omission?!" if $is_omission;
439             push( @reading, $bit );
440         } elsif( $bit eq ':' ) {
441             # Stop processing.
442             last;
443         } elsif( $bit =~ /^\(/ ) { 
444             # It's a recursive reading within a reading. Lemmatize what we
445             # have so far and grab the extra.
446             my @new = ( $bit );
447             until( $new[-1] =~ /\)$/ ) {
448                 push( @new, shift @words );
449             }
450             my $recursed_reading = join( ' ', @new );
451             $recursed_reading =~ s/^\((.*)\)/$1/;
452             # This recursive entry refers to the last reading word(s) we
453             # saw.  Push its index+1.  We will have to come back to parse
454             # it when we are dealing with the main reading.
455             # TODO handle () as first element
456             # TODO handle - as suffix to add, i.e. make new word
457             $recursed->{@reading} = $recursed_reading;
458         } elsif( $bit =~ /^($sig_regex)(.*)$/ ) {
459             # It must be a sigil.
460             my( $sigil, $mod ) = ( $1, $2 );
461             if( $mod eq "\x{80}" ) {
462                 $reading_sigla->{$sigil} = '_PC_';
463                 $ALL_SIGLA{$sigil} = 2;  # a pre- and post-corr version exists
464             } elsif( $mod eq '*' ) {
465                 $reading_sigla->{$sigil} = '_AC_';
466                 $ALL_SIGLA{$sigil} = 2;  # a pre- and post-corr version exists
467             } else {
468                 $reading_sigla->{$sigil} = 1 unless $mod; # skip secondhand corrections
469             }
470         } elsif( $bit eq 'rel' ) {
471             # The anti-reading. All sigla except those cited.
472             $reading_sigla->{'__REL__'} = 1;
473         } elsif( $bit eq 'ed' ) {
474             # An emendation. TODO make sure all other sigla appear in readings?
475             $skip = 1;
476             last;
477         } elsif( $bit =~ /transpos/ ) {
478             # There are some transpositions not coded rigorously; skip them.
479             warn "Found hard transposition in $rdg; fix manually";
480             last;
481         } else {
482             warn "Not sure what to do with bit $bit in $rdg";
483             $skip = 1;
484             last;
485         }
486     }
487     
488     return( [], {}, {} ) if $skip;
489     # Transmogrify the reading if necessary.
490     unshift( @reading, '__LEMMA__' ) if $is_add;
491     unshift( @reading, '__TRANSPOSE__' ) if $is_transposition;
492     @reading = () if $is_omission;
493     unless( @reading || $is_omission ) {
494         # It was just sigla on a line, meaning the base changed. Thus
495         # the reading is the lemma.
496         unshift( @reading, '__LEMMA__' );
497     }
498    
499     return( \@reading, $reading_sigla, $recursed );  
500 }
501
502 # Add a path for the specified sigla to connect the reading sequence.
503 # Add an a.c. path to the base sequence if we have an explicitly p.c.
504 # reading.
505 # Also handle the paths for sigla we have already added in recursive
506 # apparatus readings (i.e. don't add a path if one already exists.)
507
508 sub _add_sigil_path {
509     my( $c, $sigla, $base_sequence, $reading_sequence ) = @_;
510     my %skip;
511     foreach my $sig ( keys %$sigla ) {
512         my $use_sig = $sigla->{$sig} eq '_AC_' ? $sig.$c->ac_label : $sig;
513         foreach my $i ( 0 .. $#{$reading_sequence}-1 ) {
514             if( $skip{$use_sig} ) {
515                 next if !_has_prior_reading( $reading_sequence->[$i], $use_sig );
516                 $skip{$use_sig} = 0;
517             }
518             if( _has_next_reading( $reading_sequence->[$i], $use_sig ) ) {
519                 $skip{$use_sig} = 1;
520                 next;
521             }
522             $c->add_path( $reading_sequence->[$i], $reading_sequence->[$i+1], $use_sig );
523         }
524         if( $sigla->{$sig} eq '_PC_') {
525             $use_sig = $sig.$c->ac_label;
526             foreach my $i ( 0 .. $#{$base_sequence}-1 ) {
527                 if( $skip{$use_sig} ) {
528                     next if !_has_prior_reading( $reading_sequence->[$i], $use_sig );
529                     $skip{$use_sig} = 0;
530                 }
531                 if( _has_next_reading( $reading_sequence->[$i], $use_sig ) ) {
532                     $skip{$use_sig} = 1;
533                     next;
534                 }
535                 $c->add_path( $base_sequence->[$i], $base_sequence->[$i+1], $use_sig );
536             }
537         }
538     }
539 }
540
541 # Walk the collation for all witness paths, delete the ATTACH anchor nodes,
542 # and then nuke and re-draw all edges (thus getting rid of the base).
543
544 sub expand_all_paths { 
545     my( $c ) = @_;
546     
547     # Walk the collation and fish out the paths for each witness
548     foreach my $sig ( keys %ALL_SIGLA ) {
549         my $wit = $c->tradition->witness( $sig );
550         my @path = grep { $_->name !~ /ATTACH/ } 
551             $c->reading_sequence( $c->start, $c->end, $sig );
552         $wit->path( \@path );
553         if( $ALL_SIGLA{$sig} > 1 ) {
554             my @ac_path = grep { $_->name !~ /ATTACH/ } 
555                 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label, $sig );
556             $wit->uncorrected_path( \@ac_path );
557         }
558     }   
559     
560     # Delete the anchors
561     foreach my $anchor ( grep { $_->name =~ /ATTACH/ } $c->readings ) {
562         $c->del_reading( $anchor );
563     }
564     # Delete all edges
565     map { $c->del_path( $_ ) } $c->paths;
566     
567     # Make the path edges
568     $c->make_witness_paths();
569 }
570
571 sub _get_seq {
572     my( $str ) = @_;
573     my $seq = 1;
574     my $lw = $str;
575     if( $str =~ /^(.*)(\d)\x{b0}$/ ) {
576         ( $lw, $seq) = ( $1, $2 );
577     }
578     return( $lw, $seq );
579 }
580
581 # Normalize to lowercase, no punct
582 sub _norm {
583     my( $str ) = @_;
584     $str =~ s/[^[:alnum:]]//g;
585     return lc( $str );
586 }
587
588 sub _has_next_reading {
589     my( $rdg, $sigil ) = @_;
590     return grep { $_->label eq $sigil } $rdg->outgoing();
591 }
592 sub _has_prior_reading {
593     my( $rdg, $sigil ) = @_;
594     return grep { $_->label eq $sigil } $rdg->incoming();
595 }
596 sub next_real_reading {
597     my( $c, $rdg ) = @_;
598     while( my $r = $c->next_reading( $rdg ) ) {
599         return $r unless $r->is_meta;
600         return $r if $r eq $c->end;
601         $rdg = $r;
602     }
603 }
604 # For debugging
605 sub rstr {
606     my @l = @_;
607     if( ref( $_[0] ) eq 'ARRAY' ) {
608         @l = @{$_[0]};
609     }
610     my $str = join( ' ', map { $_->text } @l );
611     return $str;
612 }
613
614 1;