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.
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
42 # First, parse the XML.
43 my( $tei, $xpc ) = _remove_formatting( $opts );
44 return unless $tei; # we have already warned.
46 # CTE uses a DTD rather than any xmlns-based parsing. Thus we
47 # need no namespace handling.
48 # Get the witnesses and create the witness objects.
49 foreach my $wit_el ( $xpc->findnodes( '//sourceDesc/listWit/witness' ) ) {
50 # The witness xml:id is used internally, and is *not* the sigil name.
51 my $id= $wit_el->getAttribute( 'xml:id' );
52 my @sig_parts = $xpc->findnodes( 'descendant::text()', $wit_el );
53 my $sig = _stringify_sigil( @sig_parts );
54 print STDERR "Adding witness $sig\n";
55 $tradition->add_witness( sigil => $sig, sourcetype => 'collation' );
56 $sigil_for{'#'.$id} = $sig; # Make life easy by keying on the ID ref syntax
59 # Now go through the text and find the base tokens, apparatus tags, and
60 # anchors. Make a giant array of all of these things in sequence.
61 # TODO consider combining this with creation of graph below
63 foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
64 foreach my $xn ( $pg_el->childNodes ) {
65 push( @base_text, _get_base( $xn ) );
68 # We now have to work through this array applying the alternate
69 # apparatus readings to the base text. Essentially we will put
70 # everything on the graph, from which we will delete the apps and
71 # anchors when we are done.
73 # First, put the base tokens, apps, and anchors in the graph.
76 foreach my $item ( @base_text ) {
78 if( $item->{'type'} eq 'token' ) {
79 $r = $c->add_reading( { id => 'n'.$counter++,
80 text => $item->{'content'} } );
81 } elsif ( $item->{'type'} eq 'anchor' ) {
82 $r = $c->add_reading( { id => '__ANCHOR_' . $item->{'content'} . '__',
84 } elsif ( $item->{'type'} eq 'app' ) {
85 my $tag = '__APP_' . $counter++ . '__';
86 $r = $c->add_reading( { id => $tag, is_ph => 1 } );
87 $apps{$tag} = $item->{'content'};
89 $c->add_path( $last, $r, $c->baselabel );
92 $c->add_path( $last, $c->end, $c->baselabel );
94 # Now we can parse the apparatus entries, and add the variant readings
97 foreach my $app_id ( keys %apps ) {
98 _add_readings( $c, $app_id );
101 # Finally, add explicit witness paths, remove the base paths, and remove
102 # the app/anchor tags.
103 expand_all_paths( $c );
105 # Save the text for each witness so that we can ensure consistency
107 $tradition->collation->text_from_paths();
108 $tradition->collation->calculate_ranks();
109 $tradition->collation->flatten_ranks();
112 sub _stringify_sigil {
114 my @parts = grep { /\w/ } map { $_->data } @nodes;
115 my $whole = join( '', @parts );
120 # Get rid of all the formatting elements that get in the way of tokenization.
121 sub _remove_formatting {
124 # First, parse the original XML
125 my $parser = XML::LibXML->new();
127 if( exists $opts->{'string'} ) {
128 $doc = $parser->parse_string( $opts->{'string'} );
129 } elsif ( exists $opts->{'file'} ) {
130 $doc = $parser->parse_file( $opts->{'file'} );
132 warn "Could not find string or file option to parse";
136 # Second, remove the formatting
137 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
138 my @useless = $xpc->findnodes( '//hi' );
139 foreach my $n ( @useless ) {
140 my $parent = $n->parentNode();
141 my @children = $n->childNodes();
142 my $first = shift @children;
143 $parent->replaceChild( $first, $n );
144 foreach my $c ( @children ) {
145 $parent->insertAfter( $c, $first );
150 # Third, write out and reparse to merge the text nodes.
151 my $enc = $doc->encoding || 'UTF-8';
152 my $result = decode( $enc, $doc->toString() );
153 my $tei = $parser->parse_string( $result )->documentElement;
154 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
155 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
157 $xpc = XML::LibXML::XPathContext->new( $tei );
158 return( $tei, $xpc );
161 ## Helper function to help us navigate through nested XML, picking out
162 ## the words, the apparatus, and the anchors.
167 if( $xn->nodeType == XML_TEXT_NODE ) {
168 # Base text, just split the words on whitespace and add them
172 my @tokens = split( /\s+/, $str );
173 push( @readings, map { { 'type' => 'token', 'content' => $_ } } @tokens );
174 } elsif( $xn->nodeName eq 'app' ) {
175 # Apparatus, just save the entire XML node.
176 push( @readings, { 'type' => 'app', 'content' => $xn } );
177 } elsif( $xn->nodeName eq 'anchor' ) {
178 # Anchor to mark the end of some apparatus; save its ID.
179 push( @readings, { 'type' => 'anchor',
180 'content' => $xn->getAttribute( 'xml:id' ) } );
181 } elsif ( $xn->nodeName ne 'note' ) { # Any tag we don't know to disregard
182 print STDERR "Unrecognized tag " . $xn->nodeName . "\n";
188 my( $list, @tokens ) = @_;
189 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
190 # The list evidently ended mid-word; join the next token onto it.
191 my $t = shift @tokens;
192 if( ref $t && $t->{'type'} eq 'token' ) {
194 $t = $t->{'content'};
196 # An app or anchor intervened; end the word.
197 unshift( @tokens, $t );
200 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
202 foreach my $t ( @tokens ) {
203 unless( ref( $t ) ) {
204 $t = { 'type' => 'token', 'content' => $t };
211 my( $c, $app_id ) = @_;
212 my $xn = $apps{$app_id};
213 my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
214 # Get the lemma, which is all the readings between app and anchor,
215 # excluding other apps or anchors.
216 my @lemma = _return_lemma( $c, $app_id, $anchor );
217 my $lemma_str = join( ' ', grep { $_ !~ /^__/ } map { $_->text } @lemma );
219 # For each reading, send its text to 'interpret' along with the lemma,
220 # and then save the list of witnesses that these tokens belong to.
221 my %wit_rdgs; # Maps from witnesses to the variant text
224 $tag =~ s/^\__APP_(.*)\__$/$1/;
226 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
228 foreach ( $rdg->childNodes ) {
229 push( @text, _get_base( $_ ) );
231 my( $interpreted, $flag ) = ( '', undef );
233 ( $interpreted, $flag ) = interpret(
234 join( ' ', map { $_->{'content'} } @text ), $lemma_str );
236 next if( $interpreted eq $lemma_str ) && !$flag; # Reading is lemma.
239 if( $interpreted eq '#LACUNA#' ) {
240 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
241 is_lacuna => 1 } ) );
243 foreach my $w ( split( /\s+/, $interpreted ) ) {
244 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
246 push( @rdg_nodes, $r );
249 # For each listed wit, save the reading.
250 foreach my $wit ( split( /\s+/, $rdg->getAttribute( 'wit' ) ) ) {
251 $wit .= $flag if $flag;
252 $wit_rdgs{$wit} = \@rdg_nodes;
255 # Does the reading have an ID? If so it probably has a witDetail
256 # attached, and we need to read it.
257 if( $rdg->hasAttribute( 'xml:id' ) ) {
258 warn "Witdetail on meta reading" if $flag; # this could get complicated.
259 my $rid = $rdg->getAttribute( 'xml:id' );
260 my $xpc = XML::LibXML::XPathContext->new( $xn );
261 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
262 foreach my $d ( @details ) {
263 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
268 # Now collate the variant readings, since it is not done for us.
269 collate_variants( $c, \@lemma, values %wit_rdgs );
271 # Now add the witness paths for each reading.
272 foreach my $wit_id ( keys %wit_rdgs ) {
273 my $witstr = get_sigil( $wit_id, $c );
274 my $rdg_list = $wit_rdgs{$wit_id};
275 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
282 return sprintf( "__ANCHOR_%s__", $xmlid );
286 my( $c, $app, $anchor ) = @_;
287 my @nodes = grep { $_->id !~ /^__A(PP|NCHOR)/ }
288 $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
294 # A utility function to change apparatus-ese into a full variant.
295 my( $reading, $lemma ) = @_;
296 return $reading if $reading eq $lemma;
297 my $oldreading = $reading;
298 # $lemma =~ s/\s+[[:punct:]]+$//;
299 my $flag; # In case of p.c. indications
300 my @words = split( /\s+/, $lemma );
301 if( $reading =~ /^(.*) praem.$/ ) {
302 $reading = "$1 $lemma";
303 } elsif( $reading =~ /^(.*) add.$/ ) {
304 $reading = "$lemma $1";
305 } elsif( $reading =~ /add. alia manu/
306 || $reading =~ /inscriptionem compegi e/ # TODO huh?
307 || $reading eq 'inc.' # TODO huh?
311 } elsif( $reading =~ /locus [uv]acuus/
312 || $reading eq 'def.'
313 || $reading eq 'illeg.'
314 || $reading eq 'onleesbar'
316 $reading = '#LACUNA#';
317 } elsif( $reading eq 'om.' ) {
319 } elsif( $reading =~ /^in[uv]\.$/
320 || $reading eq 'transp.' ) {
321 # Hope it is two words.
322 print STDERR "WARNING: want to invert a lemma that is not two words\n"
323 unless scalar( @words ) == 2;
324 $reading = join( ' ', reverse( @words ) );
325 } elsif( $reading =~ /^iter(\.|at)$/ ) {
327 $reading = "$lemma $lemma";
328 } elsif( $reading eq 'in marg.' ) {
329 # There was nothing before a correction.
332 } elsif( $reading =~ /^(.*?)\s*\(?sic([\s\w.]+)?\)?$/ ) {
333 # Discard any 'sic' notation; indeed, indeed.
335 } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
336 # The first and last N words captured should replace the first and
337 # last N words of the lemma.
338 my @begin = split( /\s+/, $1 );
339 my @end = split( /\s+/, $2 );
340 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
341 # Something is wrong and we can't do the splice.
342 print STDERR "ERROR: $lemma is too short to accommodate $oldreading\n";
344 splice( @words, 0, scalar @begin, @begin );
345 splice( @words, -(scalar @end), scalar @end, @end );
346 $reading = join( ' ', @words );
349 if( $oldreading ne $reading || $flag || $oldreading =~ /\./ ) {
351 $int .= " ($flag)" if $flag;
352 print STDERR "Interpreted $oldreading as $int given $lemma\n";
354 return( $reading, $flag );
357 sub _parse_wit_detail {
358 my( $detail, $readings, $lemma ) = @_;
359 my $wit = $detail->getAttribute( 'wit' );
360 my $content = $detail->textContent;
361 if( $content =~ /a\.\s*c\./ ) {
362 # Replace the key in the $readings hash
363 my $rdg = delete $readings->{$wit};
364 $readings->{$wit.'_ac'} = $rdg;
365 $has_ac{$sigil_for{$wit}} = 1;
366 } elsif( $content =~ /p\.\s*c\./ ) {
367 # If no key for the wit a.c. exists, add one pointing to the lemma
368 unless( exists $readings->{$wit.'_ac'} ) {
369 $readings->{$wit.'_ac'} = $lemma;
371 $has_ac{$sigil_for{$wit}} = 1;
372 } # else don't bother just yet
376 my( $xml_id, $c ) = @_;
377 if( $xml_id =~ /^(.*)_ac$/ ) {
379 return $sigil_for{$real_id} . $c->ac_label;
381 return $sigil_for{$xml_id};
385 sub expand_all_paths {
388 # Walk the collation and fish out the paths for each witness
389 foreach my $wit ( $c->tradition->witnesses ) {
390 my $sig = $wit->sigil;
391 my @path = grep { !$_->is_ph }
392 $c->reading_sequence( $c->start, $c->end, $sig );
393 $wit->path( \@path );
394 if( $has_ac{$sig} ) {
395 my @ac_path = grep { !$_->is_ph }
396 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
397 $wit->uncorrected_path( \@ac_path );
402 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
403 $c->del_reading( $anchor );
405 # Delete the base edges
406 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
408 # Make the path edges
409 $c->make_witness_paths();
413 my( $c, $rdg, $app, $anchor, $wit ) = @_;
415 push( @nodes, $c->reading( $anchor ) );
417 my $cur = $c->reading( $app );
418 foreach my $n ( @nodes ) {
419 $c->add_path( $cur, $n, $wit );
425 Text::Tradition::Error->throw(
426 'ident' => 'Parser::CTE error',
435 This package is free software and is provided "as is" without express
436 or implied warranty. You can redistribute it and/or modify it under
437 the same terms as Perl itself.
441 Tara L Andrews, aurum@cpan.org