add lacunae properly at start of TEI parsing
[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 my $app_count;          # Keep track of how many apps we have
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     map { $text->{$_->sigil} = [] } $tradition->witnesses;
81
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     # Count up how many apps we have.
87     my @apps = $xpc->findnodes( "//$APP" );
88     $app_count = scalar( @apps );
89
90     # Now go through the children of the text element and pull out the
91     # actual text.
92     foreach my $xml_el ( $xpc->findnodes( "//$TEXT" ) ) {
93         foreach my $xn ( $xml_el->childNodes ) {
94             _get_readings( $tradition, $xn );
95         }
96     }
97     # Our $text global now has lists of readings, one per witness.
98     # Join them up.
99     my $c = $tradition->collation;
100     foreach my $sig ( keys %$text ) {
101         next if $sig eq 'base';  # Skip base text readings with no witnesses.
102         # Determine the list of readings for 
103         my $sequence = $text->{$sig};
104         my @real_sequence = ( $c->start );
105         push( @$sequence, $c->end );
106         my $source = $c->start;
107         foreach( _clean_sequence( $sig, $sequence ) ) {
108             my $rdg = _return_rdg( $_ );
109             push( @real_sequence, $rdg );
110             $c->add_path( $source, $rdg, $sig );
111             $source = $rdg;
112         }
113         $tradition->witness( $sig )->path( \@real_sequence );
114         # See if we need to make an a.c. version of the witness.
115         if( exists $app_ac->{$sig} ) {
116             my @uncorrected;
117             push( @uncorrected, @real_sequence );
118             foreach my $app ( keys %{$app_ac->{$sig}} ) {
119                 my $start = _return_rdg( $app_anchors->{$app}->{$sig}->{'start'} ); 
120                 my $end = _return_rdg( $app_anchors->{$app}->{$sig}->{'end'} );
121                 my @new = map { _return_rdg( $_ ) } @{$app_ac->{$sig}->{$app}};
122                 _replace_sequence( \@uncorrected, $start, $end, @new );
123             }
124             my $source = $c->start;
125             foreach my $rdg ( @uncorrected ) {
126                 my $has_base = grep { $_->label eq $sig } $source->edges_to( $rdg );
127                 if( $rdg ne $c->start && !$has_base ) {
128                     print STDERR sprintf( "Adding path %s from %s -> %s\n",
129                         $sig.$c->ac_label, $source->name, $rdg->name );
130                     $c->add_path( $source, $rdg, $sig.$c->ac_label );
131                 }
132                 $source = $rdg;
133             }
134             print STDERR "Adding a.c. version for witness $sig\n";
135             $tradition->witness( $sig )->uncorrected_path( \@uncorrected );
136         }
137     }
138     # Delete readings that are no longer part of the graph.
139     # TODO think this is useless actually
140     foreach ( keys %$substitutions ) {
141         $tradition->collation->del_reading( $tradition->collation->reading( $_ ) );
142     }
143     $tradition->collation->calculate_ranks();
144     
145     # Now that we have ranks, see if we have distinct nodes with identical
146     # text and identical rank that can be merged.
147     $tradition->collation->flatten_ranks();
148 }
149
150 sub _clean_sequence {
151     my( $wit, $sequence ) = @_;
152     my @clean_sequence;
153     foreach my $rdg ( @$sequence ) {
154         if( $rdg =~ /^PH-(.*)$/ ) {
155             # It is a placeholder.  Keep it only if we need it.
156             my $app_id = $1;
157             if( exists $app_ac->{$wit} &&
158                 exists $app_ac->{$wit}->{$app_id} ) {
159                 print STDERR "Retaining empty placeholder for $app_id\n";
160                 push( @clean_sequence, $rdg );
161             }
162         } else {
163             push( @clean_sequence, $rdg );
164         }
165     }
166     return @clean_sequence;
167 }
168
169 sub _replace_sequence {
170     my( $arr, $start, $end, @new ) = @_;
171     my( $start_idx, $end_idx );
172     foreach my $i ( 0 .. $#{$arr} ) {
173         $start_idx = $i if( $arr->[$i]->name eq $start );
174         if( $arr->[$i]->name eq $end ) {
175             $end_idx = $i;
176             last;
177         }
178     }
179     unless( $start_idx && $end_idx ) {
180         warn "Could not find start and end";
181         return;
182     }
183     my $length = $end_idx - $start_idx + 1;
184     splice( @$arr, $start_idx, $length, @new );
185 }
186
187 sub _return_rdg {
188     my( $rdg ) = @_;
189     # If we were passed a reading name, return the name.  If we were
190     # passed a reading object, return the object.
191     my $wantobj = ref( $rdg ) eq 'Text::Tradition::Collation::Reading';
192     my $real = $rdg;
193     if( exists $substitutions->{ $wantobj ? $rdg->name : $rdg } ) {
194         $real = $substitutions->{ $wantobj ? $rdg->name : $rdg };
195         $real = $real->name unless $wantobj;
196     }
197     return $real;
198 }
199
200 ## Recursive helper function to help us navigate through nested XML,
201 ## picking out the text.  $tradition is the tradition, needed for
202 ## making readings; $xn is the XML node currently being looked at,
203 ## $in_var is a flag to say that we are inside a variant, $ac is a
204 ## flag to say that we are inside an ante-correctionem reading, and
205 ## @cur_wits is the list of witnesses to which this XML node applies.
206 ## Returns the list of readings, if any, created on the run.
207
208 {
209     my %active_wits;
210     my $current_app;
211     my $seen_apps;
212
213     sub _get_readings {
214         my( $tradition, $xn, $in_var, $ac, @cur_wits ) = @_;
215         @cur_wits = grep { $active_wits{$_} } keys %active_wits unless $in_var;
216
217         my @new_readings;
218         if( $xn->nodeType == XML_TEXT_NODE ) {
219             # Some words, thus make some readings.
220             my $str = $xn->data;
221             return unless $str =~ /\S/; # skip whitespace-only text nodes
222             #print STDERR "Handling text node " . $str . "\n";
223             # Check that all the witnesses we have are active.
224             foreach my $c ( @cur_wits ) {
225                 warn "$c is not among active wits" unless $active_wits{$c};
226             }
227             $str =~ s/^\s+//;
228             my $final = $str =~ s/\s+$//;
229             foreach my $w ( split( /\s+/, $str ) ) {
230                 # For now, skip punctuation.
231                 next if $w !~ /[[:alnum:]]/;
232                 my $rdg = make_reading( $tradition->collation, $w );
233                 push( @new_readings, $rdg );
234                 unless( $in_var ) {
235                     $rdg->make_common;
236                 }
237                 foreach ( @cur_wits ) {
238                     warn "Empty wit!" unless $_;
239                     warn "Empty reading!" unless $rdg;
240                     push( @{$text->{$_}}, $rdg ) unless $ac;
241                 }
242             }
243         } elsif( $xn->nodeName eq 'w' ) {
244             # Everything in this tag is one word.  Also save any original XML ID.
245             #print STDERR "Handling word " . $xn->toString . "\n";
246             # Check that all the witnesses we have are active.
247             foreach my $c ( @cur_wits ) {
248                 warn "$c is not among active wits" unless $active_wits{$c};
249             }
250             my $xml_id = $xn->getAttribute( 'xml:id' );
251             my $rdg = make_reading( $tradition->collation, $xn->textContent, $xml_id );
252             push( @new_readings, $rdg );
253             unless( $in_var ) {
254                 $rdg->make_common;
255             }
256             foreach( @cur_wits ) {
257                 warn "Empty wit!" unless $_;
258                 warn "Empty reading!" unless $rdg;
259                 push( @{$text->{$_}}, $rdg ) unless $ac;
260             }
261         } elsif ( $xn->nodeName eq 'app' ) {
262             $seen_apps++;
263             $current_app = $xn->getAttribute( 'xml:id' );
264             # print STDERR "Handling app $current_app\n";
265             # Keep the reading sets in this app.
266             my @sets;
267             # Recurse through all children (i.e. rdgs) for sets of words.
268             foreach ( $xn->childNodes ) {
269                 my @rdg_set = _get_readings( $tradition, $_, $in_var, $ac, @cur_wits );
270                 push( @sets, \@rdg_set ) if @rdg_set;
271             }
272             # Now collate these sets if we have more than one.
273             my $subs = collate_variants( $tradition->collation, @sets ) if @sets > 1;
274             map { $substitutions->{$_} = $subs->{$_} } keys %$subs;
275             # TODO Look through substitutions to see if we can make anything common now.
276             # Return the entire set of unique readings.
277             my %unique;
278             foreach my $s ( @sets ) {
279                 map { $unique{$_->name} = $_ } @$s;
280             }
281             push( @new_readings, values( %unique ) );
282             # Exit the current app.
283             $current_app = '';
284         } elsif ( $xn->nodeName eq 'lem' || $xn->nodeName eq 'rdg' ) {
285             # Alter the current witnesses and recurse.
286             #print STDERR "Handling reading for " . $xn->getAttribute( 'wit' ) . "\n";
287             # TODO handle p.c. and s.l. designations too
288             $ac = $xn->getAttribute( 'type' ) && $xn->getAttribute( 'type' ) eq 'a.c.';
289             my @rdg_wits = get_sigla( $xn );
290             @rdg_wits = ( 'base' ) unless @rdg_wits;  # Allow for editorially-supplied readings
291             my @words;
292             foreach ( $xn->childNodes ) {
293                 my @rdg_set = _get_readings( $tradition, $_, 1, $ac, @rdg_wits );
294                 push( @words, @rdg_set ) if @rdg_set;
295             }
296             # If we have more than one word in a reading, it should become a segment.
297             # $tradition->collation->add_segment( @words ) if @words > 1;
298             
299             if( $ac ) {
300                 # Add the reading set to the a.c. readings.
301                 foreach ( @rdg_wits ) {
302                     $app_ac->{$_}->{$current_app} = \@words;
303                 }
304             } else {
305                 # Add the reading set to the app anchors for each witness
306                 # or put in placeholders for empty p.c. readings
307                 foreach ( @rdg_wits ) {
308                     my $start = @words ? $words[0]->name : "PH-$current_app";
309                     my $end = @words ? $words[-1]->name : "PH-$current_app";
310                     $app_anchors->{$current_app}->{$_}->{'start'} = $start;
311                     $app_anchors->{$current_app}->{$_}->{'end'} = $end;
312                     push( @{$text->{$_}}, $start ) unless @words;
313                 }
314             }
315             push( @new_readings, @words );
316         } elsif( $xn->nodeName eq 'witStart' ) {
317             # Add the relevant wit(s) to the active list.
318             #print STDERR "Handling witStart\n";
319             map { $active_wits{$_} = 1 } @cur_wits;
320             # Record a lacuna in all non-active witnesses if this is
321             # the first app. Get the full list from $text.
322             if( $seen_apps == 1 ) {
323                 my $i = 0;
324                 foreach my $sig ( keys %$text ) {
325                     next if $active_wits{$sig};
326                     my $l = $tradition->collation->add_lacuna( $current_app . "_$i" );
327                     $i++;
328                     push( @{$text->{$sig}}, $l );
329                 }
330             }
331         } elsif( $xn->nodeName eq 'witEnd' ) {
332             # Take the relevant wit(s) out of the list.
333             #print STDERR "Handling witEnd\n";
334             map { $active_wits{$_} = undef } @cur_wits;
335             # Record a lacuna, unless this is the last app.
336             unless( $seen_apps == $app_count ) {
337                 foreach my $i ( 0 .. $#cur_wits ) {
338                     my $w = $cur_wits[$i];
339                     my $l = $tradition->collation->add_lacuna( $current_app . "_$i" );
340                     push( @{$text->{$w}}, $l );
341                 }
342             }
343         } elsif( $xn->nodeName eq 'witDetail' ) {
344             # Ignore these for now.
345             return;
346         } else {
347             # Recurse as if this tag weren't there.
348             #print STDERR "Recursing on tag " . $xn->nodeName . "\n";
349             foreach( $xn->childNodes ) {
350                 push( @new_readings, _get_readings( $tradition, $_, $in_var, $ac, @cur_wits ) );
351             }
352         }
353         return @new_readings;
354     }
355
356 }
357
358 # Helper to extract a list of witness sigla from a reading element.
359 sub get_sigla {
360     my( $rdg ) = @_;
361     # Cope if we have been handed a NodeList.  There is only
362     # one reading here.
363     if( ref( $rdg ) eq 'XML::LibXML::NodeList' ) {
364         $rdg = $rdg->shift;
365     }
366
367     my @wits;
368     if( ref( $rdg ) eq 'XML::LibXML::Element' ) {
369         my $witstr = $rdg->getAttribute( 'wit' );
370         $witstr =~ s/^\s+//;
371         $witstr =~ s/\s+$//;
372         @wits = split( /\s+/, $witstr );
373         map { $_ =~ s/^\#// } @wits;
374     }
375     return @wits;
376 }
377
378 # Helper with its counters to actually make the readings.
379 {
380     my $word_ctr = 0;
381     my %used_nodeids;
382
383     sub save_preexisting_nodeids {
384         foreach( @_ ) {
385             $used_nodeids{$_->getValue()} = 1;
386         }
387     }
388
389     sub make_reading {
390         my( $graph, $word, $xml_id ) = @_;
391         if( $xml_id ) {
392             if( exists $used_nodeids{$xml_id} ) {
393                 if( $used_nodeids{$xml_id} != 1 ) {
394                     warn "Already used assigned XML ID somewhere else!";
395                     $xml_id = undef;
396                 }
397             } else {
398                 warn "Undetected pre-existing XML ID";
399             }
400         }
401         if( !$xml_id ) {
402             until( $xml_id ) {
403                 my $try_id = 'w'.$word_ctr++;
404                 next if exists $used_nodeids{$try_id};
405                 $xml_id = $try_id;
406             }
407         }
408         my $rdg = $graph->add_reading( $xml_id );
409         $rdg->text( $word );
410         $used_nodeids{$xml_id} = $rdg;
411         return $rdg;
412     }
413 }
414
415 1;