b21da1b3600d06b4187975722ceec6fadb02f0be
[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( 'n'.$counter++ );
89             $r->text( $item->{'content'} );
90         } elsif ( $item->{'type'} eq 'anchor' ) {
91             $r = $c->add_reading( '#ANCHOR_' . $item->{'content'} . '#' );
92             $r->is_meta(1);
93         } elsif ( $item->{'type'} eq 'app' ) {
94             my $tag = '#APP_' . $counter++ . '#';
95             $r = $c->add_reading( $tag );
96             $r->is_meta(1);
97             $apps{$tag} = $item->{'content'};
98         }
99         $c->add_path( $last, $r, $c->baselabel );
100         $last = $r;
101     }
102     $c->add_path( $last, $c->end, $c->baselabel );
103     
104     # Now we can parse the apparatus entries, and add the variant readings 
105     # to the graph.
106     
107     foreach my $app_id ( keys %apps ) {
108         _add_readings( $c, $app_id );
109     }
110     
111     # Finally, add explicit witness paths, remove the base paths, and remove
112     # the app/anchor tags.
113     expand_all_paths( $c );
114 }
115
116 sub _stringify_sigil {
117     my( @nodes ) = @_;
118     my @parts = grep { /\w/ } map { $_->data } @nodes;
119     return join( '', @parts );
120 }
121
122 ## Recursive little helper function to help us navigate through nested
123 ## XML, picking out the words, the apparatus, and the anchors.
124
125 sub _get_base {
126         my( $xn ) = @_;
127         my @readings;
128         if( $xn->nodeType == XML_TEXT_NODE ) {
129             # Base text, just split the words on whitespace and add them 
130             # to our sequence.
131             # TODO consider that XML markup might appear mid-token.
132                 my $str = $xn->data;
133                 $str =~ s/^\s+//;
134                 foreach my $w ( split( /\s+/, $str ) ) {
135                     # HACK to cope with mismatched doublequotes
136                     $w =~ s/\"//g;
137                         push( @readings, { 'type' => 'token', 'content' => $w } );
138                 }
139         } elsif( $xn->nodeName eq 'hi' ) {
140                 # Recurse as if the hi weren't there.
141                 foreach( $xn->childNodes ) {
142                         push( @readings, _get_base( $_ ) );
143                 }
144         } elsif( $xn->nodeName eq 'app' ) {
145                 # Apparatus, just save the entire XML node.
146                 push( @readings, { 'type' => 'app', 'content' => $xn } );
147         } elsif( $xn->nodeName eq 'anchor' ) {
148                 # Anchor to mark the end of some apparatus; save its ID.
149                 push( @readings, { 'type' => 'anchor', 
150                     'content' => $xn->getAttribute( 'xml:id' ) } );
151         } elsif ( $xn->nodeName ne 'note' ) {  # Any tag we don't know to disregard
152             print STDERR "Unrecognized tag " . $xn->nodeName . "\n";
153         }
154         return @readings;
155 }
156
157 sub _add_readings {
158     my( $c, $app_id ) = @_;
159     my $xn = $apps{$app_id};
160     my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
161     # Get the lemma, which is all the readings between app and anchor,
162     # excluding other apps or anchors.
163     my @lemma = _return_lemma( $c, $app_id, $anchor );
164     my $lemma_str = join( ' ', grep { $_ !~ /^\#/ } map { $_->text } @lemma );
165     
166     # For each reading, send its text to 'interpret' along with the lemma,
167     # and then save the list of witnesses that these tokens belong to.
168     my %wit_rdgs;  # Maps from witnesses to the variant text
169     my $ctr = 0;
170     my $tag = $app_id;
171     $tag =~ s/^\#APP_(.*)\#$/$1/;
172     $DB::single = 1 if $tag < 2;
173     foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
174         my @text;
175         foreach ( $rdg->childNodes ) {
176             push( @text, _get_base( $_ ) );
177         }
178         my $interpreted = @text 
179             ? interpret( join( ' ', map { $_->{'content'} } @text ), $lemma_str ) 
180             : '';
181         my @rdg_nodes;
182         foreach my $w ( split( /\s+/, $interpreted ) ) {
183             my $r = $c->add_reading( $tag . "/" . $ctr++ );
184             $r->text( $w );
185             push( @rdg_nodes, $r );
186         }
187         
188         # For each listed wit, save the reading.
189         foreach my $wit ( split( /\s+/, $rdg->getAttribute( 'wit' ) ) ) {
190             $wit_rdgs{$wit} = \@rdg_nodes;
191         }
192         # Does the reading have an ID? If so it probably has a witDetail
193         # attached, and we need to read it.
194         if( $rdg->hasAttribute( 'xml:id' ) ) {
195             my $rid = $rdg->getAttribute( 'xml:id' );
196             my $xpc = XML::LibXML::XPathContext->new( $xn );
197             my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
198             foreach my $d ( @details ) {
199                 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
200             }
201         }
202     }       
203         
204     # Now collate the variant readings, since it is not done for us.
205     collate_variants( $c, \@lemma, values %wit_rdgs );    
206     
207     # Now add the witness paths for each reading.
208     foreach my $wit_id ( keys %wit_rdgs ) {
209         my $witstr = get_sigil( $wit_id, $c );
210         my $rdg_list = $wit_rdgs{$wit_id};
211         _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
212     }
213 }
214
215 sub _anchor_name {
216     my $xmlid = shift;
217     $xmlid =~ s/^\#//;
218     return sprintf( "#ANCHOR_%s#", $xmlid );
219 }
220
221 sub _return_lemma {
222     my( $c, $app, $anchor ) = @_;
223     my $app_node = $c->graph->node( $app );
224     my $anchor_node = $c->graph->node( $anchor );
225     my @nodes = grep { $_->name !~ /^\#A(PP|NCHOR)/ } 
226         $c->reading_sequence( $app_node, $anchor_node, $c->baselabel );
227     return @nodes;
228 }
229
230 sub interpret {
231         # A utility function to change apparatus-ese into a full variant.
232         my( $reading, $lemma ) = @_;
233         return $reading if $reading eq $lemma;
234         my $oldreading = $reading;
235         # $lemma =~ s/\s+[[:punct:]]+$//;
236         # $reading =~ s/\s*\(?sic([\s\w.]+)?\)?$//;
237         my @words = split( /\s+/, $lemma );
238         if( $reading =~ /^(.*) praem.$/ ) {
239                 $reading = "$1 $lemma";
240         } elsif( $reading =~ /^(.*) add.$/ ) {
241                 $reading = "$lemma $1";
242         } elsif( $reading eq 'om.' 
243             || $reading =~ /locus [uv]acuus/
244             || $reading =~ /inscriptionem compegi e/ # TODO huh?
245             || $reading eq 'def.' # TODO huh?
246             ) {
247                 $reading = '';
248         } elsif( $reading eq 'inv.' ) {
249                 # Hope it is two words.
250                 print STDERR "WARNING: want to invert a lemma that is not two words\n" 
251                         unless scalar( @words ) == 2;
252                 $reading = join( ' ', reverse( @words ) );
253         } elsif( $reading eq 'iter.' ) {
254                 # Repeat the lemma
255                 $reading = "$lemma $lemma";
256          } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
257                 # The first and last N words captured should replace the first and
258                 # last N words of the lemma.
259                 my @begin = split( /\s+/, $1 );
260                 my @end = split( /\s+/, $2 );
261                 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
262                         # Something is wrong and we can't do the splice.
263                         print STDERR "ERROR: $lemma is too short to accommodate $oldreading\n";
264                 } else {
265                         splice( @words, 0, scalar @begin, @begin );
266                         splice( @words, -(scalar @end), scalar @end, @end );
267                         $reading = join( ' ', @words );
268                 }
269         }
270         print STDERR "Interpreted $oldreading as $reading given $lemma\n";
271         return $reading;
272 }
273
274 sub _parse_wit_detail {
275     my( $detail, $readings, $lemma ) = @_;
276     my $wit = $detail->getAttribute( 'wit' );
277     my $content = $detail->textContent;
278     if( $content =~ /a\.\s*c\./ ) {
279         # Replace the key in the $readings hash
280         my $rdg = delete $readings->{$wit};
281         $readings->{$wit.'_ac'} = $rdg;
282         $has_ac{$sigil_for{$wit}} = 1;
283     } elsif( $content =~ /p\.\s*c\./ ) {
284         # If no key for the wit a.c. exists, add one pointing to the lemma
285         unless( exists $readings->{$wit.'_ac'} ) {
286             $readings->{$wit.'_ac'} = $lemma;
287         }
288         $has_ac{$sigil_for{$wit}} = 1;
289     } # else don't bother just yet
290 }
291
292 sub get_sigil {
293     my( $xml_id, $c ) = @_;
294     if( $xml_id =~ /^(.*)_ac$/ ) {
295         my $real_id = $1;
296         return $sigil_for{$real_id} . $c->ac_label;
297     } else {
298         return $sigil_for{$xml_id};
299     }
300 }
301
302 sub expand_all_paths { 
303     my( $c ) = @_;
304     
305     # Walk the collation and fish out the paths for each witness
306     foreach my $wit ( $c->tradition->witnesses ) {
307         my $sig = $wit->sigil;
308         my @path = grep { $_->name !~ /(APP|ANCHOR)/ } 
309             $c->reading_sequence( $c->start, $c->end, $sig );
310         $wit->path( \@path );
311         if( $has_ac{$sig} ) {
312             my @ac_path = grep { $_->name !~ /(APP|ANCHOR)/ } 
313                 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label, $sig );
314             $wit->uncorrected_path( \@ac_path );
315         }
316     }   
317     
318     # Delete the anchors
319     foreach my $anchor ( grep { $_->name =~ /(APP|ANCHOR)/ } $c->readings ) {
320         $c->del_reading( $anchor );
321     }
322     # Delete all edges
323     map { $c->del_path( $_ ) } $c->paths;
324     
325     # Make the path edges
326     $c->make_witness_paths();
327 }
328
329 sub _add_wit_path {
330     my( $c, $rdg, $app, $anchor, $wit ) = @_;
331     my @nodes = @$rdg;
332     push( @nodes, $c->reading( $anchor ) );
333     
334     my $cur = $c->reading( $app );
335     foreach my $n ( @nodes ) {
336         $c->add_path( $cur, $n, $wit );
337         $cur = $n;
338     }
339 }
340
341 =back
342
343 =head1 LICENSE
344
345 This package is free software and is provided "as is" without express
346 or implied warranty.  You can redistribute it and/or modify it under
347 the same terms as Perl itself.
348
349 =head1 AUTHOR
350
351 Tara L Andrews, aurum@cpan.org
352
353 =cut
354
355 1;
356