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.
125 _expand_all_paths( $c );
130 # Save the text for each witness so that we can ensure consistency
132 unless( $opts->{'nocalc'} ) {
134 $tradition->collation->text_from_paths();
135 $tradition->collation->calculate_ranks();
136 $tradition->collation->flatten_ranks();
143 sub _stringify_sigil {
145 my @parts = grep { /\w/ } map { $_->data } @nodes;
146 my $whole = join( '', @parts );
151 sub _tidy_identifier {
157 # Get rid of all the formatting elements that get in the way of tokenization.
158 sub _remove_formatting {
161 # First, parse the original XML
162 my $parser = XML::LibXML->new();
164 if( exists $opts->{'string'} ) {
165 $doc = $parser->parse_string( $opts->{'string'} );
166 } elsif ( exists $opts->{'file'} ) {
167 $doc = $parser->parse_file( $opts->{'file'} );
168 } elsif ( exists $opts->{'xmlobj'} ) {
169 $doc = $opts->{'xmlobj'};
171 warn "Could not find string or file option to parse";
175 # Second, remove the formatting
176 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
177 my @useless = $xpc->findnodes( '//hi' );
178 foreach my $n ( @useless ) {
179 my $parent = $n->parentNode();
180 my @children = $n->childNodes();
181 my $first = shift @children;
183 $parent->replaceChild( $first, $n );
184 foreach my $c ( @children ) {
185 $parent->insertAfter( $c, $first );
189 $parent->removeChild( $n );
193 # Third, write out and reparse to merge the text nodes.
194 my $enc = $doc->encoding || 'UTF-8';
195 my $result = decode( $enc, $doc->toString() );
196 my $tei = $parser->parse_string( $result )->documentElement;
197 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
198 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
200 $xpc = XML::LibXML::XPathContext->new( $tei );
201 return( $tei, $xpc );
204 ## Helper function to help us navigate through nested XML, picking out
205 ## the words, the apparatus, and the anchors.
210 if( $xn->nodeType == XML_TEXT_NODE ) {
211 # Base text, just split the words on whitespace and add them
215 my @tokens = split( /\s+/, $str );
216 push( @readings, map { { type => 'token', content => $_ } } @tokens );
217 } elsif( $xn->nodeName eq 'app' ) {
218 # Apparatus, just save the entire XML node.
219 push( @readings, { type => 'app', content => $xn } );
220 } elsif( $xn->nodeName eq 'anchor' ) {
221 # Anchor to mark the end of some apparatus; save its ID.
222 if( $xn->hasAttribute('xml:id') ) {
223 push( @readings, { type => 'anchor',
224 content => $xn->getAttribute( 'xml:id' ) } );
225 } # if the anchor has no XML ID, it is not relevant to us.
226 } elsif( $xn->nodeName !~ /^(note|seg|milestone|emph)$/ ) { # Any tag we don't know to disregard
227 say STDERR "Unrecognized tag " . $xn->nodeName;
233 my( $list, @tokens ) = @_;
234 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
235 # The list evidently ended mid-word; join the next token onto it.
236 my $t = shift @tokens;
237 if( ref $t && $t->{'type'} eq 'token' ) {
239 $t = $t->{'content'};
241 # An app or anchor intervened; end the word.
242 unshift( @tokens, $t );
245 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
247 foreach my $t ( @tokens ) {
248 unless( ref( $t ) ) {
249 $t = { 'type' => 'token', 'content' => $t };
256 my( $c, $app_id, $opts ) = @_;
257 my $xn = $apps{$app_id};
258 my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
260 # Get the lemma, which is all the readings between app and anchor,
261 # excluding other apps or anchors.
262 my @lemma = _return_lemma( $c, $app_id, $anchor );
263 my $lemma_str = join( ' ', map { $_->text } grep { !$_->is_ph } @lemma );
265 # For each reading, send its text to 'interpret' along with the lemma,
266 # and then save the list of witnesses that these tokens belong to.
267 my %wit_rdgs; # Maps from witnesses to the variant text
270 $tag =~ s/^\__APP_(.*)\__$/$1/;
272 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
273 my @witlist = split( /\s+/, $rdg->getAttribute( 'wit' ) );
275 foreach ( $rdg->childNodes ) {
276 push( @text, _get_base( $_ ) );
278 my( $interpreted, $flag ) = ( '', undef );
280 ( $interpreted, $flag ) = interpret(
281 join( ' ', map { $_->{'content'} } @text ), $lemma_str, $anchor, $opts );
283 next if( $interpreted eq $lemma_str ) && !keys %$flag; # Reading is lemma.
286 if( $interpreted eq '#LACUNA#' ) {
287 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
288 is_lacuna => 1 } ) );
289 } elsif( $flag->{'TR'} ) {
290 # Our reading is transposed to after the given string. Look
291 # down the collation base text and try to find it.
292 # The @rdg_nodes should remain blank here, so that the correct
293 # omission goes into the graph.
295 foreach my $w ( split( /\s+/, $interpreted ) ) {
296 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
298 push( @transp_nodes, $r );
300 if( $anchor && @lemma ) {
301 my $success = _attach_transposition( $c, \@lemma, $anchor,
302 \@transp_nodes, \@witlist, $flag->{'TR'} );
304 # If we didn't manage to insert the displaced reading,
305 # then restore it here rather than silently deleting it.
306 push( @rdg_nodes, @transp_nodes );
310 foreach my $w ( split( /\s+/, $interpreted ) ) {
311 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
313 push( @rdg_nodes, $r );
317 # For each listed wit, save the reading.
318 # If an A.C. or P.C. reading is implied rather than explicitly noted,
319 # this is where it will be dealt with.
320 foreach my $wit ( @witlist ) {
321 $wit .= '_ac' if $flag->{'AC'};
322 $wit_rdgs{$wit} = \@rdg_nodes;
323 # If the PC flag is set, there is a corresponding AC that
324 # follows the lemma and has to be explicitly declared.
325 if( $flag->{'PC'} ) {
326 $wit_rdgs{$wit.'_ac'} = \@lemma;
330 # Does the reading have an ID? If so it probably has a witDetail
331 # attached, and we need to read it. If an A.C. or P.C. reading is
332 # declared explicity, this is where it will be dealt with.
333 if( $rdg->hasAttribute( 'xml:id' ) ) {
334 warn "Witdetail on meta reading" if $flag; # this could get complicated.
335 my $rid = $rdg->getAttribute( 'xml:id' );
336 my $xpc = XML::LibXML::XPathContext->new( $xn );
337 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
338 foreach my $d ( @details ) {
339 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
344 # Now collate the variant readings, since it is not done for us.
345 collate_variants( $c, \@lemma, values %wit_rdgs );
347 # Now add the witness paths for each reading. If we don't have an anchor
348 # (e.g. with an initial witStart) there was no witness path to speak of.
349 foreach my $wit_id ( keys %wit_rdgs ) {
350 my $witstr = _get_sigil( $wit_id, $c->ac_label );
351 my $rdg_list = $wit_rdgs{$wit_id};
352 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
359 return sprintf( "__ANCHOR_%s__", $xmlid );
363 my( $c, $app, $anchor ) = @_;
364 my @nodes = grep { $_->id !~ /^__A(PP|NCHOR)/ }
365 $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
370 # Make a best-effort attempt to attach a transposition farther down the line.
371 # $lemmaseq contains the Reading objects of the lemma
372 # $anchor contains the point at which we should start scanning for a match
373 # $rdgseq contains the Reading objects of the transposed reading
374 # (should be identical to the lemma)
375 # $witlist contains the list of applicable witnesses
376 # $reftxt contains the text to match, after which the $rdgseq should go.
377 sub _attach_transposition {
378 my( $c, $lemmaseq, $anchor, $rdgseq, $witlist, $reftxt ) = @_;
379 my @refwords = split( /\s+/, $reftxt );
380 my $checked = $c->reading( $anchor );
383 while( $checked ne $c->end && !$found ) {
384 my $next = $c->next_reading( $checked, $c->baselabel );
385 if( $next->text eq $refwords[0] ) {
386 # See if the entire sequence of words matches.
388 foreach my $w ( 1..$#refwords ) {
389 $found = $c->next_reading( $next, $c->baselabel );
390 unless( $found->text eq $refwords[$w] ) {
399 # The $found variable should now contain the reading after which we
400 # should stick the transposition.
401 my $fnext = $c->next_reading( $found, $c->baselabel );
402 my $aclabel = $c->ac_label;
403 foreach my $wit_id ( @$witlist ) {
404 my $witstr = _get_sigil( $wit_id, $aclabel );
405 _add_wit_path( $c, $rdgseq, $found->id, $fnext->id, $witstr );
407 # ...and add the transposition relationship between lemma and rdgseq.
408 if( @$lemmaseq == @$rdgseq ) {
409 foreach my $i ( 0..$#{$lemmaseq} ) {
410 $c->add_relationship( $lemmaseq->[$i], $rdgseq->[$i],
411 { type => 'transposition', annotation => 'Detected by CTE' } );
415 throw( "Lemma at $found and transposed sequence different lengths?!" );
418 say STDERR "WARNING: Unable to find $reftxt in base text for transposition";
423 =head2 interpret( $reading, $lemma )
425 Given a string in $reading and a corresponding lemma in $lemma, interpret what
426 the actual reading should be. Used to deal with apparatus-ese shorthands for
427 marking transpositions, prefixed or suffixed words, and the like.
432 # A utility function to change apparatus-ese into a full variant.
433 my( $reading, $lemma, $anchor, $opts ) = @_;
434 return $reading if $reading eq $lemma;
435 my $oldreading = $reading;
436 # $lemma =~ s/\s+[[:punct:]]+$//;
437 my $flag = {}; # To pass back extra info about the interpretation
438 my @words = split( /\s+/, $lemma );
439 # Discard any 'sic' notation - that rather goes without saying.
440 $reading =~ s/([[:punct:]]+)?sic([[:punct:]]+)?//g;
442 # Now look for common jargon.
443 if( $reading =~ /^(.*) praem.$/ || $reading =~ /^praem\. (.*)$/ ) {
444 $reading = "$1 $lemma";
445 } elsif( $reading =~ /^(.*) add.$/ || $reading =~ /^add\. (.*)$/ ) {
446 $reading = "$lemma $1";
447 } elsif( $reading =~ /locus [uv]acuus/
448 || $reading eq 'def.'
449 || $reading eq 'illeg.'
450 || $reading eq 'desunt'
452 $reading = '#LACUNA#';
453 } elsif( $reading eq 'om.' ) {
455 } elsif( $reading =~ /^in[uv]\.$/
456 || $reading =~ /^tr(ans(p)?)?\.$/ ) {
457 # Hope it is two words.
458 say STDERR "WARNING: want to invert a lemma that is not two words"
459 unless scalar( @words ) == 2;
460 $reading = join( ' ', reverse( @words ) );
461 } elsif( $reading =~ /^iter(\.|at)$/ ) {
463 $reading = "$lemma $lemma";
464 } elsif( $reading =~ /^(.*?)\s*\(?in marg\.\)?$/ ) {
467 # The given text is a correction.
470 # The lemma itself was the correction; the witness carried
471 # no reading pre-correction.
474 } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
475 # The first and last N words captured should replace the first and
476 # last N words of the lemma.
477 my @begin = split( /\s+/, $1 );
478 my @end = split( /\s+/, $2 );
479 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
480 # Something is wrong and we can't do the splice.
481 throw( "$lemma is too short to accommodate $oldreading" );
483 splice( @words, 0, scalar @begin, @begin );
484 splice( @words, -(scalar @end), scalar @end, @end );
485 $reading = join( ' ', @words );
487 } elsif( $opts->{interpret_transposition} &&
488 ( $reading =~ /^post\s*(?<lem>.*?)\s+tr(ans(p)?)?\.$/ ||
489 $reading =~ /^tr(ans(p)?)?\. post\s*(?<lem>.*)$/) ) {
490 # Try to deal with transposed readings
492 say STDERR "Will attempt transposition: $reading at $anchor";
494 $flag->{'TR'} = $+{lem};
496 return( $reading, $flag );
499 sub _parse_wit_detail {
500 my( $detail, $readings, $lemma ) = @_;
501 my $wit = $detail->getAttribute( 'wit' );
502 my $content = $detail->textContent;
503 if( $content =~ /^a\.?\s*c(orr)?\.$/ ) {
504 # Replace the key in the $readings hash
505 my $rdg = delete $readings->{$wit};
506 $readings->{$wit.'_ac'} = $rdg;
507 $has_ac{$sigil_for{$wit}} = 1;
508 } elsif( $content =~ /^p\.?\s*c(orr)?\.$/ || $content =~ /^s\.?\s*l\.$/ ) {
509 # If no key for the wit a.c. exists, add one pointing to the lemma
510 unless( exists $readings->{$wit.'_ac'} ) {
511 $readings->{$wit.'_ac'} = $lemma;
513 $has_ac{$sigil_for{$wit}} = 1;
514 } else { #...not sure what it is?
515 say STDERR "WARNING: Unrecognized sigil addendum $content";
520 my( $c, @apps ) = @_;
521 # Go through the apparatus entries in order, noting where to start and stop our
525 foreach my $app ( @apps ) {
526 # Find the anchor, if any. This marks the point where the text starts
528 my $anchor = $app->getAttribute( 'to' );
531 $aname = _anchor_name( $anchor );
534 foreach my $rdg ( $app->getChildrenByTagName( 'rdg' ) ) {
535 my @witlist = map { _get_sigil( $_, $c->ac_label ) }
536 split( /\s+/, $rdg->getAttribute( 'wit' ) );
537 my @start = $rdg->getChildrenByTagName( 'witStart' );
538 my @end = $rdg->getChildrenByTagName( 'witEnd' );
539 if( @start && @end ) {
540 throw( "App sig entry at $anchor has both witStart and witEnd!" );
542 if( @start && $anchor &&
543 $c->prior_reading( $aname, $c->baselabel ) ne $c->start ) {
544 # We are picking back up after a hiatus. Find the last end and
545 # add a lacuna link between there and here.
546 foreach my $wit ( @witlist ) {
547 my $stoppoint = delete $lacunose{$wit};
548 $stoppoint = $c->start unless $stoppoint;
549 my $stopname = _anchor_name( $stoppoint );
550 say STDERR "Adding lacuna for $wit between $stoppoint and $anchor";
551 my $lacuna = $c->add_reading( { id => "as_$anchor.".$ctr++,
553 _add_wit_path( $c, [ $lacuna ], $stopname, $aname, $wit );
555 } elsif( @end && $anchor &&
556 $c->next_reading( $aname, $c->baselabel ) ne $c->end ) {
557 # We are stopping. If we've already stopped for the given witness,
558 # flag an error; otherwise record the stopping point.
559 foreach my $wit ( @witlist ) {
560 if( $lacunose{$wit} ) {
561 throw( "Trying to end $wit at $anchor when already ended at "
564 $lacunose{$wit} = $anchor;
570 # For whatever remains in the %lacunose hash, add a lacuna between that spot and
571 # $c->end for each of the witnesses.
572 foreach my $wit ( keys %lacunose ) {
573 next unless $lacunose{$wit};
574 my $aname = _anchor_name( $lacunose{$wit} );
575 say STDERR "Adding lacuna for $wit from $aname to end";
576 my $lacuna = $c->add_reading( { id => 'as_'.$lacunose{$wit}.'.'.$ctr++,
578 _add_wit_path( $c, [ $lacuna ], $aname, $c->end, $wit );
583 my( $xml_id, $layerlabel ) = @_;
584 if( $xml_id =~ /^(.*)_ac$/ ) {
586 return $sigil_for{$real_id} . $layerlabel;
588 return $sigil_for{$xml_id};
592 sub _expand_all_paths {
595 # Walk the collation and fish out the paths for each witness
596 foreach my $wit ( $c->tradition->witnesses ) {
597 my $sig = $wit->sigil;
598 my @path = grep { !$_->is_ph }
599 $c->reading_sequence( $c->start, $c->end, $sig );
600 $wit->path( \@path );
601 if( $has_ac{$sig} ) {
602 my @ac_path = grep { !$_->is_ph }
603 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
604 $wit->uncorrected_path( \@ac_path );
609 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
610 $c->del_reading( $anchor );
612 # Delete the base edges
613 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
615 # Make the path edges
616 $c->make_witness_paths();
618 # Now remove any orphan nodes, and warn that we are doing so.
619 while( $c->sequence->predecessorless_vertices > 1 ) {
620 foreach my $v ( $c->sequence->predecessorless_vertices ) {
621 my $r = $c->reading( $v );
622 next if $r->is_start;
623 say STDERR "Deleting orphan reading $r / " . $r->text;
624 $c->del_reading( $r );
630 my( $c, $rdg, $app, $anchor, $wit ) = @_;
632 push( @nodes, $c->reading( $anchor ) );
634 my $cur = $c->reading( $app );
635 foreach my $n ( @nodes ) {
636 $c->add_path( $cur, $n, $wit );
642 Text::Tradition::Error->throw(
643 'ident' => 'Parser::CTE error',
650 This package is free software and is provided "as is" without express
651 or implied warranty. You can redistribute it and/or modify it under
652 the same terms as Perl itself.
656 Tara L Andrews, aurum@cpan.org