better handling of CTE files and their annoying hilight elements
[scpubgit/stemmatology.git] / lib / Text / Tradition / Parser / CTE.pm
CommitLineData
6f4946fb 1package Text::Tradition::Parser::CTE;
2
3use strict;
4use warnings;
c9158e60 5use Encode qw/ decode /;
4d85a60e 6use Text::Tradition::Parser::Util qw/ collate_variants /;
6f4946fb 7use XML::LibXML;
8use XML::LibXML::XPathContext;
9
10=head1 NAME
11
12Text::Tradition::Parser::CTE
13
14=head1 DESCRIPTION
15
16Parser module for Text::Tradition, given a TEI file exported from
17Classical Text Editor.
18
19=head1 METHODS
20
21=over
22
23=item B<parse>
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 );
c9158e60 53 print STDERR "Adding witness $sig\n";
b8f262e8 54 $tradition->add_witness( sigil => $sig, source => $wit_el->toString() );
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 ) {
64 push( @base_text, _get_base( $xn ) );
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' ) {
12720144 81 $r = $c->add_reading( { id => '#ANCHOR_' . $item->{'content'} . '#',
82 is_ph => 1 } );
4d85a60e 83 } elsif ( $item->{'type'} eq 'app' ) {
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.
102 expand_all_paths( $c );
861c3e27 103
104 # Save the text for each witness so that we can ensure consistency
105 # later on
106 $tradition->collation->text_from_paths();
c9158e60 107 $tradition->collation->calculate_ranks();
108 $tradition->collation->flatten_ranks();
6f4946fb 109}
110
4d85a60e 111sub _stringify_sigil {
112 my( @nodes ) = @_;
113 my @parts = grep { /\w/ } map { $_->data } @nodes;
114 return join( '', @parts );
115}
6f4946fb 116
c9158e60 117# Get rid of all the formatting elements that get in the way of tokenization.
118sub _remove_formatting {
119 my( $opts ) = @_;
120
121 # First, parse the original XML
122 my $parser = XML::LibXML->new();
123 my $doc;
124 if( exists $opts->{'string'} ) {
125 $doc = $parser->parse_string( $opts->{'string'} );
126 } elsif ( exists $opts->{'file'} ) {
127 $doc = $parser->parse_file( $opts->{'file'} );
128 } else {
129 warn "Could not find string or file option to parse";
130 return;
131 }
132
133 # Second, remove the formatting
134 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
135 my @useless = $xpc->findnodes( '//hi' );
136 foreach my $n ( @useless ) {
137 my $parent = $n->parentNode();
138 my @children = $n->childNodes();
139 my $first = shift @children;
140 $parent->replaceChild( $first, $n );
141 foreach my $c ( @children ) {
142 $parent->insertAfter( $c, $first );
143 $first = $c;
144 }
145 }
146
147 # Third, write out and reparse to merge the text nodes.
148 my $result = decode( $doc->encoding, $doc->toString() );
149 my $tei = $parser->parse_string( $result )->documentElement;
150 $xpc = XML::LibXML::XPathContext->new( $tei );
151 return( $tei, $xpc );
152}
153
154## Helper function to help us navigate through nested XML, picking out
155## the words, the apparatus, and the anchors.
4d85a60e 156
157sub _get_base {
158 my( $xn ) = @_;
159 my @readings;
160 if( $xn->nodeType == XML_TEXT_NODE ) {
161 # Base text, just split the words on whitespace and add them
162 # to our sequence.
163 my $str = $xn->data;
164 $str =~ s/^\s+//;
c9158e60 165 my @tokens = split( /\s+/, $str );
166 push( @readings, map { { 'type' => 'token', 'content' => $_ } } @tokens );
4d85a60e 167 } elsif( $xn->nodeName eq 'app' ) {
168 # Apparatus, just save the entire XML node.
169 push( @readings, { 'type' => 'app', 'content' => $xn } );
170 } elsif( $xn->nodeName eq 'anchor' ) {
171 # Anchor to mark the end of some apparatus; save its ID.
172 push( @readings, { 'type' => 'anchor',
173 'content' => $xn->getAttribute( 'xml:id' ) } );
174 } elsif ( $xn->nodeName ne 'note' ) { # Any tag we don't know to disregard
175 print STDERR "Unrecognized tag " . $xn->nodeName . "\n";
6f4946fb 176 }
4d85a60e 177 return @readings;
6f4946fb 178}
179
c9158e60 180sub _append_tokens {
181 my( $list, @tokens ) = @_;
182 if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
183 # The list evidently ended mid-word; join the next token onto it.
184 my $t = shift @tokens;
185 if( ref $t && $t->{'type'} eq 'token' ) {
186 # Join the word
187 $t = $t->{'content'};
188 } elsif( ref $t ) {
189 # An app or anchor intervened; end the word.
190 unshift( @tokens, $t );
191 $t = '';
192 }
193 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
194 }
195 foreach my $t ( @tokens ) {
196 unless( ref( $t ) ) {
197 $t = { 'type' => 'token', 'content' => $t };
198 }
199 push( @$list, $t );
200 }
201}
202
4d85a60e 203sub _add_readings {
204 my( $c, $app_id ) = @_;
205 my $xn = $apps{$app_id};
206 my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
207 # Get the lemma, which is all the readings between app and anchor,
208 # excluding other apps or anchors.
209 my @lemma = _return_lemma( $c, $app_id, $anchor );
210 my $lemma_str = join( ' ', grep { $_ !~ /^\#/ } map { $_->text } @lemma );
211
212 # For each reading, send its text to 'interpret' along with the lemma,
213 # and then save the list of witnesses that these tokens belong to.
3a5d151b 214 my %wit_rdgs; # Maps from witnesses to the variant text
4d85a60e 215 my $ctr = 0;
216 my $tag = $app_id;
217 $tag =~ s/^\#APP_(.*)\#$/$1/;
c9158e60 218
4d85a60e 219 foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
220 my @text;
4d85a60e 221 foreach ( $rdg->childNodes ) {
222 push( @text, _get_base( $_ ) );
223 }
12720144 224 my( $interpreted, $flag ) = ( '', undef );
225 if( @text ) {
226 ( $interpreted, $flag ) = interpret(
227 join( ' ', map { $_->{'content'} } @text ), $lemma_str );
228 }
b8f262e8 229 next if( $interpreted eq $lemma_str ) && !$flag; # Reading is lemma.
230
4d85a60e 231 my @rdg_nodes;
b8f262e8 232 if( $interpreted eq '#LACUNA#' ) {
233 push( @rdg_nodes, $c->add_reading( { id => $tag . "/" . $ctr++,
234 is_lacuna => 1 } ) );
235 } else {
236 foreach my $w ( split( /\s+/, $interpreted ) ) {
237 my $r = $c->add_reading( { id => $tag . "/" . $ctr++,
238 text => $w } );
239 push( @rdg_nodes, $r );
240 }
4d85a60e 241 }
f6e19c7c 242 # For each listed wit, save the reading.
243 foreach my $wit ( split( /\s+/, $rdg->getAttribute( 'wit' ) ) ) {
12720144 244 $wit .= $flag if $flag;
f6e19c7c 245 $wit_rdgs{$wit} = \@rdg_nodes;
246 }
12720144 247
3a5d151b 248 # Does the reading have an ID? If so it probably has a witDetail
f6e19c7c 249 # attached, and we need to read it.
3a5d151b 250 if( $rdg->hasAttribute( 'xml:id' ) ) {
12720144 251 warn "Witdetail on meta reading" if $flag; # this could get complicated.
f6e19c7c 252 my $rid = $rdg->getAttribute( 'xml:id' );
253 my $xpc = XML::LibXML::XPathContext->new( $xn );
254 my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
255 foreach my $d ( @details ) {
256 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
257 }
3a5d151b 258 }
f6e19c7c 259 }
260
4d85a60e 261 # Now collate the variant readings, since it is not done for us.
c9158e60 262 $DB::single = 1 if @lemma > 10;
12720144 263 collate_variants( $c, \@lemma, values %wit_rdgs );
b8f262e8 264
4d85a60e 265 # Now add the witness paths for each reading.
f6e19c7c 266 foreach my $wit_id ( keys %wit_rdgs ) {
267 my $witstr = get_sigil( $wit_id, $c );
268 my $rdg_list = $wit_rdgs{$wit_id};
269 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
6f4946fb 270 }
4d85a60e 271}
6f4946fb 272
4d85a60e 273sub _anchor_name {
274 my $xmlid = shift;
275 $xmlid =~ s/^\#//;
276 return sprintf( "#ANCHOR_%s#", $xmlid );
6f4946fb 277}
278
4d85a60e 279sub _return_lemma {
280 my( $c, $app, $anchor ) = @_;
12720144 281 my @nodes = grep { $_->id !~ /^\#A(PP|NCHOR)/ }
282 $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
283 $c->baselabel );
4d85a60e 284 return @nodes;
285}
6f4946fb 286
287sub interpret {
4d85a60e 288 # A utility function to change apparatus-ese into a full variant.
289 my( $reading, $lemma ) = @_;
290 return $reading if $reading eq $lemma;
291 my $oldreading = $reading;
292 # $lemma =~ s/\s+[[:punct:]]+$//;
12720144 293 my $flag; # In case of p.c. indications
4d85a60e 294 my @words = split( /\s+/, $lemma );
295 if( $reading =~ /^(.*) praem.$/ ) {
296 $reading = "$1 $lemma";
297 } elsif( $reading =~ /^(.*) add.$/ ) {
298 $reading = "$lemma $1";
b8f262e8 299 } elsif( $reading =~ /add. alia manu/
300 || $reading =~ /inscriptionem compegi e/ # TODO huh?
301 || $reading eq 'inc.' # TODO huh?
302 ) {
12720144 303 # Ignore it.
304 $reading = $lemma;
b8f262e8 305 } elsif( $reading =~ /locus [uv]acuus/
306 || $reading eq 'def.'
c9158e60 307 || $reading eq 'illeg.'
308 || $reading eq 'onleesbar'
f6e19c7c 309 ) {
b8f262e8 310 $reading = '#LACUNA#';
311 } elsif( $reading eq 'om.' ) {
4d85a60e 312 $reading = '';
c9158e60 313 } elsif( $reading =~ /^in[uv]\.$/
314 || $reading eq 'transp.' ) {
4d85a60e 315 # Hope it is two words.
316 print STDERR "WARNING: want to invert a lemma that is not two words\n"
317 unless scalar( @words ) == 2;
318 $reading = join( ' ', reverse( @words ) );
12720144 319 } elsif( $reading =~ /^iter(\.|at)$/ ) {
4d85a60e 320 # Repeat the lemma
321 $reading = "$lemma $lemma";
12720144 322 } elsif( $reading eq 'in marg.' ) {
323 # There was nothing before a correction.
324 $reading = '';
325 $flag = '_ac';
c9158e60 326 } elsif( $reading =~ /^(.*?)\s*\(?sic([\s\w.]+)?\)?$/ ) {
327 # Discard any 'sic' notation; indeed, indeed.
328 $reading = $1;
12720144 329 } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
4d85a60e 330 # The first and last N words captured should replace the first and
331 # last N words of the lemma.
332 my @begin = split( /\s+/, $1 );
333 my @end = split( /\s+/, $2 );
334 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
335 # Something is wrong and we can't do the splice.
336 print STDERR "ERROR: $lemma is too short to accommodate $oldreading\n";
337 } else {
338 splice( @words, 0, scalar @begin, @begin );
339 splice( @words, -(scalar @end), scalar @end, @end );
340 $reading = join( ' ', @words );
341 }
6f4946fb 342 }
12720144 343 if( $oldreading ne $reading || $flag || $oldreading =~ /\./ ) {
344 my $int = $reading;
345 $int .= " ($flag)" if $flag;
346 print STDERR "Interpreted $oldreading as $int given $lemma\n";
347 }
348 return( $reading, $flag );
4d85a60e 349}
350
f6e19c7c 351sub _parse_wit_detail {
352 my( $detail, $readings, $lemma ) = @_;
353 my $wit = $detail->getAttribute( 'wit' );
354 my $content = $detail->textContent;
355 if( $content =~ /a\.\s*c\./ ) {
356 # Replace the key in the $readings hash
357 my $rdg = delete $readings->{$wit};
358 $readings->{$wit.'_ac'} = $rdg;
359 $has_ac{$sigil_for{$wit}} = 1;
360 } elsif( $content =~ /p\.\s*c\./ ) {
361 # If no key for the wit a.c. exists, add one pointing to the lemma
362 unless( exists $readings->{$wit.'_ac'} ) {
363 $readings->{$wit.'_ac'} = $lemma;
364 }
365 $has_ac{$sigil_for{$wit}} = 1;
366 } # else don't bother just yet
367}
368
369sub get_sigil {
370 my( $xml_id, $c ) = @_;
371 if( $xml_id =~ /^(.*)_ac$/ ) {
372 my $real_id = $1;
373 return $sigil_for{$real_id} . $c->ac_label;
374 } else {
375 return $sigil_for{$xml_id};
376 }
377}
378
379sub expand_all_paths {
380 my( $c ) = @_;
381
382 # Walk the collation and fish out the paths for each witness
383 foreach my $wit ( $c->tradition->witnesses ) {
384 my $sig = $wit->sigil;
12720144 385 my @path = grep { !$_->is_ph }
f6e19c7c 386 $c->reading_sequence( $c->start, $c->end, $sig );
387 $wit->path( \@path );
388 if( $has_ac{$sig} ) {
12720144 389 my @ac_path = grep { !$_->is_ph }
861c3e27 390 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
f6e19c7c 391 $wit->uncorrected_path( \@ac_path );
392 }
393 }
394
395 # Delete the anchors
12720144 396 foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
f6e19c7c 397 $c->del_reading( $anchor );
398 }
12720144 399 # Delete the base edges
400 map { $c->del_path( $_, $c->baselabel ) } $c->paths;
f6e19c7c 401
402 # Make the path edges
403 $c->make_witness_paths();
4d85a60e 404}
405
406sub _add_wit_path {
f6e19c7c 407 my( $c, $rdg, $app, $anchor, $wit ) = @_;
4d85a60e 408 my @nodes = @$rdg;
f6e19c7c 409 push( @nodes, $c->reading( $anchor ) );
4d85a60e 410
f6e19c7c 411 my $cur = $c->reading( $app );
4d85a60e 412 foreach my $n ( @nodes ) {
f6e19c7c 413 $c->add_path( $cur, $n, $wit );
4d85a60e 414 $cur = $n;
6f4946fb 415 }
6f4946fb 416}
417
418=back
419
420=head1 LICENSE
421
422This package is free software and is provided "as is" without express
423or implied warranty. You can redistribute it and/or modify it under
424the same terms as Perl itself.
425
426=head1 AUTHOR
427
428Tara L Andrews, aurum@cpan.org
429
430=cut
431
4321;
433