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