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