work in progress
[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
35 sub parse {
36         my( $tradition, $xml_str ) = @_;
37         my $c = $tradition->collation;  # Some shorthand
38         
39         # First, parse the XML.
40         my $parser = XML::LibXML->new();
41         my $doc = $parser->parse_string( $xml_str );
42         my $tei = $doc->documentElement();
43         my $xpc = XML::LibXML::XPathContext->new( $tei );
44
45         # CTE uses a DTD rather than any xmlns-based parsing.  Thus we
46         # need no namespace handling.
47
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( './abbr/descendant::text()', $wit_el );
53                 my $sig = _stringify_sigil( @sig_parts );
54                 $tradition->add_witness( sigil => $sig, source => $wit_el->toString() );
55                 $sigil_for{'#'.$id} = $sig;  # Make life easy by keying on the ID ref syntax
56         }
57
58         # Now go through the text and find the base tokens, apparatus tags, and
59         # anchors.  Make a giant array of all of these things in sequence.
60         # TODO consider combining this with creation of graph below
61         my @base_text;
62         foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
63                 foreach my $xn ( $pg_el->childNodes ) {
64                         push( @base_text, _get_base( $xn ) );
65                 }
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         my $counter = 0;
73         my $last = $c->start;
74         foreach my $item ( @base_text ) {
75             my $r;
76         if( $item->{'type'} eq 'token' ) {
77             $r = $c->add_reading( 'n'.$counter++ );
78             $r->text( $item->{'content'} );
79         } elsif ( $item->{'type'} eq 'anchor' ) {
80             $r = $c->add_reading( '#ANCHOR_' . $item->{'content'} . '#' );
81         } elsif ( $item->{'type'} eq 'app' ) {
82             my $tag = '#APP_' . $counter++ . '#';
83             $r = $c->add_reading( $tag );
84             $apps{$tag} = $item->{'content'};
85         }
86         $c->add_path( $last, $r, 'BASE' );
87         $last = $r;
88     }
89     $c->add_path( $last, $c->end, 'BASE' );
90     
91     # Now we can parse the apparatus entries, and add the variant readings 
92     # to the graph.
93     
94     foreach my $app_id ( keys %apps ) {
95         _add_readings( $c, $app_id );
96     }
97     
98     # With the variant readings added, we now have to walk the graph for
99     # each witness and add an explicit path wherever there is not a divergence
100     # from BASE.  Thus we will also construct $wit->path.
101         $DB::single = 1;
102     foreach my $wit ( $tradition->witnesses ) {
103         my $sig = $wit->sigil;
104         my @wit_path = $c->reading_sequence( $c->start, $c->end, $sig, 'BASE' );
105         my $cur = $c->start;
106         foreach my $n ( @wit_path ) {
107             next if $cur eq $c->start;
108             my @paths = $cur->edges_to( $n );
109             unless( grep { $_->name eq $sig } @paths ) {
110                 $c->add_path( $cur, $n, $sig );
111             }
112         }
113         $wit->path( \@wit_path );
114     }       
115     
116     # Collated readings are now on the graph, so now we get to remove
117     # all BASE edges and all app/anchor nodes.
118     foreach my $p ( $c->paths ) {
119         $c->del_path( $p ) if $p->name eq 'BASE';
120     }
121     foreach my $n ( $c->readings ) {
122         if( $n->name =~ /^\#A(PP|NCHOR)/ ) {
123             # Pair up incoming / outgoing edges with the same label
124             my( %incoming, %outgoing );
125             foreach my $e ( $n->incoming ) {
126                 $incoming{$e->name} = $e->from;
127                 $c->del_path( $e );
128             }
129             foreach my $e ( $n->outgoing ) {
130                 $outgoing{$e->name} = $e->to;
131                 $c->del_path( $e );
132             }
133             foreach my $w ( keys %incoming ) {
134                 my $from = $incoming{$w};
135                 my $to = delete $outgoing{$w};
136                 warn "No outgoing edge on ".$n->name." for wit $w" unless $to;
137                 $c->add_path( $from, $to, $w );
138             }
139             foreach my $w ( keys %outgoing ) {
140                 warn "Found no incoming edge on ".$n->name." for wit $w";
141             }
142             $c->del_reading( $n );
143         }
144     }
145 }
146
147 sub _stringify_sigil {
148     my( @nodes ) = @_;
149     my @parts = grep { /\w/ } map { $_->data } @nodes;
150     return join( '', @parts );
151 }
152
153 ## Recursive little helper function to help us navigate through nested
154 ## XML, picking out the words, the apparatus, and the anchors.
155
156 sub _get_base {
157         my( $xn ) = @_;
158         my @readings;
159         if( $xn->nodeType == XML_TEXT_NODE ) {
160             # Base text, just split the words on whitespace and add them 
161             # to our sequence.
162                 my $str = $xn->data;
163                 $str =~ s/^\s+//;
164                 foreach my $w ( split( /\s+/, $str ) ) {
165                         push( @readings, { 'type' => 'token', 'content' => $w } );
166                 }
167         } elsif( $xn->nodeName eq 'hi' ) {
168                 # Recurse as if the hi weren't there.
169                 foreach( $xn->childNodes ) {
170                         push( @readings, _get_base( $_ ) );
171                 }
172         } elsif( $xn->nodeName eq 'app' ) {
173                 # Apparatus, just save the entire XML node.
174                 push( @readings, { 'type' => 'app', 'content' => $xn } );
175         } elsif( $xn->nodeName eq 'anchor' ) {
176                 # Anchor to mark the end of some apparatus; save its ID.
177                 push( @readings, { 'type' => 'anchor', 
178                     'content' => $xn->getAttribute( 'xml:id' ) } );
179         } elsif ( $xn->nodeName ne 'note' ) {  # Any tag we don't know to disregard
180             print STDERR "Unrecognized tag " . $xn->nodeName . "\n";
181         }
182         return @readings;
183 }
184
185 sub _add_readings {
186     my( $c, $app_id ) = @_;
187     my $xn = $apps{$app_id};
188     my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
189     # Get the lemma, which is all the readings between app and anchor,
190     # excluding other apps or anchors.
191     my @lemma = _return_lemma( $c, $app_id, $anchor );
192     my $lemma_str = join( ' ', grep { $_ !~ /^\#/ } map { $_->text } @lemma );
193     
194     # For each reading, send its text to 'interpret' along with the lemma,
195     # and then save the list of witnesses that these tokens belong to.
196     my %wit_rdgs;  # Maps from witnesses to the variant text
197     my %wit_details; # Maps from witnesses to the witness detail e.g. a.c.
198     my $ctr = 0;
199     my $tag = $app_id;
200     $tag =~ s/^\#APP_(.*)\#$/$1/;
201     foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
202         my @text;
203         my $wits = $rdg->getAttribute( 'wit' );
204         foreach ( $rdg->childNodes ) {
205             push( @text, _get_base( $_ ) );
206         }
207         my $interpreted = @text 
208             ? interpret( join( ' ', map { $_->{'content'} } @text ), $lemma_str ) 
209             : '';
210         my @rdg_nodes;
211         foreach my $w ( split( /\s+/, $interpreted ) ) {
212             my $r = $c->add_reading( $tag . "/" . $ctr++ );
213             $r->text( $w );
214             push( @rdg_nodes, $r );
215         }
216         $wit_rdgs{$wits} = \@rdg_nodes;
217         # Does the reading have an ID? If so it probably has a witDetail
218         # attached, and that may be something we need to know.  For now,
219         # save the reading ID.
220         if( $rdg->hasAttribute( 'xml:id' ) ) {
221                 $wit_details{$wits} = $rdg->getAttribute( 'xml:id' );
222         }
223     }
224     # Now go through the available witDetails and, er, do something
225     # foreach my $d ( $xn->getChildrenByTagName( 'witDetail' ) ) {
226         # my $referent = 
227     
228     # Now collate the variant readings, since it is not done for us.
229     collate_variants( $c, \@lemma, values %wit_rdgs );
230     
231     # Now add the witness paths for each reading.
232     foreach my $wit_str ( keys %wit_rdgs ) {
233         my @wits = get_sigla( $wit_str );
234         my $rdg_list = $wit_rdgs{$wit_str};
235         _add_wit_path( $c, $rdg_list, $app_id, $anchor, @wits );
236     }
237 }
238
239 sub _anchor_name {
240     my $xmlid = shift;
241     $xmlid =~ s/^\#//;
242     return sprintf( "#ANCHOR_%s#", $xmlid );
243 }
244
245 sub _return_lemma {
246     my( $c, $app, $anchor ) = @_;
247     my $app_node = $c->graph->node( $app );
248     my $anchor_node = $c->graph->node( $anchor );
249     my @nodes = grep { $_->name !~ /^\#A(PP|NCHOR)$/ } 
250         $c->reading_sequence( $app_node, $anchor_node, 'BASE' );
251     return @nodes;
252 }
253
254 sub interpret {
255         # A utility function to change apparatus-ese into a full variant.
256         my( $reading, $lemma ) = @_;
257         return $reading if $reading eq $lemma;
258         my $oldreading = $reading;
259         # $lemma =~ s/\s+[[:punct:]]+$//;
260         # $reading =~ s/\s*\(?sic([\s\w.]+)?\)?$//;
261         my @words = split( /\s+/, $lemma );
262         if( $reading =~ /^(.*) praem.$/ ) {
263                 $reading = "$1 $lemma";
264         } elsif( $reading =~ /^(.*) add.$/ ) {
265                 $reading = "$lemma $1";
266         } elsif( $reading eq 'om.' ) {
267                 $reading = '';
268         } elsif( $reading eq 'inv.' ) {
269                 # Hope it is two words.
270                 print STDERR "WARNING: want to invert a lemma that is not two words\n" 
271                         unless scalar( @words ) == 2;
272                 $reading = join( ' ', reverse( @words ) );
273         } elsif( $reading eq 'iter.' ) {
274                 # Repeat the lemma
275                 $reading = "$lemma $lemma";
276          } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
277                 # The first and last N words captured should replace the first and
278                 # last N words of the lemma.
279                 my @begin = split( /\s+/, $1 );
280                 my @end = split( /\s+/, $2 );
281                 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
282                         # Something is wrong and we can't do the splice.
283                         print STDERR "ERROR: $lemma is too short to accommodate $oldreading\n";
284                 } else {
285                         splice( @words, 0, scalar @begin, @begin );
286                         splice( @words, -(scalar @end), scalar @end, @end );
287                         $reading = join( ' ', @words );
288                 }
289         }
290         print STDERR "Interpreted $oldreading as $reading given $lemma\n";
291         return $reading;
292 }
293
294 sub get_sigla {
295     my $witstr = shift;
296     my @xml_ids = split( /\s+/, $witstr );
297     my @sigs = map { $sigil_for{$_} } @xml_ids;
298     return @sigs;
299 }
300
301 sub _add_wit_path {
302     my( $c, $rdg, $app, $anchor, @wits ) = @_;
303     my @nodes = @$rdg;
304     push( @nodes, $c->graph->node( $anchor ) );
305     
306     my $cur = $c->graph->node( $app );
307     foreach my $n ( @nodes ) {
308         foreach my $w ( @wits ) {
309             $c->add_path( $cur, $n, $w );
310         }
311         $cur = $n;
312     }
313 }
314
315 =back
316
317 =head1 LICENSE
318
319 This package is free software and is provided "as is" without express
320 or implied warranty.  You can redistribute it and/or modify it under
321 the same terms as Perl itself.
322
323 =head1 AUTHOR
324
325 Tara L Andrews, aurum@cpan.org
326
327 =cut
328
329 1;
330