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