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