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;
15 Text::Tradition::Parser::CTE
19 Parser module for Text::Tradition, given a TEI file exported from
20 Classical Text Editor.
26 my @apparatus = read( $xml_file );
28 Takes a Tradition object and a TEI file exported from Classical Text
29 Editor using double-endpoint-attachment critical apparatus encoding;
30 initializes the Tradition from the file.
34 my %sigil_for; # Save the XML IDs for witnesses.
35 my %apps; # Save the apparatus XML for a given ID.
36 my %has_ac; # Keep track of witnesses that have corrections.
39 my( $tradition, $opts ) = @_;
40 my $c = $tradition->collation; # Some shorthand
43 $opts->{interpret_transposition} = 1;
45 # First, parse the XML.
46 my( $tei, $xpc ) = _remove_formatting( $opts );
47 return unless $tei; # we have already warned.
49 # CTE uses a DTD rather than any xmlns-based parsing. Thus we
50 # need no namespace handling.
51 # Get the witnesses and create the witness objects.
52 foreach my $wit_el ( $xpc->findnodes( '//sourceDesc/listWit/witness' ) ) {
53 # The witness xml:id is used internally, and is *not* the sigil name.
54 my $id= $wit_el->getAttribute( 'xml:id' );
55 # If the witness element has an abbr element, that is the sigil. Otherwise
56 # the whole thing is the sigil.
57 my $sig = $xpc->findvalue( 'abbr', $wit_el );
58 my $identifier = 'CTE witness';
60 # The sigil is what is in the <abbr/> tag; the identifier is anything
62 $identifier = _tidy_identifier(
63 $xpc->findvalue( 'child::text()', $wit_el ) );
65 my @sig_parts = $xpc->findnodes( 'descendant::text()', $wit_el );
66 $sig = _stringify_sigil( @sig_parts );
68 say STDERR "Adding witness $sig ($identifier)";
69 $tradition->add_witness( sigil => $sig, identifier => $identifier,
70 sourcetype => 'collation' );
71 $sigil_for{'#'.$id} = $sig; # Make life easy by keying on the ID ref syntax
74 # Now go through the text and find the base tokens, apparatus tags, and
75 # anchors. Make a giant array of all of these things in sequence.
76 # TODO consider combining this with creation of graph below
78 foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
79 foreach my $xn ( $pg_el->childNodes ) {
80 push( @base_text, _get_base( $xn ) );
83 # We now have to work through this array applying the alternate
84 # apparatus readings to the base text. Essentially we will put
85 # everything on the graph, from which we will delete the apps and
86 # anchors when we are done.
88 # First, put the base tokens, apps, and anchors in the graph. Save the
89 # app siglorum separately as it has to be processed in order.
93 foreach my $item ( @base_text ) {
95 if( $item->{'type'} eq 'token' ) {
96 $r = $c->add_reading( { id => 'n'.$counter++,
97 text => $item->{'content'} } );
98 } elsif ( $item->{'type'} eq 'anchor' ) {
99 $r = $c->add_reading( { id => '__ANCHOR_' . $item->{'content'} . '__',
101 } elsif ( $item->{'type'} eq 'app' ) {
102 my $tag = '__APP_' . $counter++ . '__';
103 $r = $c->add_reading( { id => $tag, is_ph => 1 } );
104 my $app = $item->{'content'};
105 # Apparatus should be differentiable by type attribute; apparently
106 # it is not. Peek at the content to categorize it.
107 # Apparatus criticus is type a1; app siglorum is type a2
108 my @sigtags = $xpc->findnodes( 'descendant::*[name(witStart) or name(witEnd)]', $app );
110 push( @app_sig, $app );
115 $c->add_path( $last, $r, $c->baselabel );
118 $c->add_path( $last, $c->end, $c->baselabel );
120 # Now we can parse the apparatus entries, and add the variant readings
122 foreach my $app_id ( keys %apps ) {
123 _add_readings( $c, $app_id, $opts );
125 _add_lacunae( $c, @app_sig );
127 # Finally, add explicit witness paths, remove the base paths, and remove
128 # the app/anchor tags.
130 _expand_all_paths( $c );
131 } catch( Text::Tradition::Error $e ) {
132 throw( $e->message );
137 # Save the text for each witness so that we can ensure consistency
139 unless( $opts->{'nocalc'} ) {
141 $tradition->collation->text_from_paths();
142 $tradition->collation->calculate_ranks();
143 $tradition->collation->flatten_ranks();
144 } catch( Text::Tradition::Error $e ) {
145 throw( $e->message );
152 sub _stringify_sigil {
154 my @parts = grep { /\w/ } map { $_->data } @nodes;
155 my $whole = join( '', @parts );
160 sub _tidy_identifier {
166 # Get rid of all the formatting elements that get in the way of tokenization.
167 sub _remove_formatting {
170 # First, parse the original XML
171 my $parser = XML::LibXML->new();
173 if( exists $opts->{'string'} ) {
174 $doc = $parser->parse_string( $opts->{'string'} );
175 } elsif ( exists $opts->{'file'} ) {
176 $doc = $parser->parse_file( $opts->{'file'} );
177 } elsif ( exists $opts->{'xmlobj'} ) {
178 $doc = $opts->{'xmlobj'};
180 warn "Could not find string or file option to parse";
184 # Second, remove the formatting
185 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
186 my @useless = $xpc->findnodes( '//hi' );
187 foreach my $n ( @useless ) {
188 my $parent = $n->parentNode();
189 my @children = $n->childNodes();
190 my $first = shift @children;
192 $parent->replaceChild( $first, $n );
193 foreach my $c ( @children ) {
194 $parent->insertAfter( $c, $first );
198 $parent->removeChild( $n );
202 # Third, write out and reparse to merge the text nodes.
203 my $enc = $doc->encoding || 'UTF-8';
204 my $result = decode( $enc, $doc->toString() );
205 my $tei = $parser->parse_string( $result )->documentElement;
206 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
207 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
209 $xpc = XML::LibXML::XPathContext->new( $tei );
210 return( $tei, $xpc );
213 ## Helper function to help us navigate through nested XML, picking out
214 ## the words, the apparatus, and the anchors.
219 if( $xn->nodeType == XML_TEXT_NODE ) {
220 # Base text, just split the words on whitespace and add them
224 my @tokens = split( /\s+/, $str );
225 push( @readings, map { { type => 'token', content => $_ } } @tokens );
226 } elsif( $xn->nodeName eq 'app' ) {
227 # Apparatus, just save the entire XML node.
228 push( @readings, { type => 'app', content => $xn } );
229 } elsif( $xn->nodeName eq 'anchor' ) {
230 # Anchor to mark the end of some apparatus; save its ID.
231 if( $xn->hasAttribute('xml:id') ) {
232 push( @readings, { type => 'anchor',
233 content => $xn->getAttribute( 'xml:id' ) } );
234 } # if the anchor has no XML ID, it is not relevant to us.
235 } elsif( $xn->nodeName !~ /^(note|seg|milestone|emph)$/ ) { # Any tag we don't know to disregard
236 say STDERR "Unrecognized tag " . $xn->nodeName;
242 my( $list, @tokens ) = @_;
243 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
244 # The list evidently ended mid-word; join the next token onto it.
245 my $t = shift @tokens;
246 if( ref $t && $t->{'type'} eq 'token' ) {
248 $t = $t->{'content'};
250 # An app or anchor intervened; end the word.
251 unshift( @tokens, $t );
254 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
256 foreach my $t ( @tokens ) {
257 unless( ref( $t ) ) {
258 $t = { 'type' => 'token', 'content' => $t };
265 my( $c, $app_id, $opts ) = @_;
266 my $xn = $apps{$app_id};
267 my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
269 # Get the lemma, which is all the readings between app and anchor,
270 # excluding other apps or anchors.
271 my @lemma = _return_lemma( $c, $app_id, $anchor );
272 my $lemma_str = join( ' ', map { $_->text } grep { !$_->is_ph } @lemma );
274 # For each reading, send its text to 'interpret' along with the lemma,
275 # and then save the list of witnesses that these tokens belong to.
276 my %wit_rdgs; # Maps from witnesses to the variant text
279 $tag =~ s/^\__APP_(.*)\__$/$1/;
281 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
282 my @witlist = split( /\s+/, $rdg->getAttribute( 'wit' ) );
284 foreach ( $rdg->childNodes ) {
285 push( @text, _get_base( $_ ) );
287 my( $interpreted, $flag ) = ( '', undef );
289 ( $interpreted, $flag ) = interpret(
290 join( ' ', map { $_->{'content'} } @text ), $lemma_str, $anchor, $opts );
292 next if( $interpreted eq $lemma_str ) && !keys %$flag; # Reading is lemma.
295 if( $interpreted eq '#LACUNA#' ) {
296 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
297 is_lacuna => 1 } ) );
298 } elsif( $flag->{'TR'} ) {
299 # Our reading is transposed to after the given string. Look
300 # down the collation base text and try to find it.
301 # The @rdg_nodes should remain blank here, so that the correct
302 # omission goes into the graph.
304 foreach my $w ( split( /\s+/, $interpreted ) ) {
305 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
307 push( @transp_nodes, $r );
309 if( $anchor && @lemma ) {
310 my $success = _attach_transposition( $c, \@lemma, $anchor,
311 \@transp_nodes, \@witlist, $flag->{'TR'} );
313 # If we didn't manage to insert the displaced reading,
314 # then restore it here rather than silently deleting it.
315 push( @rdg_nodes, @transp_nodes );
319 foreach my $w ( split( /\s+/, $interpreted ) ) {
320 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
322 push( @rdg_nodes, $r );
326 # For each listed wit, save the reading.
327 # If an A.C. or P.C. reading is implied rather than explicitly noted,
328 # this is where it will be dealt with.
329 foreach my $wit ( @witlist ) {
330 $wit .= '_ac' if $flag->{'AC'};
331 $wit_rdgs{$wit} = \@rdg_nodes;
332 # If the PC flag is set, there is a corresponding AC that
333 # follows the lemma and has to be explicitly declared.
334 if( $flag->{'PC'} ) {
335 $wit_rdgs{$wit.'_ac'} = \@lemma;
339 # Does the reading have an ID? If so it probably has a witDetail
340 # attached, and we need to read it. If an A.C. or P.C. reading is
341 # declared explicity, this is where it will be dealt with.
342 if( $rdg->hasAttribute( 'xml:id' ) ) {
343 warn "Witdetail on meta reading" if $flag; # this could get complicated.
344 my $rid = $rdg->getAttribute( 'xml:id' );
345 my $xpc = XML::LibXML::XPathContext->new( $xn );
346 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
347 foreach my $d ( @details ) {
348 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
353 # Now collate the variant readings, since it is not done for us.
354 collate_variants( $c, \@lemma, values %wit_rdgs );
356 # Now add the witness paths for each reading. If we don't have an anchor
357 # (e.g. with an initial witStart) there was no witness path to speak of.
358 foreach my $wit_id ( keys %wit_rdgs ) {
359 my $witstr = _get_sigil( $wit_id, $c->ac_label );
360 my $rdg_list = $wit_rdgs{$wit_id};
361 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
368 return sprintf( "__ANCHOR_%s__", $xmlid );
372 my( $c, $app, $anchor ) = @_;
373 my @nodes = grep { $_->id !~ /^__A(PP|NCHOR)/ }
374 $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
379 # Make a best-effort attempt to attach a transposition farther down the line.
380 # $lemmaseq contains the Reading objects of the lemma
381 # $anchor contains the point at which we should start scanning for a match
382 # $rdgseq contains the Reading objects of the transposed reading
383 # (should be identical to the lemma)
384 # $witlist contains the list of applicable witnesses
385 # $reftxt contains the text to match, after which the $rdgseq should go.
386 sub _attach_transposition {
387 my( $c, $lemmaseq, $anchor, $rdgseq, $witlist, $reftxt ) = @_;
388 my @refwords = split( /\s+/, $reftxt );
389 my $checked = $c->reading( $anchor );
392 while( $checked ne $c->end && !$found ) {
393 my $next = $c->next_reading( $checked, $c->baselabel );
394 if( $next->text eq $refwords[0] ) {
395 # See if the entire sequence of words matches.
397 foreach my $w ( 1..$#refwords ) {
398 $found = $c->next_reading( $next, $c->baselabel );
399 unless( $found->text eq $refwords[$w] ) {
408 # The $found variable should now contain the reading after which we
409 # should stick the transposition.
410 my $fnext = $c->next_reading( $found, $c->baselabel );
411 my $aclabel = $c->ac_label;
412 foreach my $wit_id ( @$witlist ) {
413 my $witstr = _get_sigil( $wit_id, $aclabel );
414 _add_wit_path( $c, $rdgseq, $found->id, $fnext->id, $witstr );
416 # ...and add the transposition relationship between lemma and rdgseq.
417 if( @$lemmaseq == @$rdgseq ) {
418 foreach my $i ( 0..$#{$lemmaseq} ) {
419 $c->add_relationship( $lemmaseq->[$i], $rdgseq->[$i],
420 { type => 'transposition', annotation => 'Detected by CTE' } );
424 throw( "Lemma at $found and transposed sequence different lengths?!" );
427 say STDERR "WARNING: Unable to find $reftxt in base text for transposition";
432 =head2 interpret( $reading, $lemma )
434 Given a string in $reading and a corresponding lemma in $lemma, interpret what
435 the actual reading should be. Used to deal with apparatus-ese shorthands for
436 marking transpositions, prefixed or suffixed words, and the like.
441 # A utility function to change apparatus-ese into a full variant.
442 my( $reading, $lemma, $anchor, $opts ) = @_;
443 return $reading if $reading eq $lemma;
444 my $oldreading = $reading;
445 # $lemma =~ s/\s+[[:punct:]]+$//;
446 my $flag = {}; # To pass back extra info about the interpretation
447 my @words = split( /\s+/, $lemma );
448 # Discard any 'sic' notation - that rather goes without saying.
449 $reading =~ s/([[:punct:]]+)?sic([[:punct:]]+)?//g;
451 # Now look for common jargon.
452 if( $reading =~ /^(.*) praem.$/ || $reading =~ /^praem\. (.*)$/ ) {
453 $reading = "$1 $lemma";
454 } elsif( $reading =~ /^(.*) add.$/ || $reading =~ /^add\. (.*)$/ ) {
455 $reading = "$lemma $1";
456 } elsif( $reading =~ /locus [uv]acuus/
457 || $reading eq 'def.'
458 || $reading eq 'illeg.'
459 || $reading eq 'desunt'
461 $reading = '#LACUNA#';
462 } elsif( $reading eq 'om.' ) {
464 } elsif( $reading =~ /^in[uv]\.$/
465 || $reading =~ /^tr(ans(p)?)?\.$/ ) {
466 # Hope it is two words.
467 say STDERR "WARNING: want to invert a lemma that is not two words"
468 unless scalar( @words ) == 2;
469 $reading = join( ' ', reverse( @words ) );
470 } elsif( $reading =~ /^iter(\.|at)$/ ) {
472 $reading = "$lemma $lemma";
473 } elsif( $reading =~ /^(.*?)\s*\(?in marg\.\)?$/ ) {
476 # The given text is a correction.
479 # The lemma itself was the correction; the witness carried
480 # no reading pre-correction.
483 } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
484 # The first and last N words captured should replace the first and
485 # last N words of the lemma.
486 my @begin = split( /\s+/, $1 );
487 my @end = split( /\s+/, $2 );
488 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
489 # Something is wrong and we can't do the splice.
490 throw( "$lemma is too short to accommodate $oldreading" );
492 splice( @words, 0, scalar @begin, @begin );
493 splice( @words, -(scalar @end), scalar @end, @end );
494 $reading = join( ' ', @words );
496 } elsif( $opts->{interpret_transposition} &&
497 ( $reading =~ /^post\s*(?<lem>.*?)\s+tr(ans(p)?)?\.$/ ||
498 $reading =~ /^tr(ans(p)?)?\. post\s*(?<lem>.*)$/) ) {
499 # Try to deal with transposed readings
501 say STDERR "Will attempt transposition: $reading at $anchor";
503 $flag->{'TR'} = $+{lem};
505 return( $reading, $flag );
508 sub _parse_wit_detail {
509 my( $detail, $readings, $lemma ) = @_;
510 my $wit = $detail->getAttribute( 'wit' );
511 my $content = $detail->textContent;
512 if( $content =~ /^a\.?\s*c(orr)?\.$/ ) {
513 # Replace the key in the $readings hash
514 my $rdg = delete $readings->{$wit};
515 $readings->{$wit.'_ac'} = $rdg;
516 $has_ac{$sigil_for{$wit}} = 1;
517 } elsif( $content =~ /^p\.?\s*c(orr)?\.$/ || $content =~ /^s\.?\s*l\.$/ ) {
518 # If no key for the wit a.c. exists, add one pointing to the lemma
519 unless( exists $readings->{$wit.'_ac'} ) {
520 $readings->{$wit.'_ac'} = $lemma;
522 $has_ac{$sigil_for{$wit}} = 1;
523 } else { #...not sure what it is?
524 say STDERR "WARNING: Unrecognized sigil addendum $content";
529 my( $c, @apps ) = @_;
530 # Go through the apparatus entries in order, noting where to start and stop our
534 foreach my $app ( @apps ) {
535 # Find the anchor, if any. This marks the point where the text starts
537 my $anchor = $app->getAttribute( 'to' );
541 $aname = _anchor_name( $anchor );
544 foreach my $rdg ( $app->getChildrenByTagName( 'rdg' ) ) {
545 my @witlist = map { _get_sigil( $_, $c->ac_label ) }
546 split( /\s+/, $rdg->getAttribute( 'wit' ) );
547 my @start = $rdg->getChildrenByTagName( 'witStart' );
548 my @end = $rdg->getChildrenByTagName( 'witEnd' );
549 if( @start && @end ) {
550 throw( "App sig entry at $anchor has both witStart and witEnd!" );
552 if( @start && $anchor &&
553 $c->prior_reading( $aname, $c->baselabel ) ne $c->start ) {
554 # We are picking back up after a hiatus. Find the last end and
555 # add a lacuna link between there and here.
556 foreach my $wit ( @witlist ) {
557 my $stoppoint = delete $lacunose{$wit};
558 my $stopname = $stoppoint ? _anchor_name( $stoppoint ) : $c->start->id;
559 say STDERR "Adding lacuna for $wit between $stopname and $anchor";
560 my $lacuna = $c->add_reading( { id => "as_$anchor.".$ctr++,
562 _add_wit_path( $c, [ $lacuna ], $stopname, $aname, $wit );
564 } elsif( @end && $anchor &&
565 $c->next_reading( $aname, $c->baselabel ) ne $c->end ) {
566 # We are stopping. If we've already stopped for the given witness,
567 # flag an error; otherwise record the stopping point.
568 foreach my $wit ( @witlist ) {
569 if( $lacunose{$wit} ) {
570 throw( "Trying to end $wit at $anchor when already ended at "
573 $lacunose{$wit} = $anchor;
579 # For whatever remains in the %lacunose hash, add a lacuna between that spot and
580 # $c->end for each of the witnesses.
581 foreach my $wit ( keys %lacunose ) {
582 next unless $lacunose{$wit};
583 my $aname = _anchor_name( $lacunose{$wit} );
584 say STDERR "Adding lacuna for $wit from $aname to end";
585 my $lacuna = $c->add_reading( { id => 'as_'.$lacunose{$wit}.'.'.$ctr++,
587 _add_wit_path( $c, [ $lacuna ], $aname, $c->end, $wit );
592 my( $xml_id, $layerlabel ) = @_;
593 if( $xml_id =~ /^(.*)_ac$/ ) {
595 return $sigil_for{$real_id} . $layerlabel;
597 return $sigil_for{$xml_id};
601 sub _expand_all_paths {
604 # Walk the collation and fish out the paths for each witness
605 foreach my $wit ( $c->tradition->witnesses ) {
606 my $sig = $wit->sigil;
607 my @path = grep { !$_->is_ph }
608 $c->reading_sequence( $c->start, $c->end, $sig );
609 $wit->path( \@path );
610 if( $has_ac{$sig} ) {
611 my @ac_path = grep { !$_->is_ph }
612 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
613 $wit->uncorrected_path( \@ac_path );
618 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
619 $c->del_reading( $anchor );
621 # Delete the base edges
622 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
624 # Make the path edges
625 $c->make_witness_paths();
627 # Now remove any orphan nodes, and warn that we are doing so.
628 while( $c->sequence->predecessorless_vertices > 1 ) {
629 foreach my $v ( $c->sequence->predecessorless_vertices ) {
630 my $r = $c->reading( $v );
631 next if $r->is_start;
632 say STDERR "Deleting orphan reading $r / " . $r->text;
633 $c->del_reading( $r );
639 my( $c, $rdg, $app, $anchor, $wit ) = @_;
641 push( @nodes, $c->reading( $anchor ) );
643 my $cur = $c->reading( $app );
644 foreach my $n ( @nodes ) {
645 $c->add_path( $cur, $n, $wit );
651 Text::Tradition::Error->throw(
652 'ident' => 'Parser::CTE error',
659 This package is free software and is provided "as is" without express
660 or implied warranty. You can redistribute it and/or modify it under
661 the same terms as Perl itself.
665 Tara L Andrews, aurum@cpan.org