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