1 package Text::Tradition::Parser::CTE;
5 use Encode qw/ decode /;
6 use Text::Tradition::Parser::Util qw/ collate_variants /;
8 use XML::LibXML::XPathContext;
12 Text::Tradition::Parser::CTE
16 Parser module for Text::Tradition, given a TEI file exported from
17 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
41 # First, parse the XML.
42 my( $tei, $xpc ) = _remove_formatting( $opts );
43 return unless $tei; # we have already warned.
45 # CTE uses a DTD rather than any xmlns-based parsing. Thus we
46 # need no namespace handling.
47 # Get the witnesses and create the witness objects.
48 foreach my $wit_el ( $xpc->findnodes( '//sourceDesc/listWit/witness' ) ) {
49 # The witness xml:id is used internally, and is *not* the sigil name.
50 my $id= $wit_el->getAttribute( 'xml:id' );
51 my @sig_parts = $xpc->findnodes( 'descendant::text()', $wit_el );
52 my $sig = _stringify_sigil( @sig_parts );
53 print STDERR "Adding witness $sig\n";
54 $tradition->add_witness( sigil => $sig, sourcetype => 'collation' );
55 $sigil_for{'#'.$id} = $sig; # Make life easy by keying on the ID ref syntax
58 # Now go through the text and find the base tokens, apparatus tags, and
59 # anchors. Make a giant array of all of these things in sequence.
60 # TODO consider combining this with creation of graph below
62 foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
63 foreach my $xn ( $pg_el->childNodes ) {
64 push( @base_text, _get_base( $xn ) );
67 # We now have to work through this array applying the alternate
68 # apparatus readings to the base text. Essentially we will put
69 # everything on the graph, from which we will delete the apps and
70 # anchors when we are done.
72 # First, put the base tokens, apps, and anchors in the graph.
75 foreach my $item ( @base_text ) {
77 if( $item->{'type'} eq 'token' ) {
78 $r = $c->add_reading( { id => 'n'.$counter++,
79 text => $item->{'content'} } );
80 } elsif ( $item->{'type'} eq 'anchor' ) {
81 $r = $c->add_reading( { id => '#ANCHOR_' . $item->{'content'} . '#',
83 } elsif ( $item->{'type'} eq 'app' ) {
84 my $tag = '#APP_' . $counter++ . '#';
85 $r = $c->add_reading( { id => $tag, is_ph => 1 } );
86 $apps{$tag} = $item->{'content'};
88 $c->add_path( $last, $r, $c->baselabel );
91 $c->add_path( $last, $c->end, $c->baselabel );
93 # Now we can parse the apparatus entries, and add the variant readings
96 foreach my $app_id ( keys %apps ) {
97 _add_readings( $c, $app_id );
100 # Finally, add explicit witness paths, remove the base paths, and remove
101 # the app/anchor tags.
102 expand_all_paths( $c );
104 # Save the text for each witness so that we can ensure consistency
106 $tradition->collation->text_from_paths();
107 $tradition->collation->calculate_ranks();
108 $tradition->collation->flatten_ranks();
111 sub _stringify_sigil {
113 my @parts = grep { /\w/ } map { $_->data } @nodes;
114 return join( '', @parts );
117 # Get rid of all the formatting elements that get in the way of tokenization.
118 sub _remove_formatting {
121 # First, parse the original XML
122 my $parser = XML::LibXML->new();
124 if( exists $opts->{'string'} ) {
125 $doc = $parser->parse_string( $opts->{'string'} );
126 } elsif ( exists $opts->{'file'} ) {
127 $doc = $parser->parse_file( $opts->{'file'} );
129 warn "Could not find string or file option to parse";
133 # Second, remove the formatting
134 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
135 my @useless = $xpc->findnodes( '//hi' );
136 foreach my $n ( @useless ) {
137 my $parent = $n->parentNode();
138 my @children = $n->childNodes();
139 my $first = shift @children;
140 $parent->replaceChild( $first, $n );
141 foreach my $c ( @children ) {
142 $parent->insertAfter( $c, $first );
147 # Third, write out and reparse to merge the text nodes.
148 my $result = decode( $doc->encoding, $doc->toString() );
149 my $tei = $parser->parse_string( $result )->documentElement;
150 $xpc = XML::LibXML::XPathContext->new( $tei );
151 return( $tei, $xpc );
154 ## Helper function to help us navigate through nested XML, picking out
155 ## the words, the apparatus, and the anchors.
160 if( $xn->nodeType == XML_TEXT_NODE ) {
161 # Base text, just split the words on whitespace and add them
165 my @tokens = split( /\s+/, $str );
166 push( @readings, map { { 'type' => 'token', 'content' => $_ } } @tokens );
167 } elsif( $xn->nodeName eq 'app' ) {
168 # Apparatus, just save the entire XML node.
169 push( @readings, { 'type' => 'app', 'content' => $xn } );
170 } elsif( $xn->nodeName eq 'anchor' ) {
171 # Anchor to mark the end of some apparatus; save its ID.
172 push( @readings, { 'type' => 'anchor',
173 'content' => $xn->getAttribute( 'xml:id' ) } );
174 } elsif ( $xn->nodeName ne 'note' ) { # Any tag we don't know to disregard
175 print STDERR "Unrecognized tag " . $xn->nodeName . "\n";
181 my( $list, @tokens ) = @_;
182 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
183 # The list evidently ended mid-word; join the next token onto it.
184 my $t = shift @tokens;
185 if( ref $t && $t->{'type'} eq 'token' ) {
187 $t = $t->{'content'};
189 # An app or anchor intervened; end the word.
190 unshift( @tokens, $t );
193 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
195 foreach my $t ( @tokens ) {
196 unless( ref( $t ) ) {
197 $t = { 'type' => 'token', 'content' => $t };
204 my( $c, $app_id ) = @_;
205 my $xn = $apps{$app_id};
206 my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
207 # Get the lemma, which is all the readings between app and anchor,
208 # excluding other apps or anchors.
209 my @lemma = _return_lemma( $c, $app_id, $anchor );
210 my $lemma_str = join( ' ', grep { $_ !~ /^\#/ } map { $_->text } @lemma );
212 # For each reading, send its text to 'interpret' along with the lemma,
213 # and then save the list of witnesses that these tokens belong to.
214 my %wit_rdgs; # Maps from witnesses to the variant text
217 $tag =~ s/^\#APP_(.*)\#$/$1/;
219 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
221 foreach ( $rdg->childNodes ) {
222 push( @text, _get_base( $_ ) );
224 my( $interpreted, $flag ) = ( '', undef );
226 ( $interpreted, $flag ) = interpret(
227 join( ' ', map { $_->{'content'} } @text ), $lemma_str );
229 next if( $interpreted eq $lemma_str ) && !$flag; # Reading is lemma.
232 if( $interpreted eq '#LACUNA#' ) {
233 push( @rdg_nodes, $c->add_reading( { id => $tag . "/" . $ctr++,
234 is_lacuna => 1 } ) );
236 foreach my $w ( split( /\s+/, $interpreted ) ) {
237 my $r = $c->add_reading( { id => $tag . "/" . $ctr++,
239 push( @rdg_nodes, $r );
242 # For each listed wit, save the reading.
243 foreach my $wit ( split( /\s+/, $rdg->getAttribute( 'wit' ) ) ) {
244 $wit .= $flag if $flag;
245 $wit_rdgs{$wit} = \@rdg_nodes;
248 # Does the reading have an ID? If so it probably has a witDetail
249 # attached, and we need to read it.
250 if( $rdg->hasAttribute( 'xml:id' ) ) {
251 warn "Witdetail on meta reading" if $flag; # this could get complicated.
252 my $rid = $rdg->getAttribute( 'xml:id' );
253 my $xpc = XML::LibXML::XPathContext->new( $xn );
254 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
255 foreach my $d ( @details ) {
256 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
261 # Now collate the variant readings, since it is not done for us.
262 collate_variants( $c, \@lemma, values %wit_rdgs );
264 # Now add the witness paths for each reading.
265 foreach my $wit_id ( keys %wit_rdgs ) {
266 my $witstr = get_sigil( $wit_id, $c );
267 my $rdg_list = $wit_rdgs{$wit_id};
268 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
275 return sprintf( "#ANCHOR_%s#", $xmlid );
279 my( $c, $app, $anchor ) = @_;
280 my @nodes = grep { $_->id !~ /^\#A(PP|NCHOR)/ }
281 $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
287 # A utility function to change apparatus-ese into a full variant.
288 my( $reading, $lemma ) = @_;
289 return $reading if $reading eq $lemma;
290 my $oldreading = $reading;
291 # $lemma =~ s/\s+[[:punct:]]+$//;
292 my $flag; # In case of p.c. indications
293 my @words = split( /\s+/, $lemma );
294 if( $reading =~ /^(.*) praem.$/ ) {
295 $reading = "$1 $lemma";
296 } elsif( $reading =~ /^(.*) add.$/ ) {
297 $reading = "$lemma $1";
298 } elsif( $reading =~ /add. alia manu/
299 || $reading =~ /inscriptionem compegi e/ # TODO huh?
300 || $reading eq 'inc.' # TODO huh?
304 } elsif( $reading =~ /locus [uv]acuus/
305 || $reading eq 'def.'
306 || $reading eq 'illeg.'
307 || $reading eq 'onleesbar'
309 $reading = '#LACUNA#';
310 } elsif( $reading eq 'om.' ) {
312 } elsif( $reading =~ /^in[uv]\.$/
313 || $reading eq 'transp.' ) {
314 # Hope it is two words.
315 print STDERR "WARNING: want to invert a lemma that is not two words\n"
316 unless scalar( @words ) == 2;
317 $reading = join( ' ', reverse( @words ) );
318 } elsif( $reading =~ /^iter(\.|at)$/ ) {
320 $reading = "$lemma $lemma";
321 } elsif( $reading eq 'in marg.' ) {
322 # There was nothing before a correction.
325 } elsif( $reading =~ /^(.*?)\s*\(?sic([\s\w.]+)?\)?$/ ) {
326 # Discard any 'sic' notation; indeed, indeed.
328 } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
329 # The first and last N words captured should replace the first and
330 # last N words of the lemma.
331 my @begin = split( /\s+/, $1 );
332 my @end = split( /\s+/, $2 );
333 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
334 # Something is wrong and we can't do the splice.
335 print STDERR "ERROR: $lemma is too short to accommodate $oldreading\n";
337 splice( @words, 0, scalar @begin, @begin );
338 splice( @words, -(scalar @end), scalar @end, @end );
339 $reading = join( ' ', @words );
342 if( $oldreading ne $reading || $flag || $oldreading =~ /\./ ) {
344 $int .= " ($flag)" if $flag;
345 print STDERR "Interpreted $oldreading as $int given $lemma\n";
347 return( $reading, $flag );
350 sub _parse_wit_detail {
351 my( $detail, $readings, $lemma ) = @_;
352 my $wit = $detail->getAttribute( 'wit' );
353 my $content = $detail->textContent;
354 if( $content =~ /a\.\s*c\./ ) {
355 # Replace the key in the $readings hash
356 my $rdg = delete $readings->{$wit};
357 $readings->{$wit.'_ac'} = $rdg;
358 $has_ac{$sigil_for{$wit}} = 1;
359 } elsif( $content =~ /p\.\s*c\./ ) {
360 # If no key for the wit a.c. exists, add one pointing to the lemma
361 unless( exists $readings->{$wit.'_ac'} ) {
362 $readings->{$wit.'_ac'} = $lemma;
364 $has_ac{$sigil_for{$wit}} = 1;
365 } # else don't bother just yet
369 my( $xml_id, $c ) = @_;
370 if( $xml_id =~ /^(.*)_ac$/ ) {
372 return $sigil_for{$real_id} . $c->ac_label;
374 return $sigil_for{$xml_id};
378 sub expand_all_paths {
381 # Walk the collation and fish out the paths for each witness
382 foreach my $wit ( $c->tradition->witnesses ) {
383 my $sig = $wit->sigil;
384 my @path = grep { !$_->is_ph }
385 $c->reading_sequence( $c->start, $c->end, $sig );
386 $wit->path( \@path );
387 if( $has_ac{$sig} ) {
388 my @ac_path = grep { !$_->is_ph }
389 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
390 $wit->uncorrected_path( \@ac_path );
395 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
396 $c->del_reading( $anchor );
398 # Delete the base edges
399 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
401 # Make the path edges
402 $c->make_witness_paths();
406 my( $c, $rdg, $app, $anchor, $wit ) = @_;
408 push( @nodes, $c->reading( $anchor ) );
410 my $cur = $c->reading( $app );
411 foreach my $n ( @nodes ) {
412 $c->add_path( $cur, $n, $wit );
421 This package is free software and is provided "as is" without express
422 or implied warranty. You can redistribute it and/or modify it under
423 the same terms as Perl itself.
427 Tara L Andrews, aurum@cpan.org