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