1 package Text::Tradition::Parser::CTE;
6 use Encode qw/ decode /;
7 use Text::Tradition::Error;
8 use Text::Tradition::Parser::Util qw/ collate_variants /;
10 use XML::LibXML::XPathContext;
14 Text::Tradition::Parser::CTE
18 Parser module for Text::Tradition, given a TEI file exported from
19 Classical Text Editor.
25 my @apparatus = read( $xml_file );
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.
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.
38 my( $tradition, $opts ) = @_;
39 my $c = $tradition->collation; # Some shorthand
41 # First, parse the XML.
42 my( $tei, $xpc ) = _remove_formatting( $opts );
43 return unless $tei; # we have already warned.
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 # If the witness element has an abbr element, that is the sigil. Otherwise
52 # the whole thing is the sigil.
53 my $sig = $xpc->findvalue( 'abbr', $wit_el );
54 my $identifier = 'CTE witness';
56 # The sigil is what is in the <abbr/> tag; the identifier is anything
58 $identifier = _tidy_identifier(
59 $xpc->findvalue( 'child::text()', $wit_el ) );
61 my @sig_parts = $xpc->findnodes( 'descendant::text()', $wit_el );
62 $sig = _stringify_sigil( @sig_parts );
64 say STDERR "Adding witness $sig ($identifier)";
65 $tradition->add_witness( sigil => $sig, identifier => $identifier,
66 sourcetype => 'collation' );
67 $sigil_for{'#'.$id} = $sig; # Make life easy by keying on the ID ref syntax
70 # Now go through the text and find the base tokens, apparatus tags, and
71 # anchors. Make a giant array of all of these things in sequence.
72 # TODO consider combining this with creation of graph below
74 foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
75 foreach my $xn ( $pg_el->childNodes ) {
76 push( @base_text, _get_base( $xn ) );
79 # We now have to work through this array applying the alternate
80 # apparatus readings to the base text. Essentially we will put
81 # everything on the graph, from which we will delete the apps and
82 # anchors when we are done.
84 # First, put the base tokens, apps, and anchors in the graph.
87 foreach my $item ( @base_text ) {
89 if( $item->{'type'} eq 'token' ) {
90 $r = $c->add_reading( { id => 'n'.$counter++,
91 text => $item->{'content'} } );
92 } elsif ( $item->{'type'} eq 'anchor' ) {
93 $r = $c->add_reading( { id => '__ANCHOR_' . $item->{'content'} . '__',
95 } elsif ( $item->{'type'} eq 'app' ) {
96 my $tag = '__APP_' . $counter++ . '__';
97 $r = $c->add_reading( { id => $tag, is_ph => 1 } );
98 $apps{$tag} = $item->{'content'};
100 $c->add_path( $last, $r, $c->baselabel );
103 $c->add_path( $last, $c->end, $c->baselabel );
105 # Now we can parse the apparatus entries, and add the variant readings
108 foreach my $app_id ( keys %apps ) {
109 _add_readings( $c, $app_id );
112 # Finally, add explicit witness paths, remove the base paths, and remove
113 # the app/anchor tags.
114 _expand_all_paths( $c );
116 # Save the text for each witness so that we can ensure consistency
118 unless( $opts->{'nocalc'} ) {
119 $tradition->collation->text_from_paths();
120 $tradition->collation->calculate_ranks();
121 $tradition->collation->flatten_ranks();
125 sub _stringify_sigil {
127 my @parts = grep { /\w/ } map { $_->data } @nodes;
128 my $whole = join( '', @parts );
133 sub _tidy_identifier {
139 # Get rid of all the formatting elements that get in the way of tokenization.
140 sub _remove_formatting {
143 # First, parse the original XML
144 my $parser = XML::LibXML->new();
146 if( exists $opts->{'string'} ) {
147 $doc = $parser->parse_string( $opts->{'string'} );
148 } elsif ( exists $opts->{'file'} ) {
149 $doc = $parser->parse_file( $opts->{'file'} );
151 warn "Could not find string or file option to parse";
155 # Second, remove the formatting
156 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
157 my @useless = $xpc->findnodes( '//hi' );
158 foreach my $n ( @useless ) {
159 my $parent = $n->parentNode();
160 my @children = $n->childNodes();
161 my $first = shift @children;
163 $parent->replaceChild( $first, $n );
164 foreach my $c ( @children ) {
165 $parent->insertAfter( $c, $first );
169 $parent->removeChild( $n );
173 # Third, write out and reparse to merge the text nodes.
174 my $enc = $doc->encoding || 'UTF-8';
175 my $result = decode( $enc, $doc->toString() );
176 my $tei = $parser->parse_string( $result )->documentElement;
177 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
178 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
180 $xpc = XML::LibXML::XPathContext->new( $tei );
181 return( $tei, $xpc );
184 ## Helper function to help us navigate through nested XML, picking out
185 ## the words, the apparatus, and the anchors.
190 if( $xn->nodeType == XML_TEXT_NODE ) {
191 # Base text, just split the words on whitespace and add them
195 my @tokens = split( /\s+/, $str );
196 push( @readings, map { { type => 'token', content => $_ } } @tokens );
197 } elsif( $xn->nodeName eq 'app' ) {
198 # Apparatus, just save the entire XML node.
199 push( @readings, { type => 'app', content => $xn } );
200 } elsif( $xn->nodeName eq 'anchor' ) {
201 # Anchor to mark the end of some apparatus; save its ID.
202 if( $xn->hasAttribute('xml:id') ) {
203 push( @readings, { type => 'anchor',
204 content => $xn->getAttribute( 'xml:id' ) } );
205 } # if the anchor has no XML ID, it is not relevant to us.
206 } elsif( $xn->nodeName =~ /^wit(Start|End)$/ ){
207 push( @readings, { type => 'token', content => '#' . uc( $1 ) . '#' } );
208 } elsif( $xn->nodeName !~ /^(note|seg|milestone|emph)$/ ) { # Any tag we don't know to disregard
209 say STDERR "Unrecognized tag " . $xn->nodeName;
215 my( $list, @tokens ) = @_;
216 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
217 # The list evidently ended mid-word; join the next token onto it.
218 my $t = shift @tokens;
219 if( ref $t && $t->{'type'} eq 'token' ) {
221 $t = $t->{'content'};
223 # An app or anchor intervened; end the word.
224 unshift( @tokens, $t );
227 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
229 foreach my $t ( @tokens ) {
230 unless( ref( $t ) ) {
231 $t = { 'type' => 'token', 'content' => $t };
238 my( $c, $app_id ) = @_;
239 my $xn = $apps{$app_id};
240 # If the app is of type a1, it is an apparatus criticus.
241 # If it is of type a2, it is an apparatus codicum and might not
244 if( $xn->hasAttribute('to') ) {
245 $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
248 # Get the lemma, which is all the readings between app and anchor,
249 # excluding other apps or anchors.
253 @lemma = _return_lemma( $c, $app_id, $anchor );
254 $lemma_str = join( ' ', map { $_->text } grep { !$_->is_ph } @lemma );
257 # For each reading, send its text to 'interpret' along with the lemma,
258 # and then save the list of witnesses that these tokens belong to.
259 my %wit_rdgs; # Maps from witnesses to the variant text
262 $tag =~ s/^\__APP_(.*)\__$/$1/;
264 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
266 foreach ( $rdg->childNodes ) {
267 push( @text, _get_base( $_ ) );
269 my( $interpreted, $flag ) = ( '', undef );
271 ( $interpreted, $flag ) = interpret(
272 join( ' ', map { $_->{'content'} } @text ), $lemma_str );
274 next if( $interpreted eq $lemma_str ) && !$flag; # Reading is lemma.
277 if( $interpreted eq '#LACUNA#' ) {
278 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
279 is_lacuna => 1 } ) );
281 if ( $flag && $flag eq 'START'
282 && $c->prior_reading( $app_id, $c->baselabel ) ne $c->start ) {
283 # Add a lacuna for the witness start.
284 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
285 is_lacuna => 1 } ) );
288 foreach my $w ( split( /\s+/, $interpreted ) ) {
289 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
291 push( @rdg_nodes, $r );
293 if( $flag && $flag eq 'END'
294 && $c->next_reading( $app_id, $c->baselabel ) ne $c->end ) {
295 # Add a lacuna for the witness end.
296 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
297 is_lacuna => 1 } ) );
302 # For each listed wit, save the reading.
303 foreach my $wit ( split( /\s+/, $rdg->getAttribute( 'wit' ) ) ) {
304 $wit .= $flag if $flag;
305 $wit_rdgs{$wit} = \@rdg_nodes;
308 # Does the reading have an ID? If so it probably has a witDetail
309 # attached, and we need to read it.
310 if( $rdg->hasAttribute( 'xml:id' ) ) {
311 warn "Witdetail on meta reading" if $flag; # this could get complicated.
312 my $rid = $rdg->getAttribute( 'xml:id' );
313 my $xpc = XML::LibXML::XPathContext->new( $xn );
314 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
315 foreach my $d ( @details ) {
316 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
321 # Now collate the variant readings, since it is not done for us.
322 collate_variants( $c, \@lemma, values %wit_rdgs );
324 # Now add the witness paths for each reading. If we don't have an anchor
325 # (e.g. with an initial witStart) there was no witness path to speak of.
327 my $aclabel = $c->ac_label;
328 foreach my $wit_id ( keys %wit_rdgs ) {
329 my $witstr = _get_sigil( $wit_id, $aclabel );
330 my $rdg_list = $wit_rdgs{$wit_id};
331 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
339 return sprintf( "__ANCHOR_%s__", $xmlid );
343 my( $c, $app, $anchor ) = @_;
344 my @nodes = grep { $_->id !~ /^__A(PP|NCHOR)/ }
345 $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
350 =head2 interpret( $reading, $lemma )
352 Given a string in $reading and a corresponding lemma in $lemma, interpret what
353 the actual reading should be. Used to deal with apparatus-ese shorthands for
354 marking transpositions, prefixed or suffixed words, and the like.
359 # A utility function to change apparatus-ese into a full variant.
360 my( $reading, $lemma ) = @_;
361 return $reading if $reading eq $lemma;
362 my $oldreading = $reading;
363 # $lemma =~ s/\s+[[:punct:]]+$//;
364 my $flag; # In case of p.c. indications
365 my @words = split( /\s+/, $lemma );
366 $reading =~ s/[[:punct:]]?\bsic\b([[:punct:]]+)?//g;
367 if( $reading =~ /^(.*) praem.$/ ) {
368 $reading = "$1 $lemma";
369 } elsif( $reading =~ /^(.*) add.$/ ) {
370 $reading = "$lemma $1";
371 } elsif( $reading =~ /add. alia manu/
372 || $reading =~ /inscriptionem compegi e/ # TODO huh?
373 || $reading eq 'inc.' # TODO huh?
377 } elsif( $reading =~ /locus [uv]acuus/
378 || $reading eq 'def.'
379 || $reading eq 'illeg.'
380 || $reading eq 'onleesbar'
382 $reading = '#LACUNA#';
383 } elsif( $reading eq 'om.' ) {
385 } elsif( $reading =~ /^in[uv]\.$/
386 || $reading eq 'transp.' ) {
387 # Hope it is two words.
388 say STDERR "WARNING: want to invert a lemma that is not two words"
389 unless scalar( @words ) == 2;
390 $reading = join( ' ', reverse( @words ) );
391 } elsif( $reading =~ /^iter(\.|at)$/ ) {
393 $reading = "$lemma $lemma";
394 } elsif( $reading eq 'in marg.' ) {
395 # There was nothing before a correction.
398 } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
399 # The first and last N words captured should replace the first and
400 # last N words of the lemma.
401 my @begin = split( /\s+/, $1 );
402 my @end = split( /\s+/, $2 );
403 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
404 # Something is wrong and we can't do the splice.
405 say STDERR "ERROR: $lemma is too short to accommodate $oldreading";
407 splice( @words, 0, scalar @begin, @begin );
408 splice( @words, -(scalar @end), scalar @end, @end );
409 $reading = join( ' ', @words );
411 } elsif( $reading =~ /^\#START\#\s*(.*)$/ ) {
414 } elsif( $reading =~ /^(.*?)\s*\#END\#$/ ) {
418 if( $oldreading ne $reading || $flag || $oldreading =~ /\./ ) {
420 $int .= " ($flag)" if $flag;
421 # say STDERR "Interpreted $oldreading as $int given $lemma";
423 return( $reading, $flag );
426 sub _parse_wit_detail {
427 my( $detail, $readings, $lemma ) = @_;
428 my $wit = $detail->getAttribute( 'wit' );
429 my $content = $detail->textContent;
430 if( $content =~ /a\.\s*c\b/ ) {
431 # Replace the key in the $readings hash
432 my $rdg = delete $readings->{$wit};
433 $readings->{$wit.'_ac'} = $rdg;
434 $has_ac{$sigil_for{$wit}} = 1;
435 } elsif( $content =~ /p\.\s*c\b/ ) {
436 # If no key for the wit a.c. exists, add one pointing to the lemma
437 unless( exists $readings->{$wit.'_ac'} ) {
438 $readings->{$wit.'_ac'} = $lemma;
440 $has_ac{$sigil_for{$wit}} = 1;
441 } # else don't bother just yet
445 my( $xml_id, $layerlabel ) = @_;
446 if( $xml_id =~ /^(.*)_ac$/ ) {
448 return $sigil_for{$real_id} . $layerlabel;
450 return $sigil_for{$xml_id};
454 sub _expand_all_paths {
457 # Walk the collation and fish out the paths for each witness
458 foreach my $wit ( $c->tradition->witnesses ) {
459 my $sig = $wit->sigil;
460 my @path = grep { !$_->is_ph }
461 $c->reading_sequence( $c->start, $c->end, $sig );
462 $wit->path( \@path );
463 if( $has_ac{$sig} ) {
464 my @ac_path = grep { !$_->is_ph }
465 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
466 $wit->uncorrected_path( \@ac_path );
471 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
472 $c->del_reading( $anchor );
474 # Delete the base edges
475 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
477 # Make the path edges
478 $c->make_witness_paths();
480 # Now remove any orphan nodes, and warn that we are doing so.
481 while( $c->sequence->predecessorless_vertices > 1 ) {
482 foreach my $v ( $c->sequence->predecessorless_vertices ) {
483 my $r = $c->reading( $v );
484 next if $r->is_start;
485 say STDERR "Deleting orphan reading $r / " . $r->text;
486 $c->del_reading( $r );
492 my( $c, $rdg, $app, $anchor, $wit ) = @_;
494 push( @nodes, $c->reading( $anchor ) );
496 my $cur = $c->reading( $app );
497 foreach my $n ( @nodes ) {
498 $c->add_path( $cur, $n, $wit );
504 Text::Tradition::Error->throw(
505 'ident' => 'Parser::CTE error',
512 This package is free software and is provided "as is" without express
513 or implied warranty. You can redistribute it and/or modify it under
514 the same terms as Perl itself.
518 Tara L Andrews, aurum@cpan.org