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
42 $opts->{interpret_transposition} = 1;
44 # First, parse the XML.
45 my( $tei, $xpc ) = _remove_formatting( $opts );
46 return unless $tei; # we have already warned.
48 # CTE uses a DTD rather than any xmlns-based parsing. Thus we
49 # need no namespace handling.
50 # Get the witnesses and create the witness objects.
51 foreach my $wit_el ( $xpc->findnodes( '//sourceDesc/listWit/witness' ) ) {
52 # The witness xml:id is used internally, and is *not* the sigil name.
53 my $id= $wit_el->getAttribute( 'xml:id' );
54 # If the witness element has an abbr element, that is the sigil. Otherwise
55 # the whole thing is the sigil.
56 my $sig = $xpc->findvalue( 'abbr', $wit_el );
57 my $identifier = 'CTE witness';
59 # The sigil is what is in the <abbr/> tag; the identifier is anything
61 $identifier = _tidy_identifier(
62 $xpc->findvalue( 'child::text()', $wit_el ) );
64 my @sig_parts = $xpc->findnodes( 'descendant::text()', $wit_el );
65 $sig = _stringify_sigil( @sig_parts );
67 say STDERR "Adding witness $sig ($identifier)";
68 $tradition->add_witness( sigil => $sig, identifier => $identifier,
69 sourcetype => 'collation' );
70 $sigil_for{'#'.$id} = $sig; # Make life easy by keying on the ID ref syntax
73 # Now go through the text and find the base tokens, apparatus tags, and
74 # anchors. Make a giant array of all of these things in sequence.
75 # TODO consider combining this with creation of graph below
77 foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
78 foreach my $xn ( $pg_el->childNodes ) {
79 push( @base_text, _get_base( $xn ) );
82 # We now have to work through this array applying the alternate
83 # apparatus readings to the base text. Essentially we will put
84 # everything on the graph, from which we will delete the apps and
85 # anchors when we are done.
87 # First, put the base tokens, apps, and anchors in the graph. Save the
88 # app siglorum separately as it has to be processed in order.
92 foreach my $item ( @base_text ) {
94 if( $item->{'type'} eq 'token' ) {
95 $r = $c->add_reading( { id => 'n'.$counter++,
96 text => $item->{'content'} } );
97 } elsif ( $item->{'type'} eq 'anchor' ) {
98 $r = $c->add_reading( { id => '__ANCHOR_' . $item->{'content'} . '__',
100 } elsif ( $item->{'type'} eq 'app' ) {
101 my $tag = '__APP_' . $counter++ . '__';
102 $r = $c->add_reading( { id => $tag, is_ph => 1 } );
103 # Apparatus criticus is type a1; app siglorum is type a2
104 if( $item->{'content'}->getAttribute('type') eq 'a1' ) {
105 $apps{$tag} = $item->{'content'};
107 push( @app_sig, $item->{'content'} );
110 $c->add_path( $last, $r, $c->baselabel );
113 $c->add_path( $last, $c->end, $c->baselabel );
115 # Now we can parse the apparatus entries, and add the variant readings
117 foreach my $app_id ( keys %apps ) {
118 _add_readings( $c, $app_id, $opts );
120 _add_lacunae( $c, @app_sig );
122 # Finally, add explicit witness paths, remove the base paths, and remove
123 # the app/anchor tags.
124 _expand_all_paths( $c );
126 # Save the text for each witness so that we can ensure consistency
128 unless( $opts->{'nocalc'} ) {
129 $tradition->collation->text_from_paths();
130 $tradition->collation->calculate_ranks();
131 $tradition->collation->flatten_ranks();
135 sub _stringify_sigil {
137 my @parts = grep { /\w/ } map { $_->data } @nodes;
138 my $whole = join( '', @parts );
143 sub _tidy_identifier {
149 # Get rid of all the formatting elements that get in the way of tokenization.
150 sub _remove_formatting {
153 # First, parse the original XML
154 my $parser = XML::LibXML->new();
156 if( exists $opts->{'string'} ) {
157 $doc = $parser->parse_string( $opts->{'string'} );
158 } elsif ( exists $opts->{'file'} ) {
159 $doc = $parser->parse_file( $opts->{'file'} );
161 warn "Could not find string or file option to parse";
165 # Second, remove the formatting
166 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
167 my @useless = $xpc->findnodes( '//hi' );
168 foreach my $n ( @useless ) {
169 my $parent = $n->parentNode();
170 my @children = $n->childNodes();
171 my $first = shift @children;
173 $parent->replaceChild( $first, $n );
174 foreach my $c ( @children ) {
175 $parent->insertAfter( $c, $first );
179 $parent->removeChild( $n );
183 # Third, write out and reparse to merge the text nodes.
184 my $enc = $doc->encoding || 'UTF-8';
185 my $result = decode( $enc, $doc->toString() );
186 my $tei = $parser->parse_string( $result )->documentElement;
187 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
188 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
190 $xpc = XML::LibXML::XPathContext->new( $tei );
191 return( $tei, $xpc );
194 ## Helper function to help us navigate through nested XML, picking out
195 ## the words, the apparatus, and the anchors.
200 if( $xn->nodeType == XML_TEXT_NODE ) {
201 # Base text, just split the words on whitespace and add them
205 my @tokens = split( /\s+/, $str );
206 push( @readings, map { { type => 'token', content => $_ } } @tokens );
207 } elsif( $xn->nodeName eq 'app' ) {
208 # Apparatus, just save the entire XML node.
209 push( @readings, { type => 'app', content => $xn } );
210 } elsif( $xn->nodeName eq 'anchor' ) {
211 # Anchor to mark the end of some apparatus; save its ID.
212 if( $xn->hasAttribute('xml:id') ) {
213 push( @readings, { type => 'anchor',
214 content => $xn->getAttribute( 'xml:id' ) } );
215 } # if the anchor has no XML ID, it is not relevant to us.
216 } elsif( $xn->nodeName !~ /^(note|seg|milestone|emph)$/ ) { # Any tag we don't know to disregard
217 say STDERR "Unrecognized tag " . $xn->nodeName;
223 my( $list, @tokens ) = @_;
224 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
225 # The list evidently ended mid-word; join the next token onto it.
226 my $t = shift @tokens;
227 if( ref $t && $t->{'type'} eq 'token' ) {
229 $t = $t->{'content'};
231 # An app or anchor intervened; end the word.
232 unshift( @tokens, $t );
235 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
237 foreach my $t ( @tokens ) {
238 unless( ref( $t ) ) {
239 $t = { 'type' => 'token', 'content' => $t };
246 my( $c, $app_id, $opts ) = @_;
247 my $xn = $apps{$app_id};
248 my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
250 # Get the lemma, which is all the readings between app and anchor,
251 # excluding other apps or anchors.
252 my @lemma = _return_lemma( $c, $app_id, $anchor );
253 my $lemma_str = join( ' ', map { $_->text } grep { !$_->is_ph } @lemma );
255 # For each reading, send its text to 'interpret' along with the lemma,
256 # and then save the list of witnesses that these tokens belong to.
257 my %wit_rdgs; # Maps from witnesses to the variant text
260 $tag =~ s/^\__APP_(.*)\__$/$1/;
262 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
263 my @witlist = split( /\s+/, $rdg->getAttribute( 'wit' ) );
265 foreach ( $rdg->childNodes ) {
266 push( @text, _get_base( $_ ) );
268 my( $interpreted, $flag ) = ( '', undef );
270 ( $interpreted, $flag ) = interpret(
271 join( ' ', map { $_->{'content'} } @text ), $lemma_str, $anchor, $opts );
273 next if( $interpreted eq $lemma_str ) && !keys %$flag; # Reading is lemma.
276 if( $interpreted eq '#LACUNA#' ) {
277 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
278 is_lacuna => 1 } ) );
279 } elsif( $flag->{'TR'} ) {
280 # Our reading is transposed to after the given string. Look
281 # down the collation base text and try to find it.
282 # The @rdg_nodes should remain blank here, so that the correct
283 # omission goes into the graph.
285 foreach my $w ( split( /\s+/, $interpreted ) ) {
286 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
288 push( @transp_nodes, $r );
290 if( $anchor && @lemma ) {
291 my $success = _attach_transposition( $c, \@lemma, $anchor,
292 \@transp_nodes, \@witlist, $flag->{'TR'} );
294 # If we didn't manage to insert the displaced reading,
295 # then restore it here rather than silently deleting it.
296 push( @rdg_nodes, @transp_nodes );
300 foreach my $w ( split( /\s+/, $interpreted ) ) {
301 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
303 push( @rdg_nodes, $r );
307 # For each listed wit, save the reading.
308 # If an A.C. or P.C. reading is implied rather than explicitly noted,
309 # this is where it will be dealt with.
310 foreach my $wit ( @witlist ) {
311 $wit .= '_ac' if $flag->{'AC'};
312 $wit_rdgs{$wit} = \@rdg_nodes;
313 # If the PC flag is set, there is a corresponding AC that
314 # follows the lemma and has to be explicitly declared.
315 if( $flag->{'PC'} ) {
316 $wit_rdgs{$wit.'_ac'} = \@lemma;
320 # Does the reading have an ID? If so it probably has a witDetail
321 # attached, and we need to read it. If an A.C. or P.C. reading is
322 # declared explicity, this is where it will be dealt with.
323 if( $rdg->hasAttribute( 'xml:id' ) ) {
324 warn "Witdetail on meta reading" if $flag; # this could get complicated.
325 my $rid = $rdg->getAttribute( 'xml:id' );
326 my $xpc = XML::LibXML::XPathContext->new( $xn );
327 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
328 foreach my $d ( @details ) {
329 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
334 # Now collate the variant readings, since it is not done for us.
335 collate_variants( $c, \@lemma, values %wit_rdgs );
337 # Now add the witness paths for each reading. If we don't have an anchor
338 # (e.g. with an initial witStart) there was no witness path to speak of.
339 foreach my $wit_id ( keys %wit_rdgs ) {
340 my $witstr = _get_sigil( $wit_id, $c->ac_label );
341 my $rdg_list = $wit_rdgs{$wit_id};
342 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
349 return sprintf( "__ANCHOR_%s__", $xmlid );
353 my( $c, $app, $anchor ) = @_;
354 my @nodes = grep { $_->id !~ /^__A(PP|NCHOR)/ }
355 $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
360 # Make a best-effort attempt to attach a transposition farther down the line.
361 # $lemmaseq contains the Reading objects of the lemma
362 # $anchor contains the point at which we should start scanning for a match
363 # $rdgseq contains the Reading objects of the transposed reading
364 # (should be identical to the lemma)
365 # $witlist contains the list of applicable witnesses
366 # $reftxt contains the text to match, after which the $rdgseq should go.
367 sub _attach_transposition {
368 my( $c, $lemmaseq, $anchor, $rdgseq, $witlist, $reftxt ) = @_;
369 my @refwords = split( /\s+/, $reftxt );
370 my $checked = $c->reading( $anchor );
373 while( $checked ne $c->end && !$found ) {
374 my $next = $c->next_reading( $checked, $c->baselabel );
375 if( $next->text eq $refwords[0] ) {
376 # See if the entire sequence of words matches.
378 foreach my $w ( 1..$#refwords ) {
379 $found = $c->next_reading( $next, $c->baselabel );
380 unless( $found->text eq $refwords[$w] ) {
389 # The $found variable should now contain the reading after which we
390 # should stick the transposition.
391 my $fnext = $c->next_reading( $found, $c->baselabel );
392 my $aclabel = $c->ac_label;
393 foreach my $wit_id ( @$witlist ) {
394 my $witstr = _get_sigil( $wit_id, $aclabel );
395 _add_wit_path( $c, $rdgseq, $found->id, $fnext->id, $witstr );
397 # ...and add the transposition relationship between lemma and rdgseq.
398 if( @$lemmaseq == @$rdgseq ) {
399 foreach my $i ( 0..$#{$lemmaseq} ) {
400 $c->add_relationship( $lemmaseq->[$i], $rdgseq->[$i],
401 { type => 'transposition', annotation => 'Detected by CTE' } );
405 say STDERR "ERROR: lemma and transposed sequence different lengths?!"
408 say STDERR "WARNING: Unable to find $reftxt in base text for transposition";
413 =head2 interpret( $reading, $lemma )
415 Given a string in $reading and a corresponding lemma in $lemma, interpret what
416 the actual reading should be. Used to deal with apparatus-ese shorthands for
417 marking transpositions, prefixed or suffixed words, and the like.
422 # A utility function to change apparatus-ese into a full variant.
423 my( $reading, $lemma, $anchor, $opts ) = @_;
424 return $reading if $reading eq $lemma;
425 my $oldreading = $reading;
426 # $lemma =~ s/\s+[[:punct:]]+$//;
427 my $flag = {}; # To pass back extra info about the interpretation
428 my @words = split( /\s+/, $lemma );
429 # Discard any 'sic' notation - that rather goes without saying.
430 $reading =~ s/([[:punct:]]+)?sic([[:punct:]]+)?//g;
432 # Now look for common jargon.
433 if( $reading =~ /^(.*) praem.$/ || $reading =~ /^praem\. (.*)$/ ) {
434 $reading = "$1 $lemma";
435 } elsif( $reading =~ /^(.*) add.$/ || $reading =~ /^add\. (.*)$/ ) {
436 $reading = "$lemma $1";
437 } elsif( $reading =~ /locus [uv]acuus/
438 || $reading eq 'def.'
439 || $reading eq 'illeg.'
440 || $reading eq 'desunt'
442 $reading = '#LACUNA#';
443 } elsif( $reading eq 'om.' ) {
445 } elsif( $reading =~ /^in[uv]\.$/
446 || $reading =~ /^tr(ans(p)?)?\.$/ ) {
447 # Hope it is two words.
448 say STDERR "WARNING: want to invert a lemma that is not two words"
449 unless scalar( @words ) == 2;
450 $reading = join( ' ', reverse( @words ) );
451 } elsif( $reading =~ /^iter(\.|at)$/ ) {
453 $reading = "$lemma $lemma";
454 } elsif( $reading =~ /^(.*?)\s*\(?in marg\.\)?$/ ) {
457 # The given text is a correction.
460 # The lemma itself was the correction; the witness carried
461 # no reading pre-correction.
464 } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
465 # The first and last N words captured should replace the first and
466 # last N words of the lemma.
467 my @begin = split( /\s+/, $1 );
468 my @end = split( /\s+/, $2 );
469 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
470 # Something is wrong and we can't do the splice.
471 say STDERR "ERROR: $lemma is too short to accommodate $oldreading";
473 splice( @words, 0, scalar @begin, @begin );
474 splice( @words, -(scalar @end), scalar @end, @end );
475 $reading = join( ' ', @words );
477 } elsif( $opts->{interpret_transposition} &&
478 ( $reading =~ /^post\s*(?<lem>.*?)\s+tr(ans(p)?)?\.$/ ||
479 $reading =~ /^tr(ans(p)?)?\. post\s*(?<lem>.*)$/) ) {
480 # Try to deal with transposed readings
482 say STDERR "Will attempt transposition: $reading at $anchor";
484 $flag->{'TR'} = $+{lem};
486 return( $reading, $flag );
489 sub _parse_wit_detail {
490 my( $detail, $readings, $lemma ) = @_;
491 my $wit = $detail->getAttribute( 'wit' );
492 my $content = $detail->textContent;
493 if( $content =~ /^a\.?\s*c(orr)?\.$/ ) {
494 # Replace the key in the $readings hash
495 my $rdg = delete $readings->{$wit};
496 $readings->{$wit.'_ac'} = $rdg;
497 $has_ac{$sigil_for{$wit}} = 1;
498 } elsif( $content =~ /^p\.?\s*c(orr)?\.$/ || $content =~ /^s\.?\s*l\.$/ ) {
499 # If no key for the wit a.c. exists, add one pointing to the lemma
500 unless( exists $readings->{$wit.'_ac'} ) {
501 $readings->{$wit.'_ac'} = $lemma;
503 $has_ac{$sigil_for{$wit}} = 1;
504 } else { #...not sure what it is?
505 say STDERR "WARNING: Unrecognized sigil addendum $content";
510 my( $c, @apps ) = @_;
511 # Go through the apparatus entries in order, noting where to start and stop our
515 foreach my $app ( @apps ) {
516 # Find the anchor, if any. This marks the point where the text starts
518 my $anchor = $app->getAttribute( 'to' );
521 $aname = _anchor_name( $anchor );
524 foreach my $rdg ( $app->getChildrenByTagName( 'rdg' ) ) {
525 my @witlist = map { _get_sigil( $_, $c->ac_label ) }
526 split( /\s+/, $rdg->getAttribute( 'wit' ) );
527 my @start = $rdg->getChildrenByTagName( 'witStart' );
528 my @end = $rdg->getChildrenByTagName( 'witEnd' );
529 if( @start && @end ) {
530 throw( "App sig entry at $anchor has both witStart and witEnd!" );
532 if( @start && $anchor &&
533 $c->prior_reading( $aname, $c->baselabel ) ne $c->start ) {
534 # We are picking back up after a hiatus. Find the last end and
535 # add a lacuna link between there and here.
536 foreach my $wit ( @witlist ) {
537 my $stoppoint = delete $lacunose{$wit};
538 $stoppoint = $c->start unless $stoppoint;
539 my $stopname = _anchor_name( $stoppoint );
540 say STDERR "Adding lacuna for $wit between $stoppoint and $anchor";
541 my $lacuna = $c->add_reading( { id => "as_$anchor.".$ctr++,
543 _add_wit_path( $c, [ $lacuna ], $stopname, $aname, $wit );
545 } elsif( @end && $anchor &&
546 $c->next_reading( $aname, $c->baselabel ) ne $c->end ) {
547 # We are stopping. If we've already stopped for the given witness,
548 # flag an error; otherwise record the stopping point.
549 foreach my $wit ( @witlist ) {
550 if( $lacunose{$wit} ) {
551 throw( "Trying to end $wit at $anchor when already ended at "
554 $lacunose{$wit} = $anchor;
560 # For whatever remains in the %lacunose hash, add a lacuna between that spot and
561 # $c->end for each of the witnesses.
562 foreach my $wit ( keys %lacunose ) {
563 next unless $lacunose{$wit};
564 my $aname = _anchor_name( $lacunose{$wit} );
565 say STDERR "Adding lacuna for $wit from $aname to end";
566 my $lacuna = $c->add_reading( { id => 'as_'.$lacunose{$wit}.'.'.$ctr++,
568 _add_wit_path( $c, [ $lacuna ], $aname, $c->end, $wit );
573 my( $xml_id, $layerlabel ) = @_;
574 if( $xml_id =~ /^(.*)_ac$/ ) {
576 return $sigil_for{$real_id} . $layerlabel;
578 return $sigil_for{$xml_id};
582 sub _expand_all_paths {
585 # Walk the collation and fish out the paths for each witness
586 foreach my $wit ( $c->tradition->witnesses ) {
587 my $sig = $wit->sigil;
588 my @path = grep { !$_->is_ph }
589 $c->reading_sequence( $c->start, $c->end, $sig );
590 $wit->path( \@path );
591 if( $has_ac{$sig} ) {
592 my @ac_path = grep { !$_->is_ph }
593 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
594 $wit->uncorrected_path( \@ac_path );
599 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
600 $c->del_reading( $anchor );
602 # Delete the base edges
603 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
605 # Make the path edges
606 $c->make_witness_paths();
608 # Now remove any orphan nodes, and warn that we are doing so.
609 while( $c->sequence->predecessorless_vertices > 1 ) {
610 foreach my $v ( $c->sequence->predecessorless_vertices ) {
611 my $r = $c->reading( $v );
612 next if $r->is_start;
613 say STDERR "Deleting orphan reading $r / " . $r->text;
614 $c->del_reading( $r );
620 my( $c, $rdg, $app, $anchor, $wit ) = @_;
622 push( @nodes, $c->reading( $anchor ) );
624 my $cur = $c->reading( $app );
625 foreach my $n ( @nodes ) {
626 $c->add_path( $cur, $n, $wit );
632 Text::Tradition::Error->throw(
633 'ident' => 'Parser::CTE error',
640 This package is free software and is provided "as is" without express
641 or implied warranty. You can redistribute it and/or modify it under
642 the same terms as Perl itself.
646 Tara L Andrews, aurum@cpan.org