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