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