bookkeeping for CPAN release
[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
41 # First, parse the XML.
c9158e60 42 my( $tei, $xpc ) = _remove_formatting( $opts );
43 return unless $tei; # we have already warned.
4d85a60e 44
45 # CTE uses a DTD rather than any xmlns-based parsing. Thus we
46 # need no namespace handling.
4d85a60e 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' );
c9158e60 51 my @sig_parts = $xpc->findnodes( 'descendant::text()', $wit_el );
4d85a60e 52 my $sig = _stringify_sigil( @sig_parts );
a188b944 53 say STDERR "Adding witness $sig";
82fa4d57 54 $tradition->add_witness( sigil => $sig, sourcetype => 'collation' );
b8f262e8 55 $sigil_for{'#'.$id} = $sig; # Make life easy by keying on the ID ref syntax
4d85a60e 56 }
c9158e60 57
4d85a60e 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
61 my @base_text;
62 foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
63 foreach my $xn ( $pg_el->childNodes ) {
82a45078 64 push( @base_text, _get_base( $xn ) );
4d85a60e 65 }
6f4946fb 66 }
4d85a60e 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.
f6e19c7c 71
72 # First, put the base tokens, apps, and anchors in the graph.
4d85a60e 73 my $counter = 0;
74 my $last = $c->start;
75 foreach my $item ( @base_text ) {
76 my $r;
77 if( $item->{'type'} eq 'token' ) {
12720144 78 $r = $c->add_reading( { id => 'n'.$counter++,
79 text => $item->{'content'} } );
4d85a60e 80 } elsif ( $item->{'type'} eq 'anchor' ) {
10e4b1ac 81 $r = $c->add_reading( { id => '__ANCHOR_' . $item->{'content'} . '__',
12720144 82 is_ph => 1 } );
4d85a60e 83 } elsif ( $item->{'type'} eq 'app' ) {
10e4b1ac 84 my $tag = '__APP_' . $counter++ . '__';
12720144 85 $r = $c->add_reading( { id => $tag, is_ph => 1 } );
4d85a60e 86 $apps{$tag} = $item->{'content'};
87 }
f6e19c7c 88 $c->add_path( $last, $r, $c->baselabel );
4d85a60e 89 $last = $r;
6f4946fb 90 }
f6e19c7c 91 $c->add_path( $last, $c->end, $c->baselabel );
4d85a60e 92
93 # Now we can parse the apparatus entries, and add the variant readings
94 # to the graph.
95
96 foreach my $app_id ( keys %apps ) {
97 _add_readings( $c, $app_id );
6f4946fb 98 }
4d85a60e 99
f6e19c7c 100 # Finally, add explicit witness paths, remove the base paths, and remove
101 # the app/anchor tags.
a445ce40 102 _expand_all_paths( $c );
861c3e27 103
104 # Save the text for each witness so that we can ensure consistency
105 # later on
a188b944 106 unless( $opts->{'nocalc'} ) {
107 $tradition->collation->text_from_paths();
108 $tradition->collation->calculate_ranks();
109 $tradition->collation->flatten_ranks();
110 }
6f4946fb 111}
112
4d85a60e 113sub _stringify_sigil {
114 my( @nodes ) = @_;
115 my @parts = grep { /\w/ } map { $_->data } @nodes;
222d58f1 116 my $whole = join( '', @parts );
117 $whole =~ s/\W//g;
118 return $whole;
4d85a60e 119}
6f4946fb 120
c9158e60 121# Get rid of all the formatting elements that get in the way of tokenization.
122sub _remove_formatting {
123 my( $opts ) = @_;
124
125 # First, parse the original XML
126 my $parser = XML::LibXML->new();
127 my $doc;
128 if( exists $opts->{'string'} ) {
129 $doc = $parser->parse_string( $opts->{'string'} );
130 } elsif ( exists $opts->{'file'} ) {
131 $doc = $parser->parse_file( $opts->{'file'} );
132 } else {
133 warn "Could not find string or file option to parse";
134 return;
135 }
00311328 136
c9158e60 137 # Second, remove the formatting
138 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
139 my @useless = $xpc->findnodes( '//hi' );
140 foreach my $n ( @useless ) {
141 my $parent = $n->parentNode();
142 my @children = $n->childNodes();
143 my $first = shift @children;
7c2ed85e 144 if( $first ) {
145 $parent->replaceChild( $first, $n );
146 foreach my $c ( @children ) {
147 $parent->insertAfter( $c, $first );
148 $first = $c;
149 }
150 } else {
151 $parent->removeChild( $n );
c9158e60 152 }
153 }
154
155 # Third, write out and reparse to merge the text nodes.
00311328 156 my $enc = $doc->encoding || 'UTF-8';
157 my $result = decode( $enc, $doc->toString() );
c9158e60 158 my $tei = $parser->parse_string( $result )->documentElement;
00311328 159 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
160 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
161 }
c9158e60 162 $xpc = XML::LibXML::XPathContext->new( $tei );
163 return( $tei, $xpc );
164}
165
166## Helper function to help us navigate through nested XML, picking out
167## the words, the apparatus, and the anchors.
4d85a60e 168
169sub _get_base {
170 my( $xn ) = @_;
171 my @readings;
172 if( $xn->nodeType == XML_TEXT_NODE ) {
173 # Base text, just split the words on whitespace and add them
174 # to our sequence.
175 my $str = $xn->data;
176 $str =~ s/^\s+//;
c9158e60 177 my @tokens = split( /\s+/, $str );
178 push( @readings, map { { 'type' => 'token', 'content' => $_ } } @tokens );
4d85a60e 179 } elsif( $xn->nodeName eq 'app' ) {
180 # Apparatus, just save the entire XML node.
181 push( @readings, { 'type' => 'app', 'content' => $xn } );
182 } elsif( $xn->nodeName eq 'anchor' ) {
183 # Anchor to mark the end of some apparatus; save its ID.
82a45078 184 if( $xn->hasAttribute('xml:id') ) {
a188b944 185 push( @readings, { 'type' => 'anchor',
186 'content' => $xn->getAttribute( 'xml:id' ) } );
82a45078 187 } # if the anchor has no XML ID, it is not relevant to us.
a188b944 188 } elsif ( $xn->nodeName !~ /^(note|seg|milestone|emph)$/ ) { # Any tag we don't know to disregard
189 say STDERR "Unrecognized tag " . $xn->nodeName;
6f4946fb 190 }
4d85a60e 191 return @readings;
6f4946fb 192}
193
c9158e60 194sub _append_tokens {
195 my( $list, @tokens ) = @_;
196 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
197 # The list evidently ended mid-word; join the next token onto it.
198 my $t = shift @tokens;
199 if( ref $t && $t->{'type'} eq 'token' ) {
200 # Join the word
201 $t = $t->{'content'};
202 } elsif( ref $t ) {
203 # An app or anchor intervened; end the word.
204 unshift( @tokens, $t );
205 $t = '';
206 }
207 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
208 }
209 foreach my $t ( @tokens ) {
210 unless( ref( $t ) ) {
211 $t = { 'type' => 'token', 'content' => $t };
212 }
213 push( @$list, $t );
214 }
215}
216
4d85a60e 217sub _add_readings {
218 my( $c, $app_id ) = @_;
219 my $xn = $apps{$app_id};
220 my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
221 # Get the lemma, which is all the readings between app and anchor,
222 # excluding other apps or anchors.
223 my @lemma = _return_lemma( $c, $app_id, $anchor );
82a45078 224 my $lemma_str = join( ' ', map { $_->text } grep { !$_->is_ph } @lemma );
4d85a60e 225
226 # For each reading, send its text to 'interpret' along with the lemma,
227 # and then save the list of witnesses that these tokens belong to.
3a5d151b 228 my %wit_rdgs; # Maps from witnesses to the variant text
4d85a60e 229 my $ctr = 0;
230 my $tag = $app_id;
10e4b1ac 231 $tag =~ s/^\__APP_(.*)\__$/$1/;
c9158e60 232
4d85a60e 233 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
234 my @text;
4d85a60e 235 foreach ( $rdg->childNodes ) {
236 push( @text, _get_base( $_ ) );
237 }
12720144 238 my( $interpreted, $flag ) = ( '', undef );
239 if( @text ) {
240 ( $interpreted, $flag ) = interpret(
241 join( ' ', map { $_->{'content'} } @text ), $lemma_str );
242 }
b8f262e8 243 next if( $interpreted eq $lemma_str ) && !$flag; # Reading is lemma.
244
4d85a60e 245 my @rdg_nodes;
b8f262e8 246 if( $interpreted eq '#LACUNA#' ) {
10e4b1ac 247 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
b8f262e8 248 is_lacuna => 1 } ) );
249 } else {
250 foreach my $w ( split( /\s+/, $interpreted ) ) {
10e4b1ac 251 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
b8f262e8 252 text => $w } );
253 push( @rdg_nodes, $r );
254 }
4d85a60e 255 }
f6e19c7c 256 # For each listed wit, save the reading.
257 foreach my $wit ( split( /\s+/, $rdg->getAttribute( 'wit' ) ) ) {
12720144 258 $wit .= $flag if $flag;
f6e19c7c 259 $wit_rdgs{$wit} = \@rdg_nodes;
260 }
12720144 261
3a5d151b 262 # Does the reading have an ID? If so it probably has a witDetail
f6e19c7c 263 # attached, and we need to read it.
3a5d151b 264 if( $rdg->hasAttribute( 'xml:id' ) ) {
12720144 265 warn "Witdetail on meta reading" if $flag; # this could get complicated.
f6e19c7c 266 my $rid = $rdg->getAttribute( 'xml:id' );
267 my $xpc = XML::LibXML::XPathContext->new( $xn );
268 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
269 foreach my $d ( @details ) {
270 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
271 }
3a5d151b 272 }
f6e19c7c 273 }
274
4d85a60e 275 # Now collate the variant readings, since it is not done for us.
12720144 276 collate_variants( $c, \@lemma, values %wit_rdgs );
b8f262e8 277
4d85a60e 278 # Now add the witness paths for each reading.
a445ce40 279 my $aclabel = $c->ac_label;
f6e19c7c 280 foreach my $wit_id ( keys %wit_rdgs ) {
a445ce40 281 my $witstr = _get_sigil( $wit_id, $aclabel );
f6e19c7c 282 my $rdg_list = $wit_rdgs{$wit_id};
283 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
6f4946fb 284 }
4d85a60e 285}
6f4946fb 286
4d85a60e 287sub _anchor_name {
288 my $xmlid = shift;
289 $xmlid =~ s/^\#//;
10e4b1ac 290 return sprintf( "__ANCHOR_%s__", $xmlid );
6f4946fb 291}
292
4d85a60e 293sub _return_lemma {
294 my( $c, $app, $anchor ) = @_;
10e4b1ac 295 my @nodes = grep { $_->id !~ /^__A(PP|NCHOR)/ }
12720144 296 $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
297 $c->baselabel );
4d85a60e 298 return @nodes;
299}
6f4946fb 300
a445ce40 301=head2 interpret( $reading, $lemma )
302
303Given a string in $reading and a corresponding lemma in $lemma, interpret what
304the actual reading should be. Used to deal with apparatus-ese shorthands for
305marking transpositions, prefixed or suffixed words, and the like.
306
307=cut
308
6f4946fb 309sub interpret {
4d85a60e 310 # A utility function to change apparatus-ese into a full variant.
311 my( $reading, $lemma ) = @_;
312 return $reading if $reading eq $lemma;
313 my $oldreading = $reading;
314 # $lemma =~ s/\s+[[:punct:]]+$//;
12720144 315 my $flag; # In case of p.c. indications
4d85a60e 316 my @words = split( /\s+/, $lemma );
82a45078 317 $reading =~ s/[[:punct:]]?\bsic\b[[:punct:]]?//g;
4d85a60e 318 if( $reading =~ /^(.*) praem.$/ ) {
319 $reading = "$1 $lemma";
320 } elsif( $reading =~ /^(.*) add.$/ ) {
321 $reading = "$lemma $1";
b8f262e8 322 } elsif( $reading =~ /add. alia manu/
323 || $reading =~ /inscriptionem compegi e/ # TODO huh?
324 || $reading eq 'inc.' # TODO huh?
325 ) {
12720144 326 # Ignore it.
327 $reading = $lemma;
b8f262e8 328 } elsif( $reading =~ /locus [uv]acuus/
329 || $reading eq 'def.'
c9158e60 330 || $reading eq 'illeg.'
331 || $reading eq 'onleesbar'
f6e19c7c 332 ) {
b8f262e8 333 $reading = '#LACUNA#';
334 } elsif( $reading eq 'om.' ) {
4d85a60e 335 $reading = '';
c9158e60 336 } elsif( $reading =~ /^in[uv]\.$/
337 || $reading eq 'transp.' ) {
4d85a60e 338 # Hope it is two words.
a188b944 339 say STDERR "WARNING: want to invert a lemma that is not two words"
4d85a60e 340 unless scalar( @words ) == 2;
341 $reading = join( ' ', reverse( @words ) );
12720144 342 } elsif( $reading =~ /^iter(\.|at)$/ ) {
4d85a60e 343 # Repeat the lemma
344 $reading = "$lemma $lemma";
12720144 345 } elsif( $reading eq 'in marg.' ) {
346 # There was nothing before a correction.
347 $reading = '';
348 $flag = '_ac';
c9158e60 349 } elsif( $reading =~ /^(.*?)\s*\(?sic([\s\w.]+)?\)?$/ ) {
350 # Discard any 'sic' notation; indeed, indeed.
351 $reading = $1;
12720144 352 } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
4d85a60e 353 # The first and last N words captured should replace the first and
354 # last N words of the lemma.
355 my @begin = split( /\s+/, $1 );
356 my @end = split( /\s+/, $2 );
357 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
358 # Something is wrong and we can't do the splice.
a188b944 359 say STDERR "ERROR: $lemma is too short to accommodate $oldreading";
4d85a60e 360 } else {
361 splice( @words, 0, scalar @begin, @begin );
362 splice( @words, -(scalar @end), scalar @end, @end );
363 $reading = join( ' ', @words );
364 }
6f4946fb 365 }
12720144 366 if( $oldreading ne $reading || $flag || $oldreading =~ /\./ ) {
367 my $int = $reading;
368 $int .= " ($flag)" if $flag;
b39e7cb5 369 # say STDERR "Interpreted $oldreading as $int given $lemma";
12720144 370 }
371 return( $reading, $flag );
4d85a60e 372}
373
f6e19c7c 374sub _parse_wit_detail {
375 my( $detail, $readings, $lemma ) = @_;
376 my $wit = $detail->getAttribute( 'wit' );
377 my $content = $detail->textContent;
4ed2b212 378 if( $content =~ /a\.\s*c\b/ ) {
f6e19c7c 379 # Replace the key in the $readings hash
380 my $rdg = delete $readings->{$wit};
381 $readings->{$wit.'_ac'} = $rdg;
382 $has_ac{$sigil_for{$wit}} = 1;
4ed2b212 383 } elsif( $content =~ /p\.\s*c\b/ ) {
f6e19c7c 384 # If no key for the wit a.c. exists, add one pointing to the lemma
385 unless( exists $readings->{$wit.'_ac'} ) {
386 $readings->{$wit.'_ac'} = $lemma;
387 }
388 $has_ac{$sigil_for{$wit}} = 1;
389 } # else don't bother just yet
390}
391
a445ce40 392sub _get_sigil {
393 my( $xml_id, $layerlabel ) = @_;
f6e19c7c 394 if( $xml_id =~ /^(.*)_ac$/ ) {
395 my $real_id = $1;
a445ce40 396 return $sigil_for{$real_id} . $layerlabel;
f6e19c7c 397 } else {
398 return $sigil_for{$xml_id};
399 }
400}
401
a445ce40 402sub _expand_all_paths {
f6e19c7c 403 my( $c ) = @_;
404
405 # Walk the collation and fish out the paths for each witness
406 foreach my $wit ( $c->tradition->witnesses ) {
407 my $sig = $wit->sigil;
12720144 408 my @path = grep { !$_->is_ph }
f6e19c7c 409 $c->reading_sequence( $c->start, $c->end, $sig );
410 $wit->path( \@path );
411 if( $has_ac{$sig} ) {
12720144 412 my @ac_path = grep { !$_->is_ph }
861c3e27 413 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
f6e19c7c 414 $wit->uncorrected_path( \@ac_path );
415 }
416 }
417
418 # Delete the anchors
12720144 419 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
f6e19c7c 420 $c->del_reading( $anchor );
421 }
12720144 422 # Delete the base edges
423 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
f6e19c7c 424
425 # Make the path edges
426 $c->make_witness_paths();
7c2ed85e 427
428 # Now remove any orphan nodes, and warn that we are doing so.
82a45078 429 while( $c->sequence->predecessorless_vertices > 1 ) {
430 foreach my $v ( $c->sequence->predecessorless_vertices ) {
431 my $r = $c->reading( $v );
432 next if $r->is_start;
433 say STDERR "Deleting orphan reading $r / " . $r->text;
434 $c->del_reading( $r );
435 }
7c2ed85e 436 }
4d85a60e 437}
438
439sub _add_wit_path {
f6e19c7c 440 my( $c, $rdg, $app, $anchor, $wit ) = @_;
4d85a60e 441 my @nodes = @$rdg;
f6e19c7c 442 push( @nodes, $c->reading( $anchor ) );
4d85a60e 443
f6e19c7c 444 my $cur = $c->reading( $app );
4d85a60e 445 foreach my $n ( @nodes ) {
f6e19c7c 446 $c->add_path( $cur, $n, $wit );
4d85a60e 447 $cur = $n;
6f4946fb 448 }
6f4946fb 449}
450
00311328 451sub throw {
452 Text::Tradition::Error->throw(
453 'ident' => 'Parser::CTE error',
454 'message' => $_[0],
455 );
456}
457
6f4946fb 458=head1 LICENSE
459
460This package is free software and is provided "as is" without express
461or implied warranty. You can redistribute it and/or modify it under
462the same terms as Perl itself.
463
464=head1 AUTHOR
465
466Tara L Andrews, aurum@cpan.org
467
468=cut
469
4701;
471