Bugfix for superfluous a.c. witnesses
[scpubgit/stemmatology.git] / lib / Text / Tradition / Parser / TEI.pm
CommitLineData
f6066bac 1package Text::Tradition::Parser::TEI;
2
3use strict;
4use warnings;
910a0a6d 5use Text::Tradition::Parser::Util qw( collate_variants );
f6066bac 6use XML::LibXML;
7use XML::LibXML::XPathContext;
8
9=head1 NAME
10
11Text::Tradition::Parser::TEI
12
13=head1 DESCRIPTION
14
15Parser module for Text::Tradition, given a TEI parallel-segmentation
16file that describes a text and its variants.
17
18=head1 METHODS
19
20=over
21
22=item B<parse>
23
24parse( $tei_string );
25
26Takes an initialized tradition and a string containing the TEI;
27creates the appropriate nodes and edges on the graph, as well as
28the appropriate witness objects.
29
30=cut
31
910a0a6d 32my $text = {}; # Hash of arrays, one per eventual witness we find.
910a0a6d 33my $substitutions = {}; # Keep track of merged readings
34my $app_anchors = {}; # Track apparatus references
35my $app_ac = {}; # Save a.c. readings
eca16057 36my $app_count; # Keep track of how many apps we have
910a0a6d 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.
42my( $LISTWIT, $WITNESS, $TEXT, $W, $SEG, $APP, $RDG, $LEM )
43 = ( 'listWit', 'witness', 'text', 'w', 'seg', 'app', 'rdg', 'lem' );
44sub 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.
f6066bac 59sub 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();
f2b9605f 66 my $xpc = XML::LibXML::XPathContext->new( $tei );
910a0a6d 67 my $ns;
68 if( $tei->namespaceURI ) {
69 $ns = 'tei';
70 $xpc->registerNs( $ns, $tei->namespaceURI );
71 }
72 make_tagnames( $ns );
73
f6066bac 74 # Then get the witnesses and create the witness objects.
910a0a6d 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 );
f6066bac 79 }
910a0a6d 80 map { $text->{$_->sigil} = [] } $tradition->witnesses;
eca16057 81
910a0a6d 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
eca16057 86 # Count up how many apps we have.
87 my @apps = $xpc->findnodes( "//$APP" );
88 $app_count = scalar( @apps );
89
910a0a6d 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 }
78fab1cf 134 print STDERR "Adding a.c. version for witness $sig\n";
910a0a6d 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 }
7e450e44 143 $tradition->collation->calculate_ranks();
910a0a6d 144}
145
146sub _clean_sequence {
147 my( $wit, $sequence ) = @_;
148 my @clean_sequence;
149 foreach my $rdg ( @$sequence ) {
150 if( $rdg =~ /^PH-(.*)$/ ) {
151 # It is a placeholder. Keep it only if we need it.
152 my $app_id = $1;
78fab1cf 153 if( exists $app_ac->{$wit} &&
154 exists $app_ac->{$wit}->{$app_id} ) {
910a0a6d 155 print STDERR "Retaining empty placeholder for $app_id\n";
156 push( @clean_sequence, $rdg );
157 }
158 } else {
159 push( @clean_sequence, $rdg );
160 }
f6066bac 161 }
910a0a6d 162 return @clean_sequence;
163}
f6066bac 164
910a0a6d 165sub _replace_sequence {
166 my( $arr, $start, $end, @new ) = @_;
167 my( $start_idx, $end_idx );
168 foreach my $i ( 0 .. $#{$arr} ) {
169 $start_idx = $i if( $arr->[$i]->name eq $start );
170 if( $arr->[$i]->name eq $end ) {
171 $end_idx = $i;
172 last;
173 }
174 }
175 unless( $start_idx && $end_idx ) {
176 warn "Could not find start and end";
177 return;
f2b9605f 178 }
910a0a6d 179 my $length = $end_idx - $start_idx + 1;
180 splice( @$arr, $start_idx, $length, @new );
181}
f6066bac 182
910a0a6d 183sub _return_rdg {
184 my( $rdg ) = @_;
185 # If we were passed a reading name, return the name. If we were
186 # passed a reading object, return the object.
187 my $wantobj = ref( $rdg ) eq 'Text::Tradition::Collation::Reading';
188 my $real = $rdg;
189 if( exists $substitutions->{ $wantobj ? $rdg->name : $rdg } ) {
190 $real = $substitutions->{ $wantobj ? $rdg->name : $rdg };
191 $real = $real->name unless $wantobj;
192 }
193 return $real;
f6066bac 194}
195
910a0a6d 196## Recursive helper function to help us navigate through nested XML,
197## picking out the text. $tradition is the tradition, needed for
198## making readings; $xn is the XML node currently being looked at,
199## $in_var is a flag to say that we are inside a variant, $ac is a
200## flag to say that we are inside an ante-correctionem reading, and
201## @cur_wits is the list of witnesses to which this XML node applies.
202## Returns the list of readings, if any, created on the run.
203
204{
205 my @active_wits;
206 my $current_app;
eca16057 207 my $seen_apps;
910a0a6d 208
209 sub _get_readings {
210 my( $tradition, $xn, $in_var, $ac, @cur_wits ) = @_;
211 @cur_wits = @active_wits unless $in_var;
212
213 my @new_readings;
214 if( $xn->nodeType == XML_TEXT_NODE ) {
215 # Some words, thus make some readings.
216 my $str = $xn->data;
217 return unless $str =~ /\S/; # skip whitespace-only text nodes
218 #print STDERR "Handling text node " . $str . "\n";
219 # Check that all the witnesses we have are active.
220 foreach my $c ( @cur_wits ) {
221 warn "Could not find $c in active wits"
222 unless grep { $c eq $_ } @active_wits;
223 }
224 $str =~ s/^\s+//;
225 my $final = $str =~ s/\s+$//;
226 foreach my $w ( split( /\s+/, $str ) ) {
227 # For now, skip punctuation.
228 next if $w !~ /[[:alnum:]]/;
229 my $rdg = make_reading( $tradition->collation, $w );
230 push( @new_readings, $rdg );
231 unless( $in_var ) {
910a0a6d 232 $rdg->make_common;
233 }
234 foreach ( @cur_wits ) {
235 warn "Empty wit!" unless $_;
236 warn "Empty reading!" unless $rdg;
237 push( @{$text->{$_}}, $rdg ) unless $ac;
238 }
239 }
240 } elsif( $xn->nodeName eq 'w' ) {
241 # Everything in this tag is one word. Also save any original XML ID.
242 #print STDERR "Handling word " . $xn->toString . "\n";
243 # Check that all the witnesses we have are active.
244 foreach my $c ( @cur_wits ) {
245 warn "Could not find $c in active wits"
246 unless grep { $c eq $_ } @active_wits;
247 }
248 my $xml_id = $xn->getAttribute( 'xml:id' );
249 my $rdg = make_reading( $tradition->collation, $xn->textContent, $xml_id );
250 push( @new_readings, $rdg );
251 unless( $in_var ) {
910a0a6d 252 $rdg->make_common;
253 }
254 foreach( @cur_wits ) {
255 warn "Empty wit!" unless $_;
256 warn "Empty reading!" unless $rdg;
257 push( @{$text->{$_}}, $rdg ) unless $ac;
258 }
259 } elsif ( $xn->nodeName eq 'app' ) {
eca16057 260 $seen_apps++;
910a0a6d 261 $current_app = $xn->getAttribute( 'xml:id' );
262 # print STDERR "Handling app $current_app\n";
263 # Keep the reading sets in this app.
264 my @sets;
265 # Recurse through all children (i.e. rdgs) for sets of words.
266 foreach ( $xn->childNodes ) {
267 my @rdg_set = _get_readings( $tradition, $_, $in_var, $ac, @cur_wits );
268 push( @sets, \@rdg_set ) if @rdg_set;
269 }
270 # Now collate these sets if we have more than one.
271 my $subs = collate_variants( $tradition->collation, @sets ) if @sets > 1;
272 map { $substitutions->{$_} = $subs->{$_} } keys %$subs;
273 # TODO Look through substitutions to see if we can make anything common now.
274 # Return the entire set of unique readings.
275 my %unique;
276 foreach my $s ( @sets ) {
277 map { $unique{$_->name} = $_ } @$s;
278 }
279 push( @new_readings, values( %unique ) );
280 # Exit the current app.
281 $current_app = '';
282 } elsif ( $xn->nodeName eq 'lem' || $xn->nodeName eq 'rdg' ) {
283 # Alter the current witnesses and recurse.
284 #print STDERR "Handling reading for " . $xn->getAttribute( 'wit' ) . "\n";
285 $ac = $xn->getAttribute( 'type' ) && $xn->getAttribute( 'type' ) eq 'a.c.';
286 my @rdg_wits = get_sigla( $xn );
287 @rdg_wits = ( 'base' ) unless @rdg_wits; # Allow for editorially-supplied readings
288 my @words;
289 foreach ( $xn->childNodes ) {
290 my @rdg_set = _get_readings( $tradition, $_, 1, $ac, @rdg_wits );
291 push( @words, @rdg_set ) if @rdg_set;
292 }
293 # If we have more than one word in a reading, it should become a segment.
294 # $tradition->collation->add_segment( @words ) if @words > 1;
295
296 if( $ac ) {
297 # Add the reading set to the a.c. readings.
298 foreach ( @rdg_wits ) {
299 $app_ac->{$_}->{$current_app} = \@words;
300 }
301 } else {
302 # Add the reading set to the app anchors for each witness
303 # or put in placeholders for empty p.c. readings
304 foreach ( @rdg_wits ) {
305 my $start = @words ? $words[0]->name : "PH-$current_app";
306 my $end = @words ? $words[-1]->name : "PH-$current_app";
307 $app_anchors->{$current_app}->{$_}->{'start'} = $start;
308 $app_anchors->{$current_app}->{$_}->{'end'} = $end;
309 push( @{$text->{$_}}, $start ) unless @words;
310 }
311 }
312 push( @new_readings, @words );
313 } elsif( $xn->nodeName eq 'witStart' ) {
314 # Add the relevant wit(s) to the active list.
315 #print STDERR "Handling witStart\n";
316 push( @active_wits, @cur_wits );
317 } elsif( $xn->nodeName eq 'witEnd' ) {
318 # Take the relevant wit(s) out of the list.
319 #print STDERR "Handling witEnd\n";
320 my $regexp = '^(' . join( '|', @cur_wits ) . ')$';
321 @active_wits = grep { $_ !~ /$regexp/ } @active_wits;
eca16057 322 # Record a lacuna, unless this is the last app.
323 unless( $seen_apps == $app_count ) {
324 foreach my $i ( 0 .. $#cur_wits ) {
325 my $w = $cur_wits[$i];
326 my $l = $tradition->collation->add_lacuna( $current_app . "_$i" );
327 push( @{$text->{$w}}, $l );
328 }
329 }
910a0a6d 330 } elsif( $xn->nodeName eq 'witDetail' ) {
331 # Ignore these for now.
332 return;
333 } else {
334 # Recurse as if this tag weren't there.
335 #print STDERR "Recursing on tag " . $xn->nodeName . "\n";
336 foreach( $xn->childNodes ) {
337 push( @new_readings, _get_readings( $tradition, $_, $in_var, $ac, @cur_wits ) );
338 }
339 }
340 return @new_readings;
341 }
342
343}
344
345# Helper to extract a list of witness sigla from a reading element.
f6066bac 346sub get_sigla {
347 my( $rdg ) = @_;
348 # Cope if we have been handed a NodeList. There is only
349 # one reading here.
350 if( ref( $rdg ) eq 'XML::LibXML::NodeList' ) {
910a0a6d 351 $rdg = $rdg->shift;
f6066bac 352 }
353
354 my @wits;
355 if( ref( $rdg ) eq 'XML::LibXML::Element' ) {
910a0a6d 356 my $witstr = $rdg->getAttribute( 'wit' );
357 $witstr =~ s/^\s+//;
358 $witstr =~ s/\s+$//;
359 @wits = split( /\s+/, $witstr );
360 map { $_ =~ s/^\#// } @wits;
f6066bac 361 }
362 return @wits;
363}
364
910a0a6d 365# Helper with its counters to actually make the readings.
f2b9605f 366{
367 my $word_ctr = 0;
368 my %used_nodeids;
369
910a0a6d 370 sub save_preexisting_nodeids {
371 foreach( @_ ) {
372 $used_nodeids{$_->getValue()} = 1;
373 }
374 }
375
f2b9605f 376 sub make_reading {
910a0a6d 377 my( $graph, $word, $xml_id ) = @_;
378 if( $xml_id ) {
379 if( exists $used_nodeids{$xml_id} ) {
380 if( $used_nodeids{$xml_id} != 1 ) {
381 warn "Already used assigned XML ID somewhere else!";
382 $xml_id = undef;
383 }
384 } else {
385 warn "Undetected pre-existing XML ID";
386 }
387 }
388 if( !$xml_id ) {
389 until( $xml_id ) {
390 my $try_id = 'w'.$word_ctr++;
391 next if exists $used_nodeids{$try_id};
392 $xml_id = $try_id;
393 }
394 }
395 my $rdg = $graph->add_reading( $xml_id );
396 $rdg->text( $word );
397 $used_nodeids{$xml_id} = $rdg;
398 return $rdg;
f2b9605f 399 }
400}
401
f6066bac 4021;