68172f75049cbc2aecdd9bd30498d123b14f47bd
[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 DESCRIPTION
14
15 Parser module for Text::Tradition, given a TEI parallel-segmentation
16 file that describes a text and its variants.
17
18 =head1 METHODS
19
20 =over
21
22 =item B<parse>
23
24 parse( $tei_string );
25
26 Takes an initialized tradition and a string containing the TEI;
27 creates the appropriate nodes and edges on the graph, as well as
28 the appropriate witness objects.
29
30 =cut
31
32 my $text = {}; # Hash of arrays, one per eventual witness we find.
33 my $substitutions = {}; # Keep track of merged readings
34 my $app_anchors = {};   # Track apparatus references
35 my $app_ac = {};        # Save a.c. readings
36
37 # Create the package variables for tag names.
38
39 # Would really like to do this with varname variables, but apparently this
40 # is considered a bad idea.  The long way round then.
41 my( $LISTWIT, $WITNESS, $TEXT, $W, $SEG, $APP, $RDG, $LEM ) 
42     = ( 'listWit', 'witness', 'text', 'w', 'seg', 'app', 'rdg', 'lem' );
43 sub make_tagnames {
44     my( $ns ) = @_;
45     if( $ns ) {
46         $LISTWIT = "$ns:$LISTWIT";
47         $WITNESS = "$ns:$WITNESS";
48         $TEXT = "$ns:$TEXT";
49         $W = "$ns:$W";
50         $SEG = "$ns:$SEG";
51         $APP = "$ns:$APP";
52         $RDG = "$ns:$RDG";
53         $LEM = "$ns:$LEM";
54     }
55 }
56
57 # Parse the TEI file.
58 sub parse {
59     my( $tradition, $xml_str ) = @_;
60     
61     # First, parse the XML.
62     my $parser = XML::LibXML->new();
63     my $doc = $parser->parse_string( $xml_str );
64     my $tei = $doc->documentElement();
65     my $xpc = XML::LibXML::XPathContext->new( $tei );
66     my $ns;
67     if( $tei->namespaceURI ) {
68         $ns = 'tei';
69         $xpc->registerNs( $ns, $tei->namespaceURI );
70     }
71     make_tagnames( $ns );
72
73     # Then get the witnesses and create the witness objects.
74     foreach my $wit_el ( $xpc->findnodes( "//$LISTWIT/$WITNESS" ) ) {
75         my $sig = $wit_el->getAttribute( 'xml:id' );
76         my $source = $wit_el->toString();
77         $tradition->add_witness( sigil => $sig, source => $source );
78     }
79
80     map { $text->{$_->sigil} = [] } $tradition->witnesses;
81     # Look for all word/seg node IDs and note their pre-existence.
82     my @attrs = $xpc->findnodes( "//$W|$SEG/attribute::xml:id" );
83     save_preexisting_nodeids( @attrs );
84
85     # Now go through the children of the text element and pull out the
86     # actual text.
87     foreach my $xml_el ( $xpc->findnodes( "//$TEXT" ) ) {
88         foreach my $xn ( $xml_el->childNodes ) {
89             _get_readings( $tradition, $xn );
90         }
91     }
92     # Our $text global now has lists of readings, one per witness.
93     # Join them up.
94     my $c = $tradition->collation;
95     foreach my $sig ( keys %$text ) {
96         next if $sig eq 'base';  # Skip base text readings with no witnesses.
97         # Determine the list of readings for 
98         my $sequence = $text->{$sig};
99         my @real_sequence = ( $c->start );
100         push( @$sequence, $c->end );
101         my $source = $c->start;
102         foreach( _clean_sequence( $sig, $sequence ) ) {
103             my $rdg = _return_rdg( $_ );
104             push( @real_sequence, $rdg );
105             $c->add_path( $source, $rdg, $sig );
106             $source = $rdg;
107         }
108         $tradition->witness( $sig )->path( \@real_sequence );
109         # See if we need to make an a.c. version of the witness.
110         if( exists $app_ac->{$sig} ) {
111             my @uncorrected;
112             push( @uncorrected, @real_sequence );
113             foreach my $app ( keys %{$app_ac->{$sig}} ) {
114                 my $start = _return_rdg( $app_anchors->{$app}->{$sig}->{'start'} ); 
115                 my $end = _return_rdg( $app_anchors->{$app}->{$sig}->{'end'} );
116                 my @new = map { _return_rdg( $_ ) } @{$app_ac->{$sig}->{$app}};
117                 _replace_sequence( \@uncorrected, $start, $end, @new );
118             }
119             my $source = $c->start;
120             foreach my $rdg ( @uncorrected ) {
121                 my $has_base = grep { $_->label eq $sig } $source->edges_to( $rdg );
122                 if( $rdg ne $c->start && !$has_base ) {
123                     print STDERR sprintf( "Adding path %s from %s -> %s\n",
124                         $sig.$c->ac_label, $source->name, $rdg->name );
125                     $c->add_path( $source, $rdg, $sig.$c->ac_label );
126                 }
127                 $source = $rdg;
128             }
129             $tradition->witness( $sig )->uncorrected_path( \@uncorrected );
130         }
131     }
132     # Delete readings that are no longer part of the graph.
133     # TODO think this is useless actually
134     foreach ( keys %$substitutions ) {
135         $tradition->collation->del_reading( $tradition->collation->reading( $_ ) );
136     }
137     $tradition->collation->calculate_ranks();
138 }
139
140 sub _clean_sequence {
141     my( $wit, $sequence ) = @_;
142     my @clean_sequence;
143     foreach my $rdg ( @$sequence ) {
144         if( $rdg =~ /^PH-(.*)$/ ) {
145             # It is a placeholder.  Keep it only if we need it.
146             my $app_id = $1;
147             if( exists $app_ac->{$wit}->{$app_id} ) {
148                 print STDERR "Retaining empty placeholder for $app_id\n";
149                 push( @clean_sequence, $rdg );
150             }
151         } else {
152             push( @clean_sequence, $rdg );
153         }
154     }
155     return @clean_sequence;
156 }
157
158 sub _replace_sequence {
159     my( $arr, $start, $end, @new ) = @_;
160     my( $start_idx, $end_idx );
161     foreach my $i ( 0 .. $#{$arr} ) {
162         $start_idx = $i if( $arr->[$i]->name eq $start );
163         if( $arr->[$i]->name eq $end ) {
164             $end_idx = $i;
165             last;
166         }
167     }
168     unless( $start_idx && $end_idx ) {
169         warn "Could not find start and end";
170         return;
171     }
172     my $length = $end_idx - $start_idx + 1;
173     splice( @$arr, $start_idx, $length, @new );
174 }
175
176 sub _return_rdg {
177     my( $rdg ) = @_;
178     # If we were passed a reading name, return the name.  If we were
179     # passed a reading object, return the object.
180     my $wantobj = ref( $rdg ) eq 'Text::Tradition::Collation::Reading';
181     my $real = $rdg;
182     if( exists $substitutions->{ $wantobj ? $rdg->name : $rdg } ) {
183         $real = $substitutions->{ $wantobj ? $rdg->name : $rdg };
184         $real = $real->name unless $wantobj;
185     }
186     return $real;
187 }
188
189 ## Recursive helper function to help us navigate through nested XML,
190 ## picking out the text.  $tradition is the tradition, needed for
191 ## making readings; $xn is the XML node currently being looked at,
192 ## $in_var is a flag to say that we are inside a variant, $ac is a
193 ## flag to say that we are inside an ante-correctionem reading, and
194 ## @cur_wits is the list of witnesses to which this XML node applies.
195 ## Returns the list of readings, if any, created on the run.
196
197 {
198     my @active_wits;
199     my $current_app;
200
201     sub _get_readings {
202         my( $tradition, $xn, $in_var, $ac, @cur_wits ) = @_;
203         @cur_wits = @active_wits unless $in_var;
204
205         my @new_readings;
206         if( $xn->nodeType == XML_TEXT_NODE ) {
207             # Some words, thus make some readings.
208             my $str = $xn->data;
209             return unless $str =~ /\S/; # skip whitespace-only text nodes
210             #print STDERR "Handling text node " . $str . "\n";
211             # Check that all the witnesses we have are active.
212             foreach my $c ( @cur_wits ) {
213                 warn "Could not find $c in active wits"
214                     unless grep { $c eq $_ } @active_wits;
215             }
216             $str =~ s/^\s+//;
217             my $final = $str =~ s/\s+$//;
218             foreach my $w ( split( /\s+/, $str ) ) {
219                 # For now, skip punctuation.
220                 next if $w !~ /[[:alnum:]]/;
221                 my $rdg = make_reading( $tradition->collation, $w );
222                 push( @new_readings, $rdg );
223                 unless( $in_var ) {
224                     $rdg->make_common;
225                 }
226                 foreach ( @cur_wits ) {
227                     warn "Empty wit!" unless $_;
228                     warn "Empty reading!" unless $rdg;
229                     push( @{$text->{$_}}, $rdg ) unless $ac;
230                 }
231             }
232         } elsif( $xn->nodeName eq 'w' ) {
233             # Everything in this tag is one word.  Also save any original XML ID.
234             #print STDERR "Handling word " . $xn->toString . "\n";
235             # Check that all the witnesses we have are active.
236             foreach my $c ( @cur_wits ) {
237                 warn "Could not find $c in active wits"
238                     unless grep { $c eq $_ } @active_wits;
239             }
240             my $xml_id = $xn->getAttribute( 'xml:id' );
241             my $rdg = make_reading( $tradition->collation, $xn->textContent, $xml_id );
242             push( @new_readings, $rdg );
243             unless( $in_var ) {
244                 $rdg->make_common;
245             }
246             foreach( @cur_wits ) {
247                 warn "Empty wit!" unless $_;
248                 warn "Empty reading!" unless $rdg;
249                 push( @{$text->{$_}}, $rdg ) unless $ac;
250             }
251         } elsif ( $xn->nodeName eq 'app' ) {
252             $current_app = $xn->getAttribute( 'xml:id' );
253             # print STDERR "Handling app $current_app\n";
254             # Keep the reading sets in this app.
255             my @sets;
256             # Recurse through all children (i.e. rdgs) for sets of words.
257             foreach ( $xn->childNodes ) {
258                 my @rdg_set = _get_readings( $tradition, $_, $in_var, $ac, @cur_wits );
259                 push( @sets, \@rdg_set ) if @rdg_set;
260             }
261             # Now collate these sets if we have more than one.
262             my $subs = collate_variants( $tradition->collation, @sets ) if @sets > 1;
263             map { $substitutions->{$_} = $subs->{$_} } keys %$subs;
264             # TODO Look through substitutions to see if we can make anything common now.
265             # Return the entire set of unique readings.
266             my %unique;
267             foreach my $s ( @sets ) {
268                 map { $unique{$_->name} = $_ } @$s;
269             }
270             push( @new_readings, values( %unique ) );
271             # Exit the current app.
272             $current_app = '';
273         } elsif ( $xn->nodeName eq 'lem' || $xn->nodeName eq 'rdg' ) {
274             # Alter the current witnesses and recurse.
275             #print STDERR "Handling reading for " . $xn->getAttribute( 'wit' ) . "\n";
276             $ac = $xn->getAttribute( 'type' ) && $xn->getAttribute( 'type' ) eq 'a.c.';
277             my @rdg_wits = get_sigla( $xn );
278             @rdg_wits = ( 'base' ) unless @rdg_wits;  # Allow for editorially-supplied readings
279             my @words;
280             foreach ( $xn->childNodes ) {
281                 my @rdg_set = _get_readings( $tradition, $_, 1, $ac, @rdg_wits );
282                 push( @words, @rdg_set ) if @rdg_set;
283             }
284             # If we have more than one word in a reading, it should become a segment.
285             # $tradition->collation->add_segment( @words ) if @words > 1;
286             
287             if( $ac ) {
288                 # Add the reading set to the a.c. readings.
289                 foreach ( @rdg_wits ) {
290                     $app_ac->{$_}->{$current_app} = \@words;
291                 }
292             } else {
293                 # Add the reading set to the app anchors for each witness
294                 # or put in placeholders for empty p.c. readings
295                 foreach ( @rdg_wits ) {
296                     my $start = @words ? $words[0]->name : "PH-$current_app";
297                     my $end = @words ? $words[-1]->name : "PH-$current_app";
298                     $app_anchors->{$current_app}->{$_}->{'start'} = $start;
299                     $app_anchors->{$current_app}->{$_}->{'end'} = $end;
300                     push( @{$text->{$_}}, $start ) unless @words;
301                 }
302             }
303             push( @new_readings, @words );
304         } elsif( $xn->nodeName eq 'witStart' ) {
305             # Add the relevant wit(s) to the active list.
306             #print STDERR "Handling witStart\n";
307             push( @active_wits, @cur_wits );
308         } elsif( $xn->nodeName eq 'witEnd' ) {
309             # Take the relevant wit(s) out of the list.
310             #print STDERR "Handling witEnd\n";
311             my $regexp = '^(' . join( '|', @cur_wits ) . ')$';
312             @active_wits = grep { $_ !~ /$regexp/ } @active_wits;
313         } elsif( $xn->nodeName eq 'witDetail' ) {
314             # Ignore these for now.
315             return;
316         } else {
317             # Recurse as if this tag weren't there.
318             #print STDERR "Recursing on tag " . $xn->nodeName . "\n";
319             foreach( $xn->childNodes ) {
320                 push( @new_readings, _get_readings( $tradition, $_, $in_var, $ac, @cur_wits ) );
321             }
322         }
323         return @new_readings;
324     }
325
326 }
327
328 # Helper to extract a list of witness sigla from a reading element.
329 sub get_sigla {
330     my( $rdg ) = @_;
331     # Cope if we have been handed a NodeList.  There is only
332     # one reading here.
333     if( ref( $rdg ) eq 'XML::LibXML::NodeList' ) {
334         $rdg = $rdg->shift;
335     }
336
337     my @wits;
338     if( ref( $rdg ) eq 'XML::LibXML::Element' ) {
339         my $witstr = $rdg->getAttribute( 'wit' );
340         $witstr =~ s/^\s+//;
341         $witstr =~ s/\s+$//;
342         @wits = split( /\s+/, $witstr );
343         map { $_ =~ s/^\#// } @wits;
344     }
345     return @wits;
346 }
347
348 # Helper with its counters to actually make the readings.
349 {
350     my $word_ctr = 0;
351     my %used_nodeids;
352
353     sub save_preexisting_nodeids {
354         foreach( @_ ) {
355             $used_nodeids{$_->getValue()} = 1;
356         }
357     }
358
359     sub make_reading {
360         my( $graph, $word, $xml_id ) = @_;
361         if( $xml_id ) {
362             if( exists $used_nodeids{$xml_id} ) {
363                 if( $used_nodeids{$xml_id} != 1 ) {
364                     warn "Already used assigned XML ID somewhere else!";
365                     $xml_id = undef;
366                 }
367             } else {
368                 warn "Undetected pre-existing XML ID";
369             }
370         }
371         if( !$xml_id ) {
372             until( $xml_id ) {
373                 my $try_id = 'w'.$word_ctr++;
374                 next if exists $used_nodeids{$try_id};
375                 $xml_id = $try_id;
376             }
377         }
378         my $rdg = $graph->add_reading( $xml_id );
379         $rdg->text( $word );
380         $used_nodeids{$xml_id} = $rdg;
381         return $rdg;
382     }
383 }
384
385 1;