split off stemma analysis modules from base Tradition layer
[scpubgit/stemmatology.git] / base / lib / Text / Tradition / Parser / CTE.pm
1 package Text::Tradition::Parser::CTE;
2
3 use strict;
4 use warnings;
5 use Encode qw/ decode /;
6 use Text::Tradition::Error;
7 use Text::Tradition::Parser::Util qw/ collate_variants /;
8 use XML::LibXML;
9 use XML::LibXML::XPathContext;
10
11 =head1 NAME
12
13 Text::Tradition::Parser::CTE
14
15 =head1 DESCRIPTION
16
17 Parser module for Text::Tradition, given a TEI file exported from
18 Classical Text Editor.
19
20 =head1 METHODS
21
22 =over
23
24 =item B<parse>
25
26 my @apparatus = read( $xml_file );
27
28 Takes a Tradition object and a TEI file exported from Classical Text
29 Editor using double-endpoint-attachment critical apparatus encoding; 
30 initializes the Tradition from the file.
31
32 =cut
33
34 my %sigil_for;  # Save the XML IDs for witnesses.
35 my %apps;       # Save the apparatus XML for a given ID.    
36 my %has_ac;     # Keep track of witnesses that have corrections.
37
38 sub parse {
39         my( $tradition, $opts ) = @_;
40         my $c = $tradition->collation;  # Some shorthand
41         
42         # First, parse the XML.
43     my( $tei, $xpc ) = _remove_formatting( $opts );
44     return unless $tei; # we have already warned.
45
46         # CTE uses a DTD rather than any xmlns-based parsing.  Thus we
47         # need no namespace handling.
48         # Get the witnesses and create the witness objects.
49         foreach my $wit_el ( $xpc->findnodes( '//sourceDesc/listWit/witness' ) ) {
50                 # The witness xml:id is used internally, and is *not* the sigil name.
51                 my $id= $wit_el->getAttribute( 'xml:id' );
52                 my @sig_parts = $xpc->findnodes( 'descendant::text()', $wit_el );
53                 my $sig = _stringify_sigil( @sig_parts );
54                 print STDERR "Adding witness $sig\n";
55                 $tradition->add_witness( sigil => $sig, sourcetype => 'collation' );
56                 $sigil_for{'#'.$id} = $sig;  # Make life easy by keying on the ID ref syntax
57         }
58         
59         # Now go through the text and find the base tokens, apparatus tags, and
60         # anchors.  Make a giant array of all of these things in sequence.
61         # TODO consider combining this with creation of graph below
62         my @base_text;
63         foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
64                 foreach my $xn ( $pg_el->childNodes ) {
65                         push( @base_text, _get_base( $xn ) );
66                 }
67         }
68         # We now have to work through this array applying the alternate 
69         # apparatus readings to the base text.  Essentially we will put 
70         # everything on the graph, from which we will delete the apps and
71         # anchors when we are done.
72         
73         # First, put the base tokens, apps, and anchors in the graph.
74         my $counter = 0;
75         my $last = $c->start;
76         foreach my $item ( @base_text ) {
77             my $r;
78         if( $item->{'type'} eq 'token' ) {
79             $r = $c->add_reading( { id => 'n'.$counter++, 
80                                                         text => $item->{'content'} } );
81         } elsif ( $item->{'type'} eq 'anchor' ) {
82             $r = $c->add_reading( { id => '__ANCHOR_' . $item->{'content'} . '__', 
83                                                         is_ph => 1 } );
84         } elsif ( $item->{'type'} eq 'app' ) {
85             my $tag = '__APP_' . $counter++ . '__';
86             $r = $c->add_reading( { id => $tag, is_ph => 1 } );
87             $apps{$tag} = $item->{'content'};
88         }
89         $c->add_path( $last, $r, $c->baselabel );
90         $last = $r;
91     }
92     $c->add_path( $last, $c->end, $c->baselabel );
93     
94     # Now we can parse the apparatus entries, and add the variant readings 
95     # to the graph.
96     
97     foreach my $app_id ( keys %apps ) {
98         _add_readings( $c, $app_id );
99     }
100     
101     # Finally, add explicit witness paths, remove the base paths, and remove
102     # the app/anchor tags.
103     expand_all_paths( $c );
104
105     # Save the text for each witness so that we can ensure consistency
106     # later on
107         $tradition->collation->text_from_paths();       
108         $tradition->collation->calculate_ranks();
109         $tradition->collation->flatten_ranks();
110 }
111
112 sub _stringify_sigil {
113     my( @nodes ) = @_;
114     my @parts = grep { /\w/ } map { $_->data } @nodes;
115     my $whole = join( '', @parts );
116     $whole =~ s/\W//g;
117     return $whole;
118 }
119
120 # Get rid of all the formatting elements that get in the way of tokenization.
121 sub _remove_formatting {
122         my( $opts ) = @_;
123         
124         # First, parse the original XML
125         my $parser = XML::LibXML->new();
126     my $doc;
127     if( exists $opts->{'string'} ) {
128         $doc = $parser->parse_string( $opts->{'string'} );
129     } elsif ( exists $opts->{'file'} ) {
130         $doc = $parser->parse_file( $opts->{'file'} );
131     } else {
132         warn "Could not find string or file option to parse";
133         return;
134     }
135
136     # Second, remove the formatting
137         my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
138         my @useless = $xpc->findnodes( '//hi' );
139         foreach my $n ( @useless ) {
140                 my $parent = $n->parentNode();
141                 my @children = $n->childNodes();
142                 my $first = shift @children;
143                 $parent->replaceChild( $first, $n );
144                 foreach my $c ( @children ) {
145                         $parent->insertAfter( $c, $first );
146                         $first = $c;
147                 }
148         }
149         
150         # Third, write out and reparse to merge the text nodes.
151         my $enc = $doc->encoding || 'UTF-8';
152         my $result = decode( $enc, $doc->toString() );
153         my $tei = $parser->parse_string( $result )->documentElement;
154         unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
155                 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
156         }
157         $xpc = XML::LibXML::XPathContext->new( $tei );
158         return( $tei, $xpc );
159 }
160
161 ## Helper function to help us navigate through nested XML, picking out 
162 ## the words, the apparatus, and the anchors.
163
164 sub _get_base {
165         my( $xn ) = @_;
166         my @readings;
167         if( $xn->nodeType == XML_TEXT_NODE ) {
168             # Base text, just split the words on whitespace and add them 
169             # to our sequence.
170                 my $str = $xn->data;
171                 $str =~ s/^\s+//;
172                 my @tokens = split( /\s+/, $str );
173                 push( @readings, map { { 'type' => 'token', 'content' => $_ } } @tokens );
174         } elsif( $xn->nodeName eq 'app' ) {
175                 # Apparatus, just save the entire XML node.
176                 push( @readings, { 'type' => 'app', 'content' => $xn } );
177         } elsif( $xn->nodeName eq 'anchor' ) {
178                 # Anchor to mark the end of some apparatus; save its ID.
179                 push( @readings, { 'type' => 'anchor', 
180                     'content' => $xn->getAttribute( 'xml:id' ) } );
181         } elsif ( $xn->nodeName ne 'note' ) {  # Any tag we don't know to disregard
182             print STDERR "Unrecognized tag " . $xn->nodeName . "\n";
183         }
184         return @readings;
185 }
186
187 sub _append_tokens {
188         my( $list, @tokens ) = @_;
189         if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
190                 # The list evidently ended mid-word; join the next token onto it.
191                 my $t = shift @tokens;
192                 if( ref $t && $t->{'type'} eq 'token' ) {
193                         # Join the word
194                         $t = $t->{'content'};
195                 } elsif( ref $t ) {
196                         # An app or anchor intervened; end the word.
197                         unshift( @tokens, $t );
198                         $t = '';
199                 }
200                 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
201         }
202         foreach my $t ( @tokens ) {
203                 unless( ref( $t ) ) {
204                         $t = { 'type' => 'token', 'content' => $t };
205                 }
206                 push( @$list, $t );
207         }
208 }
209
210 sub _add_readings {
211     my( $c, $app_id ) = @_;
212     my $xn = $apps{$app_id};
213     my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
214     # Get the lemma, which is all the readings between app and anchor,
215     # excluding other apps or anchors.
216     my @lemma = _return_lemma( $c, $app_id, $anchor );
217     my $lemma_str = join( ' ', grep { $_ !~ /^__/ } map { $_->text } @lemma );
218     
219     # For each reading, send its text to 'interpret' along with the lemma,
220     # and then save the list of witnesses that these tokens belong to.
221     my %wit_rdgs;  # Maps from witnesses to the variant text
222     my $ctr = 0;
223     my $tag = $app_id;
224     $tag =~ s/^\__APP_(.*)\__$/$1/;
225
226     foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
227         my @text;
228         foreach ( $rdg->childNodes ) {
229             push( @text, _get_base( $_ ) );
230         }
231         my( $interpreted, $flag ) = ( '', undef );
232         if( @text ) {
233                 ( $interpreted, $flag ) = interpret( 
234                         join( ' ', map { $_->{'content'} } @text ), $lemma_str );
235         }
236         next if( $interpreted eq $lemma_str ) && !$flag;  # Reading is lemma.
237         
238         my @rdg_nodes;
239         if( $interpreted eq '#LACUNA#' ) {
240                 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
241                                                                                          is_lacuna => 1 } ) );
242         } else {
243                         foreach my $w ( split( /\s+/, $interpreted ) ) {
244                                 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
245                                                                                    text => $w } );
246                                 push( @rdg_nodes, $r );
247                         }
248         }
249         # For each listed wit, save the reading.
250         foreach my $wit ( split( /\s+/, $rdg->getAttribute( 'wit' ) ) ) {
251                         $wit .= $flag if $flag;
252             $wit_rdgs{$wit} = \@rdg_nodes;
253         }
254                         
255         # Does the reading have an ID? If so it probably has a witDetail
256         # attached, and we need to read it.
257         if( $rdg->hasAttribute( 'xml:id' ) ) {
258                 warn "Witdetail on meta reading" if $flag; # this could get complicated.
259             my $rid = $rdg->getAttribute( 'xml:id' );
260             my $xpc = XML::LibXML::XPathContext->new( $xn );
261             my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
262             foreach my $d ( @details ) {
263                 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
264             }
265         }
266     }       
267         
268     # Now collate the variant readings, since it is not done for us.
269     collate_variants( $c, \@lemma, values %wit_rdgs );
270         
271     # Now add the witness paths for each reading.
272     foreach my $wit_id ( keys %wit_rdgs ) {
273         my $witstr = get_sigil( $wit_id, $c );
274         my $rdg_list = $wit_rdgs{$wit_id};
275         _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
276     }
277 }
278
279 sub _anchor_name {
280     my $xmlid = shift;
281     $xmlid =~ s/^\#//;
282     return sprintf( "__ANCHOR_%s__", $xmlid );
283 }
284
285 sub _return_lemma {
286     my( $c, $app, $anchor ) = @_;
287     my @nodes = grep { $_->id !~ /^__A(PP|NCHOR)/ } 
288         $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
289                 $c->baselabel );
290     return @nodes;
291 }
292
293 sub interpret {
294         # A utility function to change apparatus-ese into a full variant.
295         my( $reading, $lemma ) = @_;
296         return $reading if $reading eq $lemma;
297         my $oldreading = $reading;
298         # $lemma =~ s/\s+[[:punct:]]+$//;
299         my $flag;  # In case of p.c. indications
300         my @words = split( /\s+/, $lemma );
301         if( $reading =~ /^(.*) praem.$/ ) {
302                 $reading = "$1 $lemma";
303         } elsif( $reading =~ /^(.*) add.$/ ) {
304                 $reading = "$lemma $1";
305         } elsif( $reading =~ /add. alia manu/
306                 || $reading =~ /inscriptionem compegi e/ # TODO huh?
307                 || $reading eq 'inc.'  # TODO huh?
308                 ) {
309                 # Ignore it.
310                 $reading = $lemma;
311         } elsif( $reading =~ /locus [uv]acuus/
312             || $reading eq 'def.'
313             || $reading eq 'illeg.'
314             || $reading eq 'onleesbar'
315             ) {
316                 $reading = '#LACUNA#';
317         } elsif( $reading eq 'om.' ) {
318                 $reading = '';
319         } elsif( $reading =~ /^in[uv]\.$/ 
320                          || $reading eq 'transp.' ) {
321                 # Hope it is two words.
322                 print STDERR "WARNING: want to invert a lemma that is not two words\n" 
323                         unless scalar( @words ) == 2;
324                 $reading = join( ' ', reverse( @words ) );
325         } elsif( $reading =~ /^iter(\.|at)$/ ) {
326                 # Repeat the lemma
327                 $reading = "$lemma $lemma";
328         } elsif( $reading eq 'in marg.' ) {
329                 # There was nothing before a correction.
330                 $reading = '';
331                 $flag = '_ac';
332         } elsif( $reading =~ /^(.*?)\s*\(?sic([\s\w.]+)?\)?$/ ) {
333                 # Discard any 'sic' notation; indeed, indeed.
334                 $reading = $1;
335         } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
336                 # The first and last N words captured should replace the first and
337                 # last N words of the lemma.
338                 my @begin = split( /\s+/, $1 );
339                 my @end = split( /\s+/, $2 );
340                 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
341                         # Something is wrong and we can't do the splice.
342                         print STDERR "ERROR: $lemma is too short to accommodate $oldreading\n";
343                 } else {
344                         splice( @words, 0, scalar @begin, @begin );
345                         splice( @words, -(scalar @end), scalar @end, @end );
346                         $reading = join( ' ', @words );
347                 }
348         }
349         if( $oldreading ne $reading || $flag || $oldreading =~ /\./ ) {
350                 my $int = $reading;
351                 $int .= " ($flag)" if $flag;
352                 print STDERR "Interpreted $oldreading as $int given $lemma\n";
353         }
354         return( $reading, $flag );
355 }
356
357 sub _parse_wit_detail {
358     my( $detail, $readings, $lemma ) = @_;
359     my $wit = $detail->getAttribute( 'wit' );
360     my $content = $detail->textContent;
361     if( $content =~ /a\.\s*c\./ ) {
362         # Replace the key in the $readings hash
363         my $rdg = delete $readings->{$wit};
364         $readings->{$wit.'_ac'} = $rdg;
365         $has_ac{$sigil_for{$wit}} = 1;
366     } elsif( $content =~ /p\.\s*c\./ ) {
367         # If no key for the wit a.c. exists, add one pointing to the lemma
368         unless( exists $readings->{$wit.'_ac'} ) {
369             $readings->{$wit.'_ac'} = $lemma;
370         }
371         $has_ac{$sigil_for{$wit}} = 1;
372     } # else don't bother just yet
373 }
374
375 sub get_sigil {
376     my( $xml_id, $c ) = @_;
377     if( $xml_id =~ /^(.*)_ac$/ ) {
378         my $real_id = $1;
379         return $sigil_for{$real_id} . $c->ac_label;
380     } else {
381         return $sigil_for{$xml_id};
382     }
383 }
384
385 sub expand_all_paths { 
386     my( $c ) = @_;
387     
388     # Walk the collation and fish out the paths for each witness
389     foreach my $wit ( $c->tradition->witnesses ) {
390         my $sig = $wit->sigil;
391         my @path = grep { !$_->is_ph } 
392             $c->reading_sequence( $c->start, $c->end, $sig );
393         $wit->path( \@path );
394         if( $has_ac{$sig} ) {
395             my @ac_path = grep { !$_->is_ph } 
396                 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
397             $wit->uncorrected_path( \@ac_path );
398         }
399     }   
400     
401     # Delete the anchors
402     foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
403         $c->del_reading( $anchor );
404     }
405     # Delete the base edges
406     map { $c->del_path( $_, $c->baselabel ) } $c->paths;
407     
408     # Make the path edges
409     $c->make_witness_paths();
410 }
411
412 sub _add_wit_path {
413     my( $c, $rdg, $app, $anchor, $wit ) = @_;
414     my @nodes = @$rdg;
415     push( @nodes, $c->reading( $anchor ) );
416     
417     my $cur = $c->reading( $app );
418     foreach my $n ( @nodes ) {
419         $c->add_path( $cur, $n, $wit );
420         $cur = $n;
421     }
422 }
423
424 sub throw {
425         Text::Tradition::Error->throw( 
426                 'ident' => 'Parser::CTE error',
427                 'message' => $_[0],
428                 );
429 }
430
431 =back
432
433 =head1 LICENSE
434
435 This package is free software and is provided "as is" without express
436 or implied warranty.  You can redistribute it and/or modify it under
437 the same terms as Perl itself.
438
439 =head1 AUTHOR
440
441 Tara L Andrews, aurum@cpan.org
442
443 =cut
444
445 1;
446