Handle a2 app entries separately and more correctly. Fixes #5
[scpubgit/stemmatology.git] / base / lib / Text / Tradition / Parser / TEI.pm
CommitLineData
f6066bac 1package Text::Tradition::Parser::TEI;
2
3use strict;
4use warnings;
00311328 5use Text::Tradition::Error;
910a0a6d 6use Text::Tradition::Parser::Util qw( collate_variants );
f6066bac 7use XML::LibXML;
8use XML::LibXML::XPathContext;
9
10=head1 NAME
11
12Text::Tradition::Parser::TEI
13
3b853983 14=head1 SYNOPSIS
15
16 use Text::Tradition;
17
18 my $t_from_file = Text::Tradition->new(
19 'name' => 'my text',
20 'input' => 'TEI',
21 'file' => '/path/to/parallel_seg_file.xml'
22 );
23
24 my $t_from_string = Text::Tradition->new(
25 'name' => 'my text',
26 'input' => 'TEI',
27 'string' => $parallel_seg_xml,
28 );
29
30
f6066bac 31=head1 DESCRIPTION
32
3b853983 33Parser module for Text::Tradition, given a TEI parallel-segmentation file
34that describes a text and its variants. Normally called upon
35initialization of Text::Tradition.
36
37The witnesses for the tradition are taken from the <listWit/> element
38within the TEI header; the readings are taken from any <p/> element that
39appears in the text body (including <head/> elements therein.)
f6066bac 40
41=head1 METHODS
42
e867486f 43=head2 B<parse>( $tradition, $option_hash )
3b853983 44
45Takes an initialized tradition and a set of options; creates the
46appropriate nodes and edges on the graph, as well as the appropriate
47witness objects. The $option_hash must contain either a 'file' or a
48'string' argument with the XML to be parsed.
49
50=begin testing
51
52use Text::Tradition;
53binmode STDOUT, ":utf8";
54binmode STDERR, ":utf8";
55eval { no warnings; binmode $DB::OUT, ":utf8"; };
56
57my $par_seg = 't/data/florilegium_tei_ps.xml';
58my $t = Text::Tradition->new(
59 'name' => 'inline',
60 'input' => 'TEI',
61 'file' => $par_seg,
62 );
f6066bac 63
3b853983 64is( ref( $t ), 'Text::Tradition', "Parsed parallel-segmentation TEI" );
65if( $t ) {
56eefa04 66 is( scalar $t->collation->readings, 311, "Collation has all readings" );
67 is( scalar $t->collation->paths, 361, "Collation has all paths" );
3b853983 68}
f6066bac 69
3b853983 70=end testing
f6066bac 71
72=cut
73
910a0a6d 74my $text = {}; # Hash of arrays, one per eventual witness we find.
910a0a6d 75my $substitutions = {}; # Keep track of merged readings
76my $app_anchors = {}; # Track apparatus references
77my $app_ac = {}; # Save a.c. readings
eca16057 78my $app_count; # Keep track of how many apps we have
910a0a6d 79
80# Create the package variables for tag names.
81
82# Would really like to do this with varname variables, but apparently this
83# is considered a bad idea. The long way round then.
84my( $LISTWIT, $WITNESS, $TEXT, $W, $SEG, $APP, $RDG, $LEM )
85 = ( 'listWit', 'witness', 'text', 'w', 'seg', 'app', 'rdg', 'lem' );
3b853983 86sub _make_tagnames {
910a0a6d 87 my( $ns ) = @_;
88 if( $ns ) {
89 $LISTWIT = "$ns:$LISTWIT";
90 $WITNESS = "$ns:$WITNESS";
91 $TEXT = "$ns:$TEXT";
92 $W = "$ns:$W";
93 $SEG = "$ns:$SEG";
94 $APP = "$ns:$APP";
95 $RDG = "$ns:$RDG";
96 $LEM = "$ns:$LEM";
97 }
98}
99
100# Parse the TEI file.
f6066bac 101sub parse {
dfc37e38 102 my( $tradition, $opts ) = @_;
f6066bac 103
104 # First, parse the XML.
105 my $parser = XML::LibXML->new();
dfc37e38 106 my $doc;
107 if( exists $opts->{'string'} ) {
108 $doc = $parser->parse_string( $opts->{'string'} );
109 } elsif ( exists $opts->{'file'} ) {
110 $doc = $parser->parse_file( $opts->{'file'} );
111 } else {
112 warn "Could not find string or file option to parse";
113 return;
114 }
f6066bac 115 my $tei = $doc->documentElement();
00311328 116 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
117 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
118 }
f2b9605f 119 my $xpc = XML::LibXML::XPathContext->new( $tei );
910a0a6d 120 my $ns;
121 if( $tei->namespaceURI ) {
122 $ns = 'tei';
123 $xpc->registerNs( $ns, $tei->namespaceURI );
124 }
3b853983 125 _make_tagnames( $ns );
910a0a6d 126
f6066bac 127 # Then get the witnesses and create the witness objects.
910a0a6d 128 foreach my $wit_el ( $xpc->findnodes( "//$LISTWIT/$WITNESS" ) ) {
129 my $sig = $wit_el->getAttribute( 'xml:id' );
130 my $source = $wit_el->toString();
82fa4d57 131 $tradition->add_witness( sigil => $sig, sourcetype => 'collation' );
f6066bac 132 }
910a0a6d 133 map { $text->{$_->sigil} = [] } $tradition->witnesses;
eca16057 134
910a0a6d 135 # Look for all word/seg node IDs and note their pre-existence.
a7fb3133 136 my @attrs = $xpc->findnodes( "//$W/attribute::xml:id" );
3b853983 137 _save_preexisting_nodeids( @attrs );
910a0a6d 138
eca16057 139 # Count up how many apps we have.
140 my @apps = $xpc->findnodes( "//$APP" );
141 $app_count = scalar( @apps );
142
910a0a6d 143 # Now go through the children of the text element and pull out the
144 # actual text.
145 foreach my $xml_el ( $xpc->findnodes( "//$TEXT" ) ) {
146 foreach my $xn ( $xml_el->childNodes ) {
147 _get_readings( $tradition, $xn );
148 }
149 }
150 # Our $text global now has lists of readings, one per witness.
151 # Join them up.
152 my $c = $tradition->collation;
153 foreach my $sig ( keys %$text ) {
910a0a6d 154 # Determine the list of readings for
155 my $sequence = $text->{$sig};
156 my @real_sequence = ( $c->start );
157 push( @$sequence, $c->end );
342c1111 158 foreach( _clean_sequence( $sig, $sequence, 1 ) ) {
159 push( @real_sequence, _return_rdg( $_ ) );
910a0a6d 160 }
910a0a6d 161 # See if we need to make an a.c. version of the witness.
162 if( exists $app_ac->{$sig} ) {
163 my @uncorrected;
164 push( @uncorrected, @real_sequence );
342c1111 165 # Get rid of any remaining placeholders.
166 @real_sequence = _clean_sequence( $sig, \@uncorrected );
167 # Do the uncorrections
910a0a6d 168 foreach my $app ( keys %{$app_ac->{$sig}} ) {
169 my $start = _return_rdg( $app_anchors->{$app}->{$sig}->{'start'} );
170 my $end = _return_rdg( $app_anchors->{$app}->{$sig}->{'end'} );
171 my @new = map { _return_rdg( $_ ) } @{$app_ac->{$sig}->{$app}};
172 _replace_sequence( \@uncorrected, $start, $end, @new );
173 }
342c1111 174 # and record the results.
175 $tradition->witness( $sig )->uncorrected_path( \@uncorrected );
1f7aa795 176 $tradition->witness( $sig )->is_layered( 1 );
910a0a6d 177 }
342c1111 178 $tradition->witness( $sig )->path( \@real_sequence );
910a0a6d 179 }
342c1111 180 # Now make our witness paths.
181 $tradition->collation->make_witness_paths();
3b853983 182
82a45078 183 unless( $opts->{'nocalc'} ) {
184 # Calculate the ranks for the nodes.
185 $tradition->collation->calculate_ranks();
186
187 # Now that we have ranks, see if we have distinct nodes with identical
188 # text and identical rank that can be merged.
189 $tradition->collation->flatten_ranks();
190
191 # And now that we've done that, calculate the common nodes.
192 $tradition->collation->calculate_common_readings();
193
194 # Save the text for each witness so that we can ensure consistency
195 # later on
196 $tradition->collation->text_from_paths();
197 }
910a0a6d 198}
199
200sub _clean_sequence {
342c1111 201 my( $wit, $sequence, $keep_ac ) = @_;
910a0a6d 202 my @clean_sequence;
203 foreach my $rdg ( @$sequence ) {
204 if( $rdg =~ /^PH-(.*)$/ ) {
342c1111 205 # It is a placeholder. Keep it only if we need it for a later
206 # a.c. run.
910a0a6d 207 my $app_id = $1;
342c1111 208 if( $keep_ac && exists $app_ac->{$wit} &&
78fab1cf 209 exists $app_ac->{$wit}->{$app_id} ) {
342c1111 210 # print STDERR "Retaining empty placeholder for $app_id\n";
211 push( @clean_sequence, $rdg );
910a0a6d 212 }
213 } else {
214 push( @clean_sequence, $rdg );
215 }
f6066bac 216 }
910a0a6d 217 return @clean_sequence;
218}
f6066bac 219
910a0a6d 220sub _replace_sequence {
221 my( $arr, $start, $end, @new ) = @_;
222 my( $start_idx, $end_idx );
223 foreach my $i ( 0 .. $#{$arr} ) {
342c1111 224 # If $arr->[$i] is a placeholder, cope.
225 my $iid = ref( $arr->[$i] ) ? $arr->[$i]->id : $arr->[$i];
226 $start_idx = $i if( $iid eq $start );
227 if( $iid eq $end ) {
910a0a6d 228 $end_idx = $i;
229 last;
230 }
231 }
232 unless( $start_idx && $end_idx ) {
233 warn "Could not find start and end";
234 return;
f2b9605f 235 }
910a0a6d 236 my $length = $end_idx - $start_idx + 1;
237 splice( @$arr, $start_idx, $length, @new );
238}
f6066bac 239
910a0a6d 240sub _return_rdg {
241 my( $rdg ) = @_;
242 # If we were passed a reading name, return the name. If we were
243 # passed a reading object, return the object.
244 my $wantobj = ref( $rdg ) eq 'Text::Tradition::Collation::Reading';
245 my $real = $rdg;
e4b0f464 246 if( exists $substitutions->{ $wantobj ? $rdg->id : $rdg } ) {
247 $real = $substitutions->{ $wantobj ? $rdg->id : $rdg };
248 $real = $real->id unless $wantobj;
910a0a6d 249 }
250 return $real;
f6066bac 251}
252
3b853983 253## TODO test specific sorts of nodes of the parallel-seg XML.
254
910a0a6d 255## Recursive helper function to help us navigate through nested XML,
256## picking out the text. $tradition is the tradition, needed for
257## making readings; $xn is the XML node currently being looked at,
258## $in_var is a flag to say that we are inside a variant, $ac is a
259## flag to say that we are inside an ante-correctionem reading, and
260## @cur_wits is the list of witnesses to which this XML node applies.
261## Returns the list of readings, if any, created on the run.
262
263{
3bc0cd18 264 my %active_wits;
910a0a6d 265 my $current_app;
eca16057 266 my $seen_apps;
910a0a6d 267
268 sub _get_readings {
269 my( $tradition, $xn, $in_var, $ac, @cur_wits ) = @_;
3bc0cd18 270 @cur_wits = grep { $active_wits{$_} } keys %active_wits unless $in_var;
910a0a6d 271
272 my @new_readings;
273 if( $xn->nodeType == XML_TEXT_NODE ) {
274 # Some words, thus make some readings.
275 my $str = $xn->data;
276 return unless $str =~ /\S/; # skip whitespace-only text nodes
277 #print STDERR "Handling text node " . $str . "\n";
278 # Check that all the witnesses we have are active.
279 foreach my $c ( @cur_wits ) {
3bc0cd18 280 warn "$c is not among active wits" unless $active_wits{$c};
910a0a6d 281 }
282 $str =~ s/^\s+//;
283 my $final = $str =~ s/\s+$//;
284 foreach my $w ( split( /\s+/, $str ) ) {
285 # For now, skip punctuation.
286 next if $w !~ /[[:alnum:]]/;
3b853983 287 my $rdg = _make_reading( $tradition->collation, $w );
910a0a6d 288 push( @new_readings, $rdg );
910a0a6d 289 foreach ( @cur_wits ) {
290 warn "Empty wit!" unless $_;
291 warn "Empty reading!" unless $rdg;
292 push( @{$text->{$_}}, $rdg ) unless $ac;
293 }
294 }
295 } elsif( $xn->nodeName eq 'w' ) {
296 # Everything in this tag is one word. Also save any original XML ID.
297 #print STDERR "Handling word " . $xn->toString . "\n";
298 # Check that all the witnesses we have are active.
299 foreach my $c ( @cur_wits ) {
3bc0cd18 300 warn "$c is not among active wits" unless $active_wits{$c};
910a0a6d 301 }
302 my $xml_id = $xn->getAttribute( 'xml:id' );
3b853983 303 my $rdg = _make_reading( $tradition->collation, $xn->textContent, $xml_id );
910a0a6d 304 push( @new_readings, $rdg );
910a0a6d 305 foreach( @cur_wits ) {
306 warn "Empty wit!" unless $_;
307 warn "Empty reading!" unless $rdg;
308 push( @{$text->{$_}}, $rdg ) unless $ac;
309 }
310 } elsif ( $xn->nodeName eq 'app' ) {
eca16057 311 $seen_apps++;
910a0a6d 312 $current_app = $xn->getAttribute( 'xml:id' );
313 # print STDERR "Handling app $current_app\n";
314 # Keep the reading sets in this app.
315 my @sets;
316 # Recurse through all children (i.e. rdgs) for sets of words.
317 foreach ( $xn->childNodes ) {
318 my @rdg_set = _get_readings( $tradition, $_, $in_var, $ac, @cur_wits );
319 push( @sets, \@rdg_set ) if @rdg_set;
320 }
321 # Now collate these sets if we have more than one.
322 my $subs = collate_variants( $tradition->collation, @sets ) if @sets > 1;
323 map { $substitutions->{$_} = $subs->{$_} } keys %$subs;
910a0a6d 324 # Return the entire set of unique readings.
325 my %unique;
326 foreach my $s ( @sets ) {
e4b0f464 327 map { $unique{$_->id} = $_ } @$s;
910a0a6d 328 }
329 push( @new_readings, values( %unique ) );
330 # Exit the current app.
331 $current_app = '';
332 } elsif ( $xn->nodeName eq 'lem' || $xn->nodeName eq 'rdg' ) {
333 # Alter the current witnesses and recurse.
334 #print STDERR "Handling reading for " . $xn->getAttribute( 'wit' ) . "\n";
3bc0cd18 335 # TODO handle p.c. and s.l. designations too
910a0a6d 336 $ac = $xn->getAttribute( 'type' ) && $xn->getAttribute( 'type' ) eq 'a.c.';
3b853983 337 my @rdg_wits = _get_sigla( $xn );
a7fb3133 338 return unless @rdg_wits; # Skip readings that appear in no witnesses
910a0a6d 339 my @words;
340 foreach ( $xn->childNodes ) {
341 my @rdg_set = _get_readings( $tradition, $_, 1, $ac, @rdg_wits );
342 push( @words, @rdg_set ) if @rdg_set;
343 }
344 # If we have more than one word in a reading, it should become a segment.
345 # $tradition->collation->add_segment( @words ) if @words > 1;
346
347 if( $ac ) {
348 # Add the reading set to the a.c. readings.
349 foreach ( @rdg_wits ) {
350 $app_ac->{$_}->{$current_app} = \@words;
351 }
352 } else {
353 # Add the reading set to the app anchors for each witness
354 # or put in placeholders for empty p.c. readings
355 foreach ( @rdg_wits ) {
e4b0f464 356 my $start = @words ? $words[0]->id : "PH-$current_app";
357 my $end = @words ? $words[-1]->id : "PH-$current_app";
910a0a6d 358 $app_anchors->{$current_app}->{$_}->{'start'} = $start;
359 $app_anchors->{$current_app}->{$_}->{'end'} = $end;
360 push( @{$text->{$_}}, $start ) unless @words;
361 }
362 }
363 push( @new_readings, @words );
364 } elsif( $xn->nodeName eq 'witStart' ) {
365 # Add the relevant wit(s) to the active list.
366 #print STDERR "Handling witStart\n";
3bc0cd18 367 map { $active_wits{$_} = 1 } @cur_wits;
368 # Record a lacuna in all non-active witnesses if this is
369 # the first app. Get the full list from $text.
370 if( $seen_apps == 1 ) {
371 my $i = 0;
372 foreach my $sig ( keys %$text ) {
373 next if $active_wits{$sig};
e4b0f464 374 my $l = $tradition->collation->add_reading( {
e4b0f464 375 'id' => $current_app . "_$i",
376 'is_lacuna' => 1 } );
3bc0cd18 377 $i++;
378 push( @{$text->{$sig}}, $l );
379 }
380 }
910a0a6d 381 } elsif( $xn->nodeName eq 'witEnd' ) {
382 # Take the relevant wit(s) out of the list.
383 #print STDERR "Handling witEnd\n";
3bc0cd18 384 map { $active_wits{$_} = undef } @cur_wits;
eca16057 385 # Record a lacuna, unless this is the last app.
386 unless( $seen_apps == $app_count ) {
387 foreach my $i ( 0 .. $#cur_wits ) {
388 my $w = $cur_wits[$i];
e4b0f464 389 my $l = $tradition->collation->add_reading( {
e4b0f464 390 'id' => $current_app . "_$i",
391 'is_lacuna' => 1 } );
eca16057 392 push( @{$text->{$w}}, $l );
393 }
394 }
a7fb3133 395 } elsif( $xn->nodeName eq 'witDetail'
396 || $xn->nodeName eq 'note' ) {
910a0a6d 397 # Ignore these for now.
398 return;
399 } else {
400 # Recurse as if this tag weren't there.
401 #print STDERR "Recursing on tag " . $xn->nodeName . "\n";
402 foreach( $xn->childNodes ) {
403 push( @new_readings, _get_readings( $tradition, $_, $in_var, $ac, @cur_wits ) );
404 }
405 }
406 return @new_readings;
407 }
408
409}
410
3b853983 411=begin testing
412
413use XML::LibXML;
414use XML::LibXML::XPathContext;
415use Text::Tradition::Parser::TEI;
416
417my $xml_str = '<tei><rdg wit="#A #B #C #D">some text</rdg></tei>';
418my $el = XML::LibXML->new()->parse_string( $xml_str )->documentElement;
419my $xpc = XML::LibXML::XPathContext->new( $el );
420my $obj = $xpc->find( '//rdg' );
421
422my @wits = Text::Tradition::Parser::TEI::_get_sigla( $obj );
423is( join( ' ', @wits) , "A B C D", "correctly parsed reading wit string" );
424
425=end testing
426
427=cut
428
910a0a6d 429# Helper to extract a list of witness sigla from a reading element.
3b853983 430sub _get_sigla {
f6066bac 431 my( $rdg ) = @_;
432 # Cope if we have been handed a NodeList. There is only
433 # one reading here.
434 if( ref( $rdg ) eq 'XML::LibXML::NodeList' ) {
910a0a6d 435 $rdg = $rdg->shift;
f6066bac 436 }
437
438 my @wits;
439 if( ref( $rdg ) eq 'XML::LibXML::Element' ) {
910a0a6d 440 my $witstr = $rdg->getAttribute( 'wit' );
a7fb3133 441 return () unless $witstr;
910a0a6d 442 $witstr =~ s/^\s+//;
443 $witstr =~ s/\s+$//;
444 @wits = split( /\s+/, $witstr );
445 map { $_ =~ s/^\#// } @wits;
f6066bac 446 }
447 return @wits;
448}
449
910a0a6d 450# Helper with its counters to actually make the readings.
f2b9605f 451{
452 my $word_ctr = 0;
453 my %used_nodeids;
454
3b853983 455 sub _save_preexisting_nodeids {
910a0a6d 456 foreach( @_ ) {
457 $used_nodeids{$_->getValue()} = 1;
458 }
459 }
460
3b853983 461 sub _make_reading {
910a0a6d 462 my( $graph, $word, $xml_id ) = @_;
463 if( $xml_id ) {
464 if( exists $used_nodeids{$xml_id} ) {
465 if( $used_nodeids{$xml_id} != 1 ) {
466 warn "Already used assigned XML ID somewhere else!";
467 $xml_id = undef;
468 }
469 } else {
470 warn "Undetected pre-existing XML ID";
471 }
472 }
473 if( !$xml_id ) {
474 until( $xml_id ) {
475 my $try_id = 'w'.$word_ctr++;
476 next if exists $used_nodeids{$try_id};
477 $xml_id = $try_id;
478 }
479 }
e4b0f464 480 my $rdg = $graph->add_reading(
49d4f2ac 481 { 'id' => $xml_id,
e4b0f464 482 'text' => $word }
483 );
910a0a6d 484 $used_nodeids{$xml_id} = $rdg;
485 return $rdg;
f2b9605f 486 }
487}
488
f6066bac 4891;
3b853983 490
00311328 491sub throw {
492 Text::Tradition::Error->throw(
493 'ident' => 'Parser::TEI error',
494 'message' => $_[0],
495 );
496}
497
3b853983 498=head1 BUGS / TODO
499
500=over
501
502=item * More unit testing
503
e867486f 504=item * Handle special designations apart from a.c.
505
506=item * Mark common nodes within collated variants
507
3b853983 508=back
509
510=head1 LICENSE
511
512This package is free software and is provided "as is" without express
513or implied warranty. You can redistribute it and/or modify it under
514the same terms as Perl itself.
515
516=head1 AUTHOR
517
518Tara L Andrews E<lt>aurum@cpan.orgE<gt>