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