1 package Text::Tradition::Parser::CTE;
5 use Encode qw/ decode /;
6 use Text::Tradition::Error;
7 use Text::Tradition::Parser::Util qw/ collate_variants /;
9 use XML::LibXML::XPathContext;
13 Text::Tradition::Parser::CTE
17 Parser module for Text::Tradition, given a TEI file exported from
18 Classical Text Editor.
24 my @apparatus = read( $xml_file );
26 Takes a Tradition object and a TEI file exported from Classical Text
27 Editor using double-endpoint-attachment critical apparatus encoding;
28 initializes the Tradition from the file.
32 my %sigil_for; # Save the XML IDs for witnesses.
33 my %apps; # Save the apparatus XML for a given ID.
34 my %has_ac; # Keep track of witnesses that have corrections.
37 my( $tradition, $opts ) = @_;
38 my $c = $tradition->collation; # Some shorthand
40 # First, parse the XML.
41 my( $tei, $xpc ) = _remove_formatting( $opts );
42 return unless $tei; # we have already warned.
44 # CTE uses a DTD rather than any xmlns-based parsing. Thus we
45 # need no namespace handling.
46 # Get the witnesses and create the witness objects.
47 foreach my $wit_el ( $xpc->findnodes( '//sourceDesc/listWit/witness' ) ) {
48 # The witness xml:id is used internally, and is *not* the sigil name.
49 my $id= $wit_el->getAttribute( 'xml:id' );
50 my @sig_parts = $xpc->findnodes( 'descendant::text()', $wit_el );
51 my $sig = _stringify_sigil( @sig_parts );
52 print STDERR "Adding witness $sig\n";
53 $tradition->add_witness( sigil => $sig, sourcetype => 'collation' );
54 $sigil_for{'#'.$id} = $sig; # Make life easy by keying on the ID ref syntax
57 # Now go through the text and find the base tokens, apparatus tags, and
58 # anchors. Make a giant array of all of these things in sequence.
59 # TODO consider combining this with creation of graph below
61 foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
62 foreach my $xn ( $pg_el->childNodes ) {
63 push( @base_text, _get_base( $xn ) );
66 # We now have to work through this array applying the alternate
67 # apparatus readings to the base text. Essentially we will put
68 # everything on the graph, from which we will delete the apps and
69 # anchors when we are done.
71 # First, put the base tokens, apps, and anchors in the graph.
74 foreach my $item ( @base_text ) {
76 if( $item->{'type'} eq 'token' ) {
77 $r = $c->add_reading( { id => 'n'.$counter++,
78 text => $item->{'content'} } );
79 } elsif ( $item->{'type'} eq 'anchor' ) {
80 $r = $c->add_reading( { id => '__ANCHOR_' . $item->{'content'} . '__',
82 } elsif ( $item->{'type'} eq 'app' ) {
83 my $tag = '__APP_' . $counter++ . '__';
84 $r = $c->add_reading( { id => $tag, is_ph => 1 } );
85 $apps{$tag} = $item->{'content'};
87 $c->add_path( $last, $r, $c->baselabel );
90 $c->add_path( $last, $c->end, $c->baselabel );
92 # Now we can parse the apparatus entries, and add the variant readings
95 foreach my $app_id ( keys %apps ) {
96 _add_readings( $c, $app_id );
99 # Finally, add explicit witness paths, remove the base paths, and remove
100 # the app/anchor tags.
101 _expand_all_paths( $c );
103 # Save the text for each witness so that we can ensure consistency
105 $tradition->collation->text_from_paths();
106 $tradition->collation->calculate_ranks();
107 $tradition->collation->flatten_ranks();
110 sub _stringify_sigil {
112 my @parts = grep { /\w/ } map { $_->data } @nodes;
113 my $whole = join( '', @parts );
118 # Get rid of all the formatting elements that get in the way of tokenization.
119 sub _remove_formatting {
122 # First, parse the original XML
123 my $parser = XML::LibXML->new();
125 if( exists $opts->{'string'} ) {
126 $doc = $parser->parse_string( $opts->{'string'} );
127 } elsif ( exists $opts->{'file'} ) {
128 $doc = $parser->parse_file( $opts->{'file'} );
130 warn "Could not find string or file option to parse";
134 # Second, remove the formatting
135 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
136 my @useless = $xpc->findnodes( '//hi' );
137 foreach my $n ( @useless ) {
138 my $parent = $n->parentNode();
139 my @children = $n->childNodes();
140 my $first = shift @children;
141 $parent->replaceChild( $first, $n );
142 foreach my $c ( @children ) {
143 $parent->insertAfter( $c, $first );
148 # Third, write out and reparse to merge the text nodes.
149 my $enc = $doc->encoding || 'UTF-8';
150 my $result = decode( $enc, $doc->toString() );
151 my $tei = $parser->parse_string( $result )->documentElement;
152 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
153 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
155 $xpc = XML::LibXML::XPathContext->new( $tei );
156 return( $tei, $xpc );
159 ## Helper function to help us navigate through nested XML, picking out
160 ## the words, the apparatus, and the anchors.
165 if( $xn->nodeType == XML_TEXT_NODE ) {
166 # Base text, just split the words on whitespace and add them
170 my @tokens = split( /\s+/, $str );
171 push( @readings, map { { 'type' => 'token', 'content' => $_ } } @tokens );
172 } elsif( $xn->nodeName eq 'app' ) {
173 # Apparatus, just save the entire XML node.
174 push( @readings, { 'type' => 'app', 'content' => $xn } );
175 } elsif( $xn->nodeName eq 'anchor' ) {
176 # Anchor to mark the end of some apparatus; save its ID.
177 push( @readings, { 'type' => 'anchor',
178 'content' => $xn->getAttribute( 'xml:id' ) } );
179 } elsif ( $xn->nodeName ne 'note' ) { # Any tag we don't know to disregard
180 print STDERR "Unrecognized tag " . $xn->nodeName . "\n";
186 my( $list, @tokens ) = @_;
187 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
188 # The list evidently ended mid-word; join the next token onto it.
189 my $t = shift @tokens;
190 if( ref $t && $t->{'type'} eq 'token' ) {
192 $t = $t->{'content'};
194 # An app or anchor intervened; end the word.
195 unshift( @tokens, $t );
198 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
200 foreach my $t ( @tokens ) {
201 unless( ref( $t ) ) {
202 $t = { 'type' => 'token', 'content' => $t };
209 my( $c, $app_id ) = @_;
210 my $xn = $apps{$app_id};
211 my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
212 # Get the lemma, which is all the readings between app and anchor,
213 # excluding other apps or anchors.
214 my @lemma = _return_lemma( $c, $app_id, $anchor );
215 my $lemma_str = join( ' ', grep { $_ !~ /^__/ } map { $_->text } @lemma );
217 # For each reading, send its text to 'interpret' along with the lemma,
218 # and then save the list of witnesses that these tokens belong to.
219 my %wit_rdgs; # Maps from witnesses to the variant text
222 $tag =~ s/^\__APP_(.*)\__$/$1/;
224 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
226 foreach ( $rdg->childNodes ) {
227 push( @text, _get_base( $_ ) );
229 my( $interpreted, $flag ) = ( '', undef );
231 ( $interpreted, $flag ) = interpret(
232 join( ' ', map { $_->{'content'} } @text ), $lemma_str );
234 next if( $interpreted eq $lemma_str ) && !$flag; # Reading is lemma.
237 if( $interpreted eq '#LACUNA#' ) {
238 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
239 is_lacuna => 1 } ) );
241 foreach my $w ( split( /\s+/, $interpreted ) ) {
242 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
244 push( @rdg_nodes, $r );
247 # For each listed wit, save the reading.
248 foreach my $wit ( split( /\s+/, $rdg->getAttribute( 'wit' ) ) ) {
249 $wit .= $flag if $flag;
250 $wit_rdgs{$wit} = \@rdg_nodes;
253 # Does the reading have an ID? If so it probably has a witDetail
254 # attached, and we need to read it.
255 if( $rdg->hasAttribute( 'xml:id' ) ) {
256 warn "Witdetail on meta reading" if $flag; # this could get complicated.
257 my $rid = $rdg->getAttribute( 'xml:id' );
258 my $xpc = XML::LibXML::XPathContext->new( $xn );
259 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
260 foreach my $d ( @details ) {
261 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
266 # Now collate the variant readings, since it is not done for us.
267 collate_variants( $c, \@lemma, values %wit_rdgs );
269 # Now add the witness paths for each reading.
270 my $aclabel = $c->ac_label;
271 foreach my $wit_id ( keys %wit_rdgs ) {
272 my $witstr = _get_sigil( $wit_id, $aclabel );
273 my $rdg_list = $wit_rdgs{$wit_id};
274 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
281 return sprintf( "__ANCHOR_%s__", $xmlid );
285 my( $c, $app, $anchor ) = @_;
286 my @nodes = grep { $_->id !~ /^__A(PP|NCHOR)/ }
287 $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
292 =head2 interpret( $reading, $lemma )
294 Given a string in $reading and a corresponding lemma in $lemma, interpret what
295 the actual reading should be. Used to deal with apparatus-ese shorthands for
296 marking transpositions, prefixed or suffixed words, and the like.
301 # A utility function to change apparatus-ese into a full variant.
302 my( $reading, $lemma ) = @_;
303 return $reading if $reading eq $lemma;
304 my $oldreading = $reading;
305 # $lemma =~ s/\s+[[:punct:]]+$//;
306 my $flag; # In case of p.c. indications
307 my @words = split( /\s+/, $lemma );
308 if( $reading =~ /^(.*) praem.$/ ) {
309 $reading = "$1 $lemma";
310 } elsif( $reading =~ /^(.*) add.$/ ) {
311 $reading = "$lemma $1";
312 } elsif( $reading =~ /add. alia manu/
313 || $reading =~ /inscriptionem compegi e/ # TODO huh?
314 || $reading eq 'inc.' # TODO huh?
318 } elsif( $reading =~ /locus [uv]acuus/
319 || $reading eq 'def.'
320 || $reading eq 'illeg.'
321 || $reading eq 'onleesbar'
323 $reading = '#LACUNA#';
324 } elsif( $reading eq 'om.' ) {
326 } elsif( $reading =~ /^in[uv]\.$/
327 || $reading eq 'transp.' ) {
328 # Hope it is two words.
329 print STDERR "WARNING: want to invert a lemma that is not two words\n"
330 unless scalar( @words ) == 2;
331 $reading = join( ' ', reverse( @words ) );
332 } elsif( $reading =~ /^iter(\.|at)$/ ) {
334 $reading = "$lemma $lemma";
335 } elsif( $reading eq 'in marg.' ) {
336 # There was nothing before a correction.
339 } elsif( $reading =~ /^(.*?)\s*\(?sic([\s\w.]+)?\)?$/ ) {
340 # Discard any 'sic' notation; indeed, indeed.
342 } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
343 # The first and last N words captured should replace the first and
344 # last N words of the lemma.
345 my @begin = split( /\s+/, $1 );
346 my @end = split( /\s+/, $2 );
347 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
348 # Something is wrong and we can't do the splice.
349 print STDERR "ERROR: $lemma is too short to accommodate $oldreading\n";
351 splice( @words, 0, scalar @begin, @begin );
352 splice( @words, -(scalar @end), scalar @end, @end );
353 $reading = join( ' ', @words );
356 if( $oldreading ne $reading || $flag || $oldreading =~ /\./ ) {
358 $int .= " ($flag)" if $flag;
359 print STDERR "Interpreted $oldreading as $int given $lemma\n";
361 return( $reading, $flag );
364 sub _parse_wit_detail {
365 my( $detail, $readings, $lemma ) = @_;
366 my $wit = $detail->getAttribute( 'wit' );
367 my $content = $detail->textContent;
368 if( $content =~ /a\.\s*c\./ ) {
369 # Replace the key in the $readings hash
370 my $rdg = delete $readings->{$wit};
371 $readings->{$wit.'_ac'} = $rdg;
372 $has_ac{$sigil_for{$wit}} = 1;
373 } elsif( $content =~ /p\.\s*c\./ ) {
374 # If no key for the wit a.c. exists, add one pointing to the lemma
375 unless( exists $readings->{$wit.'_ac'} ) {
376 $readings->{$wit.'_ac'} = $lemma;
378 $has_ac{$sigil_for{$wit}} = 1;
379 } # else don't bother just yet
383 my( $xml_id, $layerlabel ) = @_;
384 if( $xml_id =~ /^(.*)_ac$/ ) {
386 return $sigil_for{$real_id} . $layerlabel;
388 return $sigil_for{$xml_id};
392 sub _expand_all_paths {
395 # Walk the collation and fish out the paths for each witness
396 foreach my $wit ( $c->tradition->witnesses ) {
397 my $sig = $wit->sigil;
398 my @path = grep { !$_->is_ph }
399 $c->reading_sequence( $c->start, $c->end, $sig );
400 $wit->path( \@path );
401 if( $has_ac{$sig} ) {
402 my @ac_path = grep { !$_->is_ph }
403 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
404 $wit->uncorrected_path( \@ac_path );
409 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
410 $c->del_reading( $anchor );
412 # Delete the base edges
413 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
415 # Make the path edges
416 $c->make_witness_paths();
420 my( $c, $rdg, $app, $anchor, $wit ) = @_;
422 push( @nodes, $c->reading( $anchor ) );
424 my $cur = $c->reading( $app );
425 foreach my $n ( @nodes ) {
426 $c->add_path( $cur, $n, $wit );
432 Text::Tradition::Error->throw(
433 'ident' => 'Parser::CTE error',
440 This package is free software and is provided "as is" without express
441 or implied warranty. You can redistribute it and/or modify it under
442 the same terms as Perl itself.
446 Tara L Andrews, aurum@cpan.org