CTE parser work in progress, debugging mostly
[scpubgit/stemmatology.git] / base / lib / Text / Tradition / Parser / CTE.pm
CommitLineData
6f4946fb 1package Text::Tradition::Parser::CTE;
2
3use strict;
4use warnings;
a188b944 5use feature 'say';
c9158e60 6use Encode qw/ decode /;
00311328 7use Text::Tradition::Error;
4d85a60e 8use Text::Tradition::Parser::Util qw/ collate_variants /;
6f4946fb 9use XML::LibXML;
10use XML::LibXML::XPathContext;
f60f9e0f 11use TryCatch;
6f4946fb 12
13=head1 NAME
14
15Text::Tradition::Parser::CTE
16
17=head1 DESCRIPTION
18
19Parser module for Text::Tradition, given a TEI file exported from
20Classical Text Editor.
21
22=head1 METHODS
23
a445ce40 24=head2 parse
6f4946fb 25
26my @apparatus = read( $xml_file );
27
28Takes a Tradition object and a TEI file exported from Classical Text
4d85a60e 29Editor using double-endpoint-attachment critical apparatus encoding;
30initializes the Tradition from the file.
6f4946fb 31
32=cut
33
4d85a60e 34my %sigil_for; # Save the XML IDs for witnesses.
35my %apps; # Save the apparatus XML for a given ID.
f6e19c7c 36my %has_ac; # Keep track of witnesses that have corrections.
6f4946fb 37
38sub parse {
dfc37e38 39 my( $tradition, $opts ) = @_;
4d85a60e 40 my $c = $tradition->collation; # Some shorthand
41
e9442e1c 42 ## DEBUG/TEST
43 $opts->{interpret_transposition} = 1;
44
4d85a60e 45 # First, parse the XML.
c9158e60 46 my( $tei, $xpc ) = _remove_formatting( $opts );
47 return unless $tei; # we have already warned.
4d85a60e 48
49 # CTE uses a DTD rather than any xmlns-based parsing. Thus we
50 # need no namespace handling.
4d85a60e 51 # Get the witnesses and create the witness objects.
52 foreach my $wit_el ( $xpc->findnodes( '//sourceDesc/listWit/witness' ) ) {
53 # The witness xml:id is used internally, and is *not* the sigil name.
54 my $id= $wit_el->getAttribute( 'xml:id' );
92de40a6 55 # If the witness element has an abbr element, that is the sigil. Otherwise
56 # the whole thing is the sigil.
57 my $sig = $xpc->findvalue( 'abbr', $wit_el );
58 my $identifier = 'CTE witness';
59 if( $sig ) {
60 # The sigil is what is in the <abbr/> tag; the identifier is anything
61 # that follows.
62 $identifier = _tidy_identifier(
63 $xpc->findvalue( 'child::text()', $wit_el ) );
64 } else {
65 my @sig_parts = $xpc->findnodes( 'descendant::text()', $wit_el );
66 $sig = _stringify_sigil( @sig_parts );
67 }
68 say STDERR "Adding witness $sig ($identifier)";
69 $tradition->add_witness( sigil => $sig, identifier => $identifier,
70 sourcetype => 'collation' );
b8f262e8 71 $sigil_for{'#'.$id} = $sig; # Make life easy by keying on the ID ref syntax
4d85a60e 72 }
c9158e60 73
4d85a60e 74 # Now go through the text and find the base tokens, apparatus tags, and
75 # anchors. Make a giant array of all of these things in sequence.
76 # TODO consider combining this with creation of graph below
77 my @base_text;
78 foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
79 foreach my $xn ( $pg_el->childNodes ) {
82a45078 80 push( @base_text, _get_base( $xn ) );
4d85a60e 81 }
6f4946fb 82 }
4d85a60e 83 # We now have to work through this array applying the alternate
84 # apparatus readings to the base text. Essentially we will put
85 # everything on the graph, from which we will delete the apps and
86 # anchors when we are done.
f6e19c7c 87
9e0a9786 88 # First, put the base tokens, apps, and anchors in the graph. Save the
89 # app siglorum separately as it has to be processed in order.
90 my @app_sig;
876c951d 91 my @app_crit;
4d85a60e 92 my $counter = 0;
93 my $last = $c->start;
94 foreach my $item ( @base_text ) {
95 my $r;
96 if( $item->{'type'} eq 'token' ) {
12720144 97 $r = $c->add_reading( { id => 'n'.$counter++,
98 text => $item->{'content'} } );
4d85a60e 99 } elsif ( $item->{'type'} eq 'anchor' ) {
10e4b1ac 100 $r = $c->add_reading( { id => '__ANCHOR_' . $item->{'content'} . '__',
12720144 101 is_ph => 1 } );
4d85a60e 102 } elsif ( $item->{'type'} eq 'app' ) {
10e4b1ac 103 my $tag = '__APP_' . $counter++ . '__';
12720144 104 $r = $c->add_reading( { id => $tag, is_ph => 1 } );
f60f9e0f 105 my $app = $item->{'content'};
876c951d 106 $apps{$tag} = $app;
f60f9e0f 107 # Apparatus should be differentiable by type attribute; apparently
108 # it is not. Peek at the content to categorize it.
9e0a9786 109 # Apparatus criticus is type a1; app siglorum is type a2
f60f9e0f 110 my @sigtags = $xpc->findnodes( 'descendant::*[name(witStart) or name(witEnd)]', $app );
111 if( @sigtags ) {
876c951d 112 push( @app_sig, $tag );
9e0a9786 113 } else {
876c951d 114 push( @app_crit, $tag );
9e0a9786 115 }
4d85a60e 116 }
f6e19c7c 117 $c->add_path( $last, $r, $c->baselabel );
4d85a60e 118 $last = $r;
6f4946fb 119 }
f6e19c7c 120 $c->add_path( $last, $c->end, $c->baselabel );
4d85a60e 121
122 # Now we can parse the apparatus entries, and add the variant readings
123 # to the graph.
876c951d 124 foreach my $app_id ( @app_crit ) {
e9442e1c 125 _add_readings( $c, $app_id, $opts );
6f4946fb 126 }
9e0a9786 127 _add_lacunae( $c, @app_sig );
4d85a60e 128
f6e19c7c 129 # Finally, add explicit witness paths, remove the base paths, and remove
130 # the app/anchor tags.
dead25ca 131 try {
132 _expand_all_paths( $c );
f60f9e0f 133 } catch( Text::Tradition::Error $e ) {
134 throw( $e->message );
135 } catch {
136 throw( $@ );
dead25ca 137 }
861c3e27 138
139 # Save the text for each witness so that we can ensure consistency
140 # later on
a188b944 141 unless( $opts->{'nocalc'} ) {
dead25ca 142 try {
143 $tradition->collation->text_from_paths();
144 $tradition->collation->calculate_ranks();
145 $tradition->collation->flatten_ranks();
f60f9e0f 146 } catch( Text::Tradition::Error $e ) {
147 throw( $e->message );
148 } catch {
149 throw( $@ );
dead25ca 150 }
a188b944 151 }
6f4946fb 152}
153
4d85a60e 154sub _stringify_sigil {
155 my( @nodes ) = @_;
156 my @parts = grep { /\w/ } map { $_->data } @nodes;
222d58f1 157 my $whole = join( '', @parts );
158 $whole =~ s/\W//g;
159 return $whole;
4d85a60e 160}
6f4946fb 161
92de40a6 162sub _tidy_identifier {
163 my( $str ) = @_;
164 $str =~ s/^\W+//;
165 return $str;
166}
167
c9158e60 168# Get rid of all the formatting elements that get in the way of tokenization.
169sub _remove_formatting {
170 my( $opts ) = @_;
171
172 # First, parse the original XML
173 my $parser = XML::LibXML->new();
174 my $doc;
175 if( exists $opts->{'string'} ) {
176 $doc = $parser->parse_string( $opts->{'string'} );
177 } elsif ( exists $opts->{'file'} ) {
178 $doc = $parser->parse_file( $opts->{'file'} );
dead25ca 179 } elsif ( exists $opts->{'xmlobj'} ) {
180 $doc = $opts->{'xmlobj'};
c9158e60 181 } else {
182 warn "Could not find string or file option to parse";
183 return;
184 }
00311328 185
c9158e60 186 # Second, remove the formatting
187 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
188 my @useless = $xpc->findnodes( '//hi' );
189 foreach my $n ( @useless ) {
190 my $parent = $n->parentNode();
191 my @children = $n->childNodes();
192 my $first = shift @children;
7c2ed85e 193 if( $first ) {
194 $parent->replaceChild( $first, $n );
195 foreach my $c ( @children ) {
196 $parent->insertAfter( $c, $first );
197 $first = $c;
198 }
199 } else {
200 $parent->removeChild( $n );
c9158e60 201 }
202 }
203
204 # Third, write out and reparse to merge the text nodes.
00311328 205 my $enc = $doc->encoding || 'UTF-8';
206 my $result = decode( $enc, $doc->toString() );
c9158e60 207 my $tei = $parser->parse_string( $result )->documentElement;
00311328 208 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
209 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
210 }
c9158e60 211 $xpc = XML::LibXML::XPathContext->new( $tei );
212 return( $tei, $xpc );
213}
214
215## Helper function to help us navigate through nested XML, picking out
216## the words, the apparatus, and the anchors.
4d85a60e 217
218sub _get_base {
219 my( $xn ) = @_;
220 my @readings;
221 if( $xn->nodeType == XML_TEXT_NODE ) {
222 # Base text, just split the words on whitespace and add them
223 # to our sequence.
224 my $str = $xn->data;
225 $str =~ s/^\s+//;
c9158e60 226 my @tokens = split( /\s+/, $str );
92de40a6 227 push( @readings, map { { type => 'token', content => $_ } } @tokens );
4d85a60e 228 } elsif( $xn->nodeName eq 'app' ) {
229 # Apparatus, just save the entire XML node.
92de40a6 230 push( @readings, { type => 'app', content => $xn } );
4d85a60e 231 } elsif( $xn->nodeName eq 'anchor' ) {
232 # Anchor to mark the end of some apparatus; save its ID.
82a45078 233 if( $xn->hasAttribute('xml:id') ) {
92de40a6 234 push( @readings, { type => 'anchor',
235 content => $xn->getAttribute( 'xml:id' ) } );
82a45078 236 } # if the anchor has no XML ID, it is not relevant to us.
92de40a6 237 } elsif( $xn->nodeName !~ /^(note|seg|milestone|emph)$/ ) { # Any tag we don't know to disregard
a188b944 238 say STDERR "Unrecognized tag " . $xn->nodeName;
6f4946fb 239 }
4d85a60e 240 return @readings;
6f4946fb 241}
242
c9158e60 243sub _append_tokens {
244 my( $list, @tokens ) = @_;
245 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
246 # The list evidently ended mid-word; join the next token onto it.
247 my $t = shift @tokens;
248 if( ref $t && $t->{'type'} eq 'token' ) {
249 # Join the word
250 $t = $t->{'content'};
251 } elsif( ref $t ) {
252 # An app or anchor intervened; end the word.
253 unshift( @tokens, $t );
254 $t = '';
255 }
256 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
257 }
258 foreach my $t ( @tokens ) {
259 unless( ref( $t ) ) {
260 $t = { 'type' => 'token', 'content' => $t };
261 }
262 push( @$list, $t );
263 }
264}
265
4d85a60e 266sub _add_readings {
e9442e1c 267 my( $c, $app_id, $opts ) = @_;
4d85a60e 268 my $xn = $apps{$app_id};
9e0a9786 269 my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
92de40a6 270
4d85a60e 271 # Get the lemma, which is all the readings between app and anchor,
272 # excluding other apps or anchors.
9e0a9786 273 my @lemma = _return_lemma( $c, $app_id, $anchor );
274 my $lemma_str = join( ' ', map { $_->text } grep { !$_->is_ph } @lemma );
92de40a6 275
4d85a60e 276 # For each reading, send its text to 'interpret' along with the lemma,
277 # and then save the list of witnesses that these tokens belong to.
3a5d151b 278 my %wit_rdgs; # Maps from witnesses to the variant text
4d85a60e 279 my $ctr = 0;
280 my $tag = $app_id;
10e4b1ac 281 $tag =~ s/^\__APP_(.*)\__$/$1/;
c9158e60 282
4d85a60e 283 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
e9442e1c 284 my @witlist = split( /\s+/, $rdg->getAttribute( 'wit' ) );
4d85a60e 285 my @text;
4d85a60e 286 foreach ( $rdg->childNodes ) {
287 push( @text, _get_base( $_ ) );
288 }
12720144 289 my( $interpreted, $flag ) = ( '', undef );
290 if( @text ) {
291 ( $interpreted, $flag ) = interpret(
e9442e1c 292 join( ' ', map { $_->{'content'} } @text ), $lemma_str, $anchor, $opts );
12720144 293 }
e9442e1c 294 next if( $interpreted eq $lemma_str ) && !keys %$flag; # Reading is lemma.
b8f262e8 295
4d85a60e 296 my @rdg_nodes;
b8f262e8 297 if( $interpreted eq '#LACUNA#' ) {
10e4b1ac 298 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
b8f262e8 299 is_lacuna => 1 } ) );
e9442e1c 300 } elsif( $flag->{'TR'} ) {
301 # Our reading is transposed to after the given string. Look
302 # down the collation base text and try to find it.
303 # The @rdg_nodes should remain blank here, so that the correct
304 # omission goes into the graph.
f9ffe014 305 my @transp_nodes;
e9442e1c 306 foreach my $w ( split( /\s+/, $interpreted ) ) {
307 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
308 text => $w } );
309 push( @transp_nodes, $r );
310 }
311 if( $anchor && @lemma ) {
f9ffe014 312 my $success = _attach_transposition( $c, \@lemma, $anchor,
313 \@transp_nodes, \@witlist, $flag->{'TR'} );
314 unless( $success ) {
315 # If we didn't manage to insert the displaced reading,
316 # then restore it here rather than silently deleting it.
317 push( @rdg_nodes, @transp_nodes );
318 }
e9442e1c 319 }
b8f262e8 320 } else {
321 foreach my $w ( split( /\s+/, $interpreted ) ) {
10e4b1ac 322 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
b8f262e8 323 text => $w } );
324 push( @rdg_nodes, $r );
325 }
4d85a60e 326 }
92de40a6 327
f6e19c7c 328 # For each listed wit, save the reading.
a5978ac8 329 # If an A.C. or P.C. reading is implied rather than explicitly noted,
330 # this is where it will be dealt with.
e9442e1c 331 foreach my $wit ( @witlist ) {
332 $wit .= '_ac' if $flag->{'AC'};
f6e19c7c 333 $wit_rdgs{$wit} = \@rdg_nodes;
a5978ac8 334 # If the PC flag is set, there is a corresponding AC that
335 # follows the lemma and has to be explicitly declared.
336 if( $flag->{'PC'} ) {
337 $wit_rdgs{$wit.'_ac'} = \@lemma;
338 }
f6e19c7c 339 }
12720144 340
3a5d151b 341 # Does the reading have an ID? If so it probably has a witDetail
a5978ac8 342 # attached, and we need to read it. If an A.C. or P.C. reading is
343 # declared explicity, this is where it will be dealt with.
3a5d151b 344 if( $rdg->hasAttribute( 'xml:id' ) ) {
12720144 345 warn "Witdetail on meta reading" if $flag; # this could get complicated.
f6e19c7c 346 my $rid = $rdg->getAttribute( 'xml:id' );
347 my $xpc = XML::LibXML::XPathContext->new( $xn );
348 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
349 foreach my $d ( @details ) {
350 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
351 }
3a5d151b 352 }
f6e19c7c 353 }
354
4d85a60e 355 # Now collate the variant readings, since it is not done for us.
12720144 356 collate_variants( $c, \@lemma, values %wit_rdgs );
b8f262e8 357
92de40a6 358 # Now add the witness paths for each reading. If we don't have an anchor
359 # (e.g. with an initial witStart) there was no witness path to speak of.
9e0a9786 360 foreach my $wit_id ( keys %wit_rdgs ) {
361 my $witstr = _get_sigil( $wit_id, $c->ac_label );
362 my $rdg_list = $wit_rdgs{$wit_id};
363 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
92de40a6 364 }
4d85a60e 365}
6f4946fb 366
4d85a60e 367sub _anchor_name {
368 my $xmlid = shift;
369 $xmlid =~ s/^\#//;
10e4b1ac 370 return sprintf( "__ANCHOR_%s__", $xmlid );
6f4946fb 371}
372
4d85a60e 373sub _return_lemma {
374 my( $c, $app, $anchor ) = @_;
10e4b1ac 375 my @nodes = grep { $_->id !~ /^__A(PP|NCHOR)/ }
12720144 376 $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
377 $c->baselabel );
4d85a60e 378 return @nodes;
379}
6f4946fb 380
e9442e1c 381# Make a best-effort attempt to attach a transposition farther down the line.
382# $lemmaseq contains the Reading objects of the lemma
383# $anchor contains the point at which we should start scanning for a match
384# $rdgseq contains the Reading objects of the transposed reading
385# (should be identical to the lemma)
386# $witlist contains the list of applicable witnesses
387# $reftxt contains the text to match, after which the $rdgseq should go.
388sub _attach_transposition {
389 my( $c, $lemmaseq, $anchor, $rdgseq, $witlist, $reftxt ) = @_;
390 my @refwords = split( /\s+/, $reftxt );
391 my $checked = $c->reading( $anchor );
392 my $found;
f9ffe014 393 my $success;
e9442e1c 394 while( $checked ne $c->end && !$found ) {
395 my $next = $c->next_reading( $checked, $c->baselabel );
396 if( $next->text eq $refwords[0] ) {
397 # See if the entire sequence of words matches.
398 $found = $next;
399 foreach my $w ( 1..$#refwords ) {
400 $found = $c->next_reading( $next, $c->baselabel );
401 unless( $found->text eq $refwords[$w] ) {
402 $found = undef;
403 last;
404 }
405 }
406 }
407 $checked = $next;
408 }
409 if( $found ) {
410 # The $found variable should now contain the reading after which we
411 # should stick the transposition.
412 my $fnext = $c->next_reading( $found, $c->baselabel );
413 my $aclabel = $c->ac_label;
414 foreach my $wit_id ( @$witlist ) {
415 my $witstr = _get_sigil( $wit_id, $aclabel );
416 _add_wit_path( $c, $rdgseq, $found->id, $fnext->id, $witstr );
417 }
418 # ...and add the transposition relationship between lemma and rdgseq.
419 if( @$lemmaseq == @$rdgseq ) {
420 foreach my $i ( 0..$#{$lemmaseq} ) {
421 $c->add_relationship( $lemmaseq->[$i], $rdgseq->[$i],
422 { type => 'transposition', annotation => 'Detected by CTE' } );
423 }
f9ffe014 424 $success = 1;
e9442e1c 425 } else {
dead25ca 426 throw( "Lemma at $found and transposed sequence different lengths?!" );
e9442e1c 427 }
428 } else {
429 say STDERR "WARNING: Unable to find $reftxt in base text for transposition";
e9442e1c 430 }
f9ffe014 431 return $success;
e9442e1c 432}
433
a445ce40 434=head2 interpret( $reading, $lemma )
435
436Given a string in $reading and a corresponding lemma in $lemma, interpret what
437the actual reading should be. Used to deal with apparatus-ese shorthands for
438marking transpositions, prefixed or suffixed words, and the like.
439
440=cut
441
6f4946fb 442sub interpret {
4d85a60e 443 # A utility function to change apparatus-ese into a full variant.
e9442e1c 444 my( $reading, $lemma, $anchor, $opts ) = @_;
4d85a60e 445 return $reading if $reading eq $lemma;
446 my $oldreading = $reading;
447 # $lemma =~ s/\s+[[:punct:]]+$//;
e9442e1c 448 my $flag = {}; # To pass back extra info about the interpretation
4d85a60e 449 my @words = split( /\s+/, $lemma );
f9ffe014 450 # Discard any 'sic' notation - that rather goes without saying.
a5978ac8 451 $reading =~ s/([[:punct:]]+)?sic([[:punct:]]+)?//g;
f9ffe014 452
453 # Now look for common jargon.
454 if( $reading =~ /^(.*) praem.$/ || $reading =~ /^praem\. (.*)$/ ) {
4d85a60e 455 $reading = "$1 $lemma";
f9ffe014 456 } elsif( $reading =~ /^(.*) add.$/ || $reading =~ /^add\. (.*)$/ ) {
4d85a60e 457 $reading = "$lemma $1";
b8f262e8 458 } elsif( $reading =~ /locus [uv]acuus/
459 || $reading eq 'def.'
c9158e60 460 || $reading eq 'illeg.'
a5978ac8 461 || $reading eq 'desunt'
f6e19c7c 462 ) {
b8f262e8 463 $reading = '#LACUNA#';
464 } elsif( $reading eq 'om.' ) {
4d85a60e 465 $reading = '';
c9158e60 466 } elsif( $reading =~ /^in[uv]\.$/
a5978ac8 467 || $reading =~ /^tr(ans(p)?)?\.$/ ) {
4d85a60e 468 # Hope it is two words.
a188b944 469 say STDERR "WARNING: want to invert a lemma that is not two words"
4d85a60e 470 unless scalar( @words ) == 2;
471 $reading = join( ' ', reverse( @words ) );
12720144 472 } elsif( $reading =~ /^iter(\.|at)$/ ) {
4d85a60e 473 # Repeat the lemma
474 $reading = "$lemma $lemma";
a5978ac8 475 } elsif( $reading =~ /^(.*?)\s*\(?in marg\.\)?$/ ) {
476 $reading = $1;
477 if( $reading ) {
478 # The given text is a correction.
479 $flag->{'PC'} = 1;
480 } else {
481 # The lemma itself was the correction; the witness carried
482 # no reading pre-correction.
483 $flag->{'AC'} = 1;
484 }
12720144 485 } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
4d85a60e 486 # The first and last N words captured should replace the first and
487 # last N words of the lemma.
488 my @begin = split( /\s+/, $1 );
489 my @end = split( /\s+/, $2 );
490 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
491 # Something is wrong and we can't do the splice.
dead25ca 492 throw( "$lemma is too short to accommodate $oldreading" );
4d85a60e 493 } else {
494 splice( @words, 0, scalar @begin, @begin );
495 splice( @words, -(scalar @end), scalar @end, @end );
496 $reading = join( ' ', @words );
497 }
e9442e1c 498 } elsif( $opts->{interpret_transposition} &&
a5978ac8 499 ( $reading =~ /^post\s*(?<lem>.*?)\s+tr(ans(p)?)?\.$/ ||
500 $reading =~ /^tr(ans(p)?)?\. post\s*(?<lem>.*)$/) ) {
e9442e1c 501 # Try to deal with transposed readings
502 ## DEBUG
503 say STDERR "Will attempt transposition: $reading at $anchor";
504 $reading = $lemma;
a5978ac8 505 $flag->{'TR'} = $+{lem};
12720144 506 }
507 return( $reading, $flag );
4d85a60e 508}
509
f6e19c7c 510sub _parse_wit_detail {
511 my( $detail, $readings, $lemma ) = @_;
512 my $wit = $detail->getAttribute( 'wit' );
513 my $content = $detail->textContent;
a5978ac8 514 if( $content =~ /^a\.?\s*c(orr)?\.$/ ) {
f6e19c7c 515 # Replace the key in the $readings hash
516 my $rdg = delete $readings->{$wit};
517 $readings->{$wit.'_ac'} = $rdg;
518 $has_ac{$sigil_for{$wit}} = 1;
a5978ac8 519 } elsif( $content =~ /^p\.?\s*c(orr)?\.$/ || $content =~ /^s\.?\s*l\.$/ ) {
f6e19c7c 520 # If no key for the wit a.c. exists, add one pointing to the lemma
521 unless( exists $readings->{$wit.'_ac'} ) {
522 $readings->{$wit.'_ac'} = $lemma;
523 }
524 $has_ac{$sigil_for{$wit}} = 1;
a5978ac8 525 } else { #...not sure what it is?
876c951d 526 say STDERR "WARNING: Unrecognized sigil annotation $content";
a5978ac8 527 }
f6e19c7c 528}
529
9e0a9786 530sub _add_lacunae {
876c951d 531 my( $c, @app_id ) = @_;
9e0a9786 532 # Go through the apparatus entries in order, noting where to start and stop our
533 # various witnesses.
534 my %lacunose;
535 my $ctr = 0;
876c951d 536 foreach my $tag ( @app_id ) {
537 my $app = $apps{$tag};
9e0a9786 538 # Find the anchor, if any. This marks the point where the text starts
539 # or ends.
540 my $anchor = $app->getAttribute( 'to' );
541 my $aname;
542 if( $anchor ) {
c8010abf 543 $anchor =~ s/^\#//;
9e0a9786 544 $aname = _anchor_name( $anchor );
545 }
546
547 foreach my $rdg ( $app->getChildrenByTagName( 'rdg' ) ) {
548 my @witlist = map { _get_sigil( $_, $c->ac_label ) }
549 split( /\s+/, $rdg->getAttribute( 'wit' ) );
550 my @start = $rdg->getChildrenByTagName( 'witStart' );
551 my @end = $rdg->getChildrenByTagName( 'witEnd' );
552 if( @start && @end ) {
553 throw( "App sig entry at $anchor has both witStart and witEnd!" );
554 }
555 if( @start && $anchor &&
556 $c->prior_reading( $aname, $c->baselabel ) ne $c->start ) {
557 # We are picking back up after a hiatus. Find the last end and
558 # add a lacuna link between there and here.
559 foreach my $wit ( @witlist ) {
560 my $stoppoint = delete $lacunose{$wit};
f60f9e0f 561 my $stopname = $stoppoint ? _anchor_name( $stoppoint ) : $c->start->id;
562 say STDERR "Adding lacuna for $wit between $stopname and $anchor";
9e0a9786 563 my $lacuna = $c->add_reading( { id => "as_$anchor.".$ctr++,
564 is_lacuna => 1 } );
565 _add_wit_path( $c, [ $lacuna ], $stopname, $aname, $wit );
566 }
567 } elsif( @end && $anchor &&
568 $c->next_reading( $aname, $c->baselabel ) ne $c->end ) {
569 # We are stopping. If we've already stopped for the given witness,
570 # flag an error; otherwise record the stopping point.
571 foreach my $wit ( @witlist ) {
572 if( $lacunose{$wit} ) {
573 throw( "Trying to end $wit at $anchor when already ended at "
574 . $lacunose{$wit} );
575 }
576 $lacunose{$wit} = $anchor;
577 }
578 }
579 }
580 }
581
582 # For whatever remains in the %lacunose hash, add a lacuna between that spot and
583 # $c->end for each of the witnesses.
584 foreach my $wit ( keys %lacunose ) {
585 next unless $lacunose{$wit};
586 my $aname = _anchor_name( $lacunose{$wit} );
587 say STDERR "Adding lacuna for $wit from $aname to end";
588 my $lacuna = $c->add_reading( { id => 'as_'.$lacunose{$wit}.'.'.$ctr++,
589 is_lacuna => 1 } );
590 _add_wit_path( $c, [ $lacuna ], $aname, $c->end, $wit );
591 }
592}
593
a445ce40 594sub _get_sigil {
595 my( $xml_id, $layerlabel ) = @_;
f6e19c7c 596 if( $xml_id =~ /^(.*)_ac$/ ) {
597 my $real_id = $1;
a445ce40 598 return $sigil_for{$real_id} . $layerlabel;
f6e19c7c 599 } else {
600 return $sigil_for{$xml_id};
601 }
602}
603
a445ce40 604sub _expand_all_paths {
f6e19c7c 605 my( $c ) = @_;
606
607 # Walk the collation and fish out the paths for each witness
608 foreach my $wit ( $c->tradition->witnesses ) {
609 my $sig = $wit->sigil;
12720144 610 my @path = grep { !$_->is_ph }
f6e19c7c 611 $c->reading_sequence( $c->start, $c->end, $sig );
612 $wit->path( \@path );
613 if( $has_ac{$sig} ) {
12720144 614 my @ac_path = grep { !$_->is_ph }
861c3e27 615 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
f6e19c7c 616 $wit->uncorrected_path( \@ac_path );
617 }
618 }
619
620 # Delete the anchors
12720144 621 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
f6e19c7c 622 $c->del_reading( $anchor );
623 }
12720144 624 # Delete the base edges
625 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
f6e19c7c 626
627 # Make the path edges
628 $c->make_witness_paths();
7c2ed85e 629
630 # Now remove any orphan nodes, and warn that we are doing so.
876c951d 631 my @suspect_apps;
82a45078 632 while( $c->sequence->predecessorless_vertices > 1 ) {
633 foreach my $v ( $c->sequence->predecessorless_vertices ) {
634 my $r = $c->reading( $v );
635 next if $r->is_start;
876c951d 636 my $tag = $r->id;
637 $tag =~ s/^r(\d+)\.\d+/$1/;
82a45078 638 say STDERR "Deleting orphan reading $r / " . $r->text;
876c951d 639 push( @suspect_apps, $tag );
82a45078 640 $c->del_reading( $r );
641 }
7c2ed85e 642 }
876c951d 643 if( $c->sequence->successorless_vertices > 1 ) {
644 my @bad = grep { $_ ne $c->end->id } $c->sequence->successorless_vertices;
645 foreach( @bad ) {
646 s/^r(\d+)\.\d+/$1/;
647 push( @suspect_apps, $_ );
648 }
649 _dump_suspects( @suspect_apps );
650 throw( "Remaining hanging readings: @bad" );
651 }
652 _dump_suspects( @suspect_apps ) if @suspect_apps;
4d85a60e 653}
654
655sub _add_wit_path {
f6e19c7c 656 my( $c, $rdg, $app, $anchor, $wit ) = @_;
4d85a60e 657 my @nodes = @$rdg;
f6e19c7c 658 push( @nodes, $c->reading( $anchor ) );
4d85a60e 659
f6e19c7c 660 my $cur = $c->reading( $app );
4d85a60e 661 foreach my $n ( @nodes ) {
f6e19c7c 662 $c->add_path( $cur, $n, $wit );
4d85a60e 663 $cur = $n;
6f4946fb 664 }
6f4946fb 665}
666
876c951d 667sub _dump_suspects {
668 say STDERR "Suspect apparatus entries:";
669 foreach my $suspect ( sort { $a <=> $b } @_ ) {
670 say STDERR "---" . print_apparatus( $suspect );
671 }
672}
673
674sub print_apparatus {
675 my( $appid ) = @_;
676 my $tag = '__APP_' . $appid . '__';
677 my $app = $apps{$tag};
678 my $appstring = '';
679 # Interpret the XML - get the lemma and readings and print them out.
680 my $xpc = XML::LibXML::XPathContext->new( $app );
681 my $anchor = $app->getAttribute('to');
682 if( $anchor ) {
683 # We have a lemma, so we construct it.
684 $anchor =~ s/^#//;
685 my $curr = $app;
686 while( $curr ) {
687 last if $curr->nodeType eq XML_ELEMENT_NODE
688 && $curr->hasAttribute( 'xml:id' )
689 && $curr->getAttribute( 'xml:id' ) eq $anchor;
690 $appstring .= $curr->data if $curr->nodeType eq XML_TEXT_NODE;
691 $curr = $curr->nextSibling;
692 }
693 }
694 $appstring .= ': ';
695 foreach my $rdg_el ( $xpc->findnodes( 'child::rdg' ) ) {
696 my $rdgtext = '';
697 my $startend = '';
698 my %detail;
699 foreach my $child_el ( $rdg_el->childNodes ) {
700 if( $child_el->nodeType eq XML_TEXT_NODE ) {
701 $rdgtext .= $child_el->data;
702 } elsif( $child_el->nodeName =~ /^wit(Start|End)$/ ) {
703 my $startend = lc( $1 );
704 } elsif( $child_el->nodeName eq 'witDetail' ) {
705 foreach my $wit ( map { _get_sigil( $_ ) }
706 split( /\s+/, $child_el->getAttribute('wit') ) ) {
707 $detail{$wit} = $child_el->textContent;
708 }
709 }
710 }
711 $appstring .= "$rdgtext ";
712 my @witlist;
713 foreach my $witrep ( map { _get_sigil( $_ ) }
714 split( /\s+/, $rdg_el->getAttribute('wit') ) ) {
715 if( exists $detail{$witrep} ) {
716 $witrep .= '(' . $detail{$witrep} . ')'
717 }
718 if( $startend eq 'start' ) {
719 $witrep = '*' . $witrep;
720 } elsif( $startend eq 'end' ) {
721 $witrep .= '*';
722 }
723 push( @witlist, $witrep );
724 }
725 $appstring .= "@witlist";
726 }
727 return $appstring;
728}
729
00311328 730sub throw {
731 Text::Tradition::Error->throw(
732 'ident' => 'Parser::CTE error',
733 'message' => $_[0],
734 );
735}
736
6f4946fb 737=head1 LICENSE
738
739This package is free software and is provided "as is" without express
740or implied warranty. You can redistribute it and/or modify it under
741the same terms as Perl itself.
742
743=head1 AUTHOR
744
745Tara L Andrews, aurum@cpan.org
746
747=cut
748
7491;
750