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