cd66989e36b3b32ad444efbbbd5ba00ebb8fe639
[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     # TODO Try as a string, then try as a filename.
65     my $doc = $parser->parse_string( $xml_str );
66     my $tei = $doc->documentElement();
67     my $xpc = XML::LibXML::XPathContext->new( $tei );
68     my $ns;
69     if( $tei->namespaceURI ) {
70         $ns = 'tei';
71         $xpc->registerNs( $ns, $tei->namespaceURI );
72     }
73     make_tagnames( $ns );
74
75     # Then get the witnesses and create the witness objects.
76     foreach my $wit_el ( $xpc->findnodes( "//$LISTWIT/$WITNESS" ) ) {
77         my $sig = $wit_el->getAttribute( 'xml:id' );
78         my $source = $wit_el->toString();
79         $tradition->add_witness( sigil => $sig, source => $source );
80     }
81     map { $text->{$_->sigil} = [] } $tradition->witnesses;
82
83     # Look for all word/seg node IDs and note their pre-existence.
84     my @attrs = $xpc->findnodes( "//$W|$SEG/attribute::xml:id" );
85     save_preexisting_nodeids( @attrs );
86
87     # Count up how many apps we have.
88     my @apps = $xpc->findnodes( "//$APP" );
89     $app_count = scalar( @apps );
90
91     # Now go through the children of the text element and pull out the
92     # actual text.
93     foreach my $xml_el ( $xpc->findnodes( "//$TEXT" ) ) {
94         foreach my $xn ( $xml_el->childNodes ) {
95             _get_readings( $tradition, $xn );
96         }
97     }
98     # Our $text global now has lists of readings, one per witness.
99     # Join them up.
100     my $c = $tradition->collation;
101     foreach my $sig ( keys %$text ) {
102         next if $sig eq 'base';  # Skip base text readings with no witnesses.
103         # Determine the list of readings for 
104         my $sequence = $text->{$sig};
105         my @real_sequence = ( $c->start );
106         push( @$sequence, $c->end );
107         my $source = $c->start;
108         foreach( _clean_sequence( $sig, $sequence ) ) {
109             my $rdg = _return_rdg( $_ );
110             push( @real_sequence, $rdg );
111             $c->add_path( $source, $rdg, $sig );
112             $source = $rdg;
113         }
114         $tradition->witness( $sig )->path( \@real_sequence );
115         # See if we need to make an a.c. version of the witness.
116         if( exists $app_ac->{$sig} ) {
117             my @uncorrected;
118             push( @uncorrected, @real_sequence );
119             foreach my $app ( keys %{$app_ac->{$sig}} ) {
120                 my $start = _return_rdg( $app_anchors->{$app}->{$sig}->{'start'} ); 
121                 my $end = _return_rdg( $app_anchors->{$app}->{$sig}->{'end'} );
122                 my @new = map { _return_rdg( $_ ) } @{$app_ac->{$sig}->{$app}};
123                 _replace_sequence( \@uncorrected, $start, $end, @new );
124             }
125             my $source = $c->start;
126             foreach my $rdg ( @uncorrected ) {
127                 my $has_base = grep { $_->label eq $sig } $source->edges_to( $rdg );
128                 if( $rdg ne $c->start && !$has_base ) {
129                     print STDERR sprintf( "Adding path %s from %s -> %s\n",
130                         $sig.$c->ac_label, $source->name, $rdg->name );
131                     $c->add_path( $source, $rdg, $sig.$c->ac_label );
132                 }
133                 $source = $rdg;
134             }
135             print STDERR "Adding a.c. version for witness $sig\n";
136             $tradition->witness( $sig )->uncorrected_path( \@uncorrected );
137         }
138     }
139     # Delete readings that are no longer part of the graph.
140     # TODO think this is useless actually
141     foreach ( keys %$substitutions ) {
142         $tradition->collation->del_reading( $tradition->collation->reading( $_ ) );
143     }
144     
145     # Calculate the ranks and flatten the graph based on the results.
146     $tradition->collation->calculate_ranks();
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 = @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 "Could not find $c in active wits"
226                     unless grep { $c eq $_ } @active_wits;
227             }
228             $str =~ s/^\s+//;
229             my $final = $str =~ s/\s+$//;
230             foreach my $w ( split( /\s+/, $str ) ) {
231                 # For now, skip punctuation.
232                 next if $w !~ /[[:alnum:]]/;
233                 my $rdg = make_reading( $tradition->collation, $w );
234                 push( @new_readings, $rdg );
235                 unless( $in_var ) {
236                     $rdg->make_common;
237                 }
238                 foreach ( @cur_wits ) {
239                     warn "Empty wit!" unless $_;
240                     warn "Empty reading!" unless $rdg;
241                     push( @{$text->{$_}}, $rdg ) unless $ac;
242                 }
243             }
244         } elsif( $xn->nodeName eq 'w' ) {
245             # Everything in this tag is one word.  Also save any original XML ID.
246             #print STDERR "Handling word " . $xn->toString . "\n";
247             # Check that all the witnesses we have are active.
248             foreach my $c ( @cur_wits ) {
249                 warn "Could not find $c in active wits"
250                     unless grep { $c eq $_ } @active_wits;
251             }
252             my $xml_id = $xn->getAttribute( 'xml:id' );
253             my $rdg = make_reading( $tradition->collation, $xn->textContent, $xml_id );
254             push( @new_readings, $rdg );
255             unless( $in_var ) {
256                 $rdg->make_common;
257             }
258             foreach( @cur_wits ) {
259                 warn "Empty wit!" unless $_;
260                 warn "Empty reading!" unless $rdg;
261                 push( @{$text->{$_}}, $rdg ) unless $ac;
262             }
263         } elsif ( $xn->nodeName eq 'app' ) {
264             $seen_apps++;
265             $current_app = $xn->getAttribute( 'xml:id' );
266             # print STDERR "Handling app $current_app\n";
267             # Keep the reading sets in this app.
268             my @sets;
269             # Recurse through all children (i.e. rdgs) for sets of words.
270             foreach ( $xn->childNodes ) {
271                 my @rdg_set = _get_readings( $tradition, $_, $in_var, $ac, @cur_wits );
272                 push( @sets, \@rdg_set ) if @rdg_set;
273             }
274             # Now collate these sets if we have more than one.
275             my $subs = collate_variants( $tradition->collation, @sets ) if @sets > 1;
276             map { $substitutions->{$_} = $subs->{$_} } keys %$subs;
277             # TODO Look through substitutions to see if we can make anything common now.
278             # Return the entire set of unique readings.
279             my %unique;
280             foreach my $s ( @sets ) {
281                 map { $unique{$_->name} = $_ } @$s;
282             }
283             push( @new_readings, values( %unique ) );
284             # Exit the current app.
285             $current_app = '';
286         } elsif ( $xn->nodeName eq 'lem' || $xn->nodeName eq 'rdg' ) {
287             # Alter the current witnesses and recurse.
288             #print STDERR "Handling reading for " . $xn->getAttribute( 'wit' ) . "\n";
289             $ac = $xn->getAttribute( 'type' ) && $xn->getAttribute( 'type' ) eq 'a.c.';
290             my @rdg_wits = get_sigla( $xn );
291             @rdg_wits = ( 'base' ) unless @rdg_wits;  # Allow for editorially-supplied readings
292             my @words;
293             foreach ( $xn->childNodes ) {
294                 my @rdg_set = _get_readings( $tradition, $_, 1, $ac, @rdg_wits );
295                 push( @words, @rdg_set ) if @rdg_set;
296             }
297             # If we have more than one word in a reading, it should become a segment.
298             # $tradition->collation->add_segment( @words ) if @words > 1;
299             
300             if( $ac ) {
301                 # Add the reading set to the a.c. readings.
302                 foreach ( @rdg_wits ) {
303                     $app_ac->{$_}->{$current_app} = \@words;
304                 }
305             } else {
306                 # Add the reading set to the app anchors for each witness
307                 # or put in placeholders for empty p.c. readings
308                 foreach ( @rdg_wits ) {
309                     my $start = @words ? $words[0]->name : "PH-$current_app";
310                     my $end = @words ? $words[-1]->name : "PH-$current_app";
311                     $app_anchors->{$current_app}->{$_}->{'start'} = $start;
312                     $app_anchors->{$current_app}->{$_}->{'end'} = $end;
313                     push( @{$text->{$_}}, $start ) unless @words;
314                 }
315             }
316             push( @new_readings, @words );
317         } elsif( $xn->nodeName eq 'witStart' ) {
318             # Add the relevant wit(s) to the active list.
319             #print STDERR "Handling witStart\n";
320             push( @active_wits, @cur_wits );
321         } elsif( $xn->nodeName eq 'witEnd' ) {
322             # Take the relevant wit(s) out of the list.
323             #print STDERR "Handling witEnd\n";
324             my $regexp = '^(' . join( '|', @cur_wits ) . ')$';
325             @active_wits = grep { $_ !~ /$regexp/ } @active_wits;
326             # Record a lacuna, unless this is the last app.
327             unless( $seen_apps == $app_count ) {
328                 foreach my $i ( 0 .. $#cur_wits ) {
329                     my $w = $cur_wits[$i];
330                     my $l = $tradition->collation->add_lacuna( $current_app . "_$i" );
331                     push( @{$text->{$w}}, $l );
332                 }
333             }
334         } elsif( $xn->nodeName eq 'witDetail' ) {
335             # Ignore these for now.
336             return;
337         } else {
338             # Recurse as if this tag weren't there.
339             #print STDERR "Recursing on tag " . $xn->nodeName . "\n";
340             foreach( $xn->childNodes ) {
341                 push( @new_readings, _get_readings( $tradition, $_, $in_var, $ac, @cur_wits ) );
342             }
343         }
344         return @new_readings;
345     }
346
347 }
348
349 # Helper to extract a list of witness sigla from a reading element.
350 sub get_sigla {
351     my( $rdg ) = @_;
352     # Cope if we have been handed a NodeList.  There is only
353     # one reading here.
354     if( ref( $rdg ) eq 'XML::LibXML::NodeList' ) {
355         $rdg = $rdg->shift;
356     }
357
358     my @wits;
359     if( ref( $rdg ) eq 'XML::LibXML::Element' ) {
360         my $witstr = $rdg->getAttribute( 'wit' );
361         $witstr =~ s/^\s+//;
362         $witstr =~ s/\s+$//;
363         @wits = split( /\s+/, $witstr );
364         map { $_ =~ s/^\#// } @wits;
365     }
366     return @wits;
367 }
368
369 # Helper with its counters to actually make the readings.
370 {
371     my $word_ctr = 0;
372     my %used_nodeids;
373
374     sub save_preexisting_nodeids {
375         foreach( @_ ) {
376             $used_nodeids{$_->getValue()} = 1;
377         }
378     }
379
380     sub make_reading {
381         my( $graph, $word, $xml_id ) = @_;
382         if( $xml_id ) {
383             if( exists $used_nodeids{$xml_id} ) {
384                 if( $used_nodeids{$xml_id} != 1 ) {
385                     warn "Already used assigned XML ID somewhere else!";
386                     $xml_id = undef;
387                 }
388             } else {
389                 warn "Undetected pre-existing XML ID";
390             }
391         }
392         if( !$xml_id ) {
393             until( $xml_id ) {
394                 my $try_id = 'w'.$word_ctr++;
395                 next if exists $used_nodeids{$try_id};
396                 $xml_id = $try_id;
397             }
398         }
399         my $rdg = $graph->add_reading( $xml_id );
400         $rdg->text( $word );
401         $used_nodeids{$xml_id} = $rdg;
402         return $rdg;
403     }
404 }
405
406 1;