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