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.
90 foreach my $item ( @base_text ) {
92 if( $item->{'type'} eq 'token' ) {
93 $r = $c->add_reading( { id => 'n'.$counter++,
94 text => $item->{'content'} } );
95 } elsif ( $item->{'type'} eq 'anchor' ) {
96 $r = $c->add_reading( { id => '__ANCHOR_' . $item->{'content'} . '__',
98 } elsif ( $item->{'type'} eq 'app' ) {
99 my $tag = '__APP_' . $counter++ . '__';
100 $r = $c->add_reading( { id => $tag, is_ph => 1 } );
101 $apps{$tag} = $item->{'content'};
103 $c->add_path( $last, $r, $c->baselabel );
106 $c->add_path( $last, $c->end, $c->baselabel );
108 # Now we can parse the apparatus entries, and add the variant readings
110 foreach my $app_id ( keys %apps ) {
111 _add_readings( $c, $app_id, $opts );
114 # Finally, add explicit witness paths, remove the base paths, and remove
115 # the app/anchor tags.
116 _expand_all_paths( $c );
118 # Save the text for each witness so that we can ensure consistency
120 unless( $opts->{'nocalc'} ) {
121 $tradition->collation->text_from_paths();
122 $tradition->collation->calculate_ranks();
123 $tradition->collation->flatten_ranks();
127 sub _stringify_sigil {
129 my @parts = grep { /\w/ } map { $_->data } @nodes;
130 my $whole = join( '', @parts );
135 sub _tidy_identifier {
141 # Get rid of all the formatting elements that get in the way of tokenization.
142 sub _remove_formatting {
145 # First, parse the original XML
146 my $parser = XML::LibXML->new();
148 if( exists $opts->{'string'} ) {
149 $doc = $parser->parse_string( $opts->{'string'} );
150 } elsif ( exists $opts->{'file'} ) {
151 $doc = $parser->parse_file( $opts->{'file'} );
153 warn "Could not find string or file option to parse";
157 # Second, remove the formatting
158 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
159 my @useless = $xpc->findnodes( '//hi' );
160 foreach my $n ( @useless ) {
161 my $parent = $n->parentNode();
162 my @children = $n->childNodes();
163 my $first = shift @children;
165 $parent->replaceChild( $first, $n );
166 foreach my $c ( @children ) {
167 $parent->insertAfter( $c, $first );
171 $parent->removeChild( $n );
175 # Third, write out and reparse to merge the text nodes.
176 my $enc = $doc->encoding || 'UTF-8';
177 my $result = decode( $enc, $doc->toString() );
178 my $tei = $parser->parse_string( $result )->documentElement;
179 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
180 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
182 $xpc = XML::LibXML::XPathContext->new( $tei );
183 return( $tei, $xpc );
186 ## Helper function to help us navigate through nested XML, picking out
187 ## the words, the apparatus, and the anchors.
192 if( $xn->nodeType == XML_TEXT_NODE ) {
193 # Base text, just split the words on whitespace and add them
197 my @tokens = split( /\s+/, $str );
198 push( @readings, map { { type => 'token', content => $_ } } @tokens );
199 } elsif( $xn->nodeName eq 'app' ) {
200 # Apparatus, just save the entire XML node.
201 push( @readings, { type => 'app', content => $xn } );
202 } elsif( $xn->nodeName eq 'anchor' ) {
203 # Anchor to mark the end of some apparatus; save its ID.
204 if( $xn->hasAttribute('xml:id') ) {
205 push( @readings, { type => 'anchor',
206 content => $xn->getAttribute( 'xml:id' ) } );
207 } # if the anchor has no XML ID, it is not relevant to us.
208 } elsif( $xn->nodeName =~ /^wit(Start|End)$/ ){
209 push( @readings, { type => 'token', content => '#' . uc( $1 ) . '#' } );
210 } elsif( $xn->nodeName !~ /^(note|seg|milestone|emph)$/ ) { # Any tag we don't know to disregard
211 say STDERR "Unrecognized tag " . $xn->nodeName;
217 my( $list, @tokens ) = @_;
218 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
219 # The list evidently ended mid-word; join the next token onto it.
220 my $t = shift @tokens;
221 if( ref $t && $t->{'type'} eq 'token' ) {
223 $t = $t->{'content'};
225 # An app or anchor intervened; end the word.
226 unshift( @tokens, $t );
229 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
231 foreach my $t ( @tokens ) {
232 unless( ref( $t ) ) {
233 $t = { 'type' => 'token', 'content' => $t };
240 my( $c, $app_id, $opts ) = @_;
241 my $xn = $apps{$app_id};
242 # If the app is of type a1, it is an apparatus criticus.
243 # If it is of type a2, it is an apparatus codicum and might not
246 if( $xn->hasAttribute('to') ) {
247 $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.
255 @lemma = _return_lemma( $c, $app_id, $anchor );
256 $lemma_str = join( ' ', map { $_->text } grep { !$_->is_ph } @lemma );
259 # For each reading, send its text to 'interpret' along with the lemma,
260 # and then save the list of witnesses that these tokens belong to.
261 my %wit_rdgs; # Maps from witnesses to the variant text
264 $tag =~ s/^\__APP_(.*)\__$/$1/;
266 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
267 my @witlist = split( /\s+/, $rdg->getAttribute( 'wit' ) );
269 foreach ( $rdg->childNodes ) {
270 push( @text, _get_base( $_ ) );
272 my( $interpreted, $flag ) = ( '', undef );
274 ( $interpreted, $flag ) = interpret(
275 join( ' ', map { $_->{'content'} } @text ), $lemma_str, $anchor, $opts );
277 next if( $interpreted eq $lemma_str ) && !keys %$flag; # Reading is lemma.
280 if( $interpreted eq '#LACUNA#' ) {
281 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
282 is_lacuna => 1 } ) );
283 } elsif( $flag->{'TR'} ) {
284 # Our reading is transposed to after the given string. Look
285 # down the collation base text and try to find it.
286 # The @rdg_nodes should remain blank here, so that the correct
287 # omission goes into the graph.
289 foreach my $w ( split( /\s+/, $interpreted ) ) {
290 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
292 push( @transp_nodes, $r );
294 if( $anchor && @lemma ) {
295 my $success = _attach_transposition( $c, \@lemma, $anchor,
296 \@transp_nodes, \@witlist, $flag->{'TR'} );
298 # If we didn't manage to insert the displaced reading,
299 # then restore it here rather than silently deleting it.
300 push( @rdg_nodes, @transp_nodes );
304 if ( $flag->{'START'}
305 && $c->prior_reading( $app_id, $c->baselabel ) ne $c->start ) {
306 # Add a lacuna for the witness start.
307 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
308 is_lacuna => 1 } ) );
310 foreach my $w ( split( /\s+/, $interpreted ) ) {
311 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
313 push( @rdg_nodes, $r );
316 && $c->next_reading( $app_id, $c->baselabel ) ne $c->end ) {
317 # Add a lacuna for the witness end.
318 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
319 is_lacuna => 1 } ) );
323 # For each listed wit, save the reading.
324 # If an A.C. or P.C. reading is implied rather than explicitly noted,
325 # this is where it will be dealt with.
326 foreach my $wit ( @witlist ) {
327 $wit .= '_ac' if $flag->{'AC'};
328 $wit_rdgs{$wit} = \@rdg_nodes;
329 # If the PC flag is set, there is a corresponding AC that
330 # follows the lemma and has to be explicitly declared.
331 if( $flag->{'PC'} ) {
332 $wit_rdgs{$wit.'_ac'} = \@lemma;
336 # Does the reading have an ID? If so it probably has a witDetail
337 # attached, and we need to read it. If an A.C. or P.C. reading is
338 # declared explicity, this is where it will be dealt with.
339 if( $rdg->hasAttribute( 'xml:id' ) ) {
340 warn "Witdetail on meta reading" if $flag; # this could get complicated.
341 my $rid = $rdg->getAttribute( 'xml:id' );
342 my $xpc = XML::LibXML::XPathContext->new( $xn );
343 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
344 foreach my $d ( @details ) {
345 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
350 # Now collate the variant readings, since it is not done for us.
351 collate_variants( $c, \@lemma, values %wit_rdgs );
353 # Now add the witness paths for each reading. If we don't have an anchor
354 # (e.g. with an initial witStart) there was no witness path to speak of.
356 my $aclabel = $c->ac_label;
357 foreach my $wit_id ( keys %wit_rdgs ) {
358 my $witstr = _get_sigil( $wit_id, $aclabel );
359 my $rdg_list = $wit_rdgs{$wit_id};
360 _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 say STDERR "ERROR: lemma 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 say STDERR "ERROR: $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};
504 # Look for processed witStart and witEnd tags
505 } elsif( $reading =~ /^\#START\#\s*(.*)$/ ) {
507 $flag->{'START'} = 1;
508 } elsif( $reading =~ /^(.*?)\s*\#END\#$/ ) {
512 return( $reading, $flag );
515 sub _parse_wit_detail {
516 my( $detail, $readings, $lemma ) = @_;
517 my $wit = $detail->getAttribute( 'wit' );
518 my $content = $detail->textContent;
519 if( $content =~ /^a\.?\s*c(orr)?\.$/ ) {
520 # Replace the key in the $readings hash
521 my $rdg = delete $readings->{$wit};
522 $readings->{$wit.'_ac'} = $rdg;
523 $has_ac{$sigil_for{$wit}} = 1;
524 } elsif( $content =~ /^p\.?\s*c(orr)?\.$/ || $content =~ /^s\.?\s*l\.$/ ) {
525 # If no key for the wit a.c. exists, add one pointing to the lemma
526 unless( exists $readings->{$wit.'_ac'} ) {
527 $readings->{$wit.'_ac'} = $lemma;
529 $has_ac{$sigil_for{$wit}} = 1;
530 } else { #...not sure what it is?
531 say STDERR "WARNING: Unrecognized sigil addendum $content";
536 my( $xml_id, $layerlabel ) = @_;
537 if( $xml_id =~ /^(.*)_ac$/ ) {
539 return $sigil_for{$real_id} . $layerlabel;
541 return $sigil_for{$xml_id};
545 sub _expand_all_paths {
548 # Walk the collation and fish out the paths for each witness
549 foreach my $wit ( $c->tradition->witnesses ) {
550 my $sig = $wit->sigil;
551 my @path = grep { !$_->is_ph }
552 $c->reading_sequence( $c->start, $c->end, $sig );
553 $wit->path( \@path );
554 if( $has_ac{$sig} ) {
555 my @ac_path = grep { !$_->is_ph }
556 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
557 $wit->uncorrected_path( \@ac_path );
562 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
563 $c->del_reading( $anchor );
565 # Delete the base edges
566 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
568 # Make the path edges
569 $c->make_witness_paths();
571 # Now remove any orphan nodes, and warn that we are doing so.
572 while( $c->sequence->predecessorless_vertices > 1 ) {
573 foreach my $v ( $c->sequence->predecessorless_vertices ) {
574 my $r = $c->reading( $v );
575 next if $r->is_start;
576 say STDERR "Deleting orphan reading $r / " . $r->text;
577 $c->del_reading( $r );
583 my( $c, $rdg, $app, $anchor, $wit ) = @_;
585 push( @nodes, $c->reading( $anchor ) );
587 my $cur = $c->reading( $app );
588 foreach my $n ( @nodes ) {
589 $c->add_path( $cur, $n, $wit );
595 Text::Tradition::Error->throw(
596 'ident' => 'Parser::CTE error',
603 This package is free software and is provided "as is" without express
604 or implied warranty. You can redistribute it and/or modify it under
605 the same terms as Perl itself.
609 Tara L Andrews, aurum@cpan.org