1 package Text::Tradition::Parser::TEI;
5 use Text::Tradition::Parser::Util qw( collate_variants );
7 use XML::LibXML::XPathContext;
11 Text::Tradition::Parser::TEI
15 Parser module for Text::Tradition, given a TEI parallel-segmentation
16 file that describes a text and its variants.
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.
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
38 # Create the package variables for tag names.
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' );
47 $LISTWIT = "$ns:$LISTWIT";
48 $WITNESS = "$ns:$WITNESS";
60 my( $tradition, $xml_str ) = @_;
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 );
68 if( $tei->namespaceURI ) {
70 $xpc->registerNs( $ns, $tei->namespaceURI );
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 );
80 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 );
86 # Count up how many apps we have.
87 my @apps = $xpc->findnodes( "//$APP" );
88 $app_count = scalar( @apps );
90 # Now go through the children of the text element and pull out the
92 foreach my $xml_el ( $xpc->findnodes( "//$TEXT" ) ) {
93 foreach my $xn ( $xml_el->childNodes ) {
94 _get_readings( $tradition, $xn );
97 # Our $text global now has lists of readings, one per witness.
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 );
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} ) {
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 );
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 );
134 $tradition->witness( $sig )->uncorrected_path( \@uncorrected );
137 # Delete readings that are no longer part of the graph.
138 # TODO think this is useless actually
139 foreach ( keys %$substitutions ) {
140 $tradition->collation->del_reading( $tradition->collation->reading( $_ ) );
142 $tradition->collation->calculate_ranks();
145 sub _clean_sequence {
146 my( $wit, $sequence ) = @_;
148 foreach my $rdg ( @$sequence ) {
149 if( $rdg =~ /^PH-(.*)$/ ) {
150 # It is a placeholder. Keep it only if we need it.
152 if( exists $app_ac->{$wit}->{$app_id} ) {
153 print STDERR "Retaining empty placeholder for $app_id\n";
154 push( @clean_sequence, $rdg );
157 push( @clean_sequence, $rdg );
160 return @clean_sequence;
163 sub _replace_sequence {
164 my( $arr, $start, $end, @new ) = @_;
165 my( $start_idx, $end_idx );
166 foreach my $i ( 0 .. $#{$arr} ) {
167 $start_idx = $i if( $arr->[$i]->name eq $start );
168 if( $arr->[$i]->name eq $end ) {
173 unless( $start_idx && $end_idx ) {
174 warn "Could not find start and end";
177 my $length = $end_idx - $start_idx + 1;
178 splice( @$arr, $start_idx, $length, @new );
183 # If we were passed a reading name, return the name. If we were
184 # passed a reading object, return the object.
185 my $wantobj = ref( $rdg ) eq 'Text::Tradition::Collation::Reading';
187 if( exists $substitutions->{ $wantobj ? $rdg->name : $rdg } ) {
188 $real = $substitutions->{ $wantobj ? $rdg->name : $rdg };
189 $real = $real->name unless $wantobj;
194 ## Recursive helper function to help us navigate through nested XML,
195 ## picking out the text. $tradition is the tradition, needed for
196 ## making readings; $xn is the XML node currently being looked at,
197 ## $in_var is a flag to say that we are inside a variant, $ac is a
198 ## flag to say that we are inside an ante-correctionem reading, and
199 ## @cur_wits is the list of witnesses to which this XML node applies.
200 ## Returns the list of readings, if any, created on the run.
208 my( $tradition, $xn, $in_var, $ac, @cur_wits ) = @_;
209 @cur_wits = @active_wits unless $in_var;
212 if( $xn->nodeType == XML_TEXT_NODE ) {
213 # Some words, thus make some readings.
215 return unless $str =~ /\S/; # skip whitespace-only text nodes
216 #print STDERR "Handling text node " . $str . "\n";
217 # Check that all the witnesses we have are active.
218 foreach my $c ( @cur_wits ) {
219 warn "Could not find $c in active wits"
220 unless grep { $c eq $_ } @active_wits;
223 my $final = $str =~ s/\s+$//;
224 foreach my $w ( split( /\s+/, $str ) ) {
225 # For now, skip punctuation.
226 next if $w !~ /[[:alnum:]]/;
227 my $rdg = make_reading( $tradition->collation, $w );
228 push( @new_readings, $rdg );
232 foreach ( @cur_wits ) {
233 warn "Empty wit!" unless $_;
234 warn "Empty reading!" unless $rdg;
235 push( @{$text->{$_}}, $rdg ) unless $ac;
238 } elsif( $xn->nodeName eq 'w' ) {
239 # Everything in this tag is one word. Also save any original XML ID.
240 #print STDERR "Handling word " . $xn->toString . "\n";
241 # Check that all the witnesses we have are active.
242 foreach my $c ( @cur_wits ) {
243 warn "Could not find $c in active wits"
244 unless grep { $c eq $_ } @active_wits;
246 my $xml_id = $xn->getAttribute( 'xml:id' );
247 my $rdg = make_reading( $tradition->collation, $xn->textContent, $xml_id );
248 push( @new_readings, $rdg );
252 foreach( @cur_wits ) {
253 warn "Empty wit!" unless $_;
254 warn "Empty reading!" unless $rdg;
255 push( @{$text->{$_}}, $rdg ) unless $ac;
257 } elsif ( $xn->nodeName eq 'app' ) {
259 $current_app = $xn->getAttribute( 'xml:id' );
260 # print STDERR "Handling app $current_app\n";
261 # Keep the reading sets in this app.
263 # Recurse through all children (i.e. rdgs) for sets of words.
264 foreach ( $xn->childNodes ) {
265 my @rdg_set = _get_readings( $tradition, $_, $in_var, $ac, @cur_wits );
266 push( @sets, \@rdg_set ) if @rdg_set;
268 # Now collate these sets if we have more than one.
269 my $subs = collate_variants( $tradition->collation, @sets ) if @sets > 1;
270 map { $substitutions->{$_} = $subs->{$_} } keys %$subs;
271 # TODO Look through substitutions to see if we can make anything common now.
272 # Return the entire set of unique readings.
274 foreach my $s ( @sets ) {
275 map { $unique{$_->name} = $_ } @$s;
277 push( @new_readings, values( %unique ) );
278 # Exit the current app.
280 } elsif ( $xn->nodeName eq 'lem' || $xn->nodeName eq 'rdg' ) {
281 # Alter the current witnesses and recurse.
282 #print STDERR "Handling reading for " . $xn->getAttribute( 'wit' ) . "\n";
283 $ac = $xn->getAttribute( 'type' ) && $xn->getAttribute( 'type' ) eq 'a.c.';
284 my @rdg_wits = get_sigla( $xn );
285 @rdg_wits = ( 'base' ) unless @rdg_wits; # Allow for editorially-supplied readings
287 foreach ( $xn->childNodes ) {
288 my @rdg_set = _get_readings( $tradition, $_, 1, $ac, @rdg_wits );
289 push( @words, @rdg_set ) if @rdg_set;
291 # If we have more than one word in a reading, it should become a segment.
292 # $tradition->collation->add_segment( @words ) if @words > 1;
295 # Add the reading set to the a.c. readings.
296 foreach ( @rdg_wits ) {
297 $app_ac->{$_}->{$current_app} = \@words;
300 # Add the reading set to the app anchors for each witness
301 # or put in placeholders for empty p.c. readings
302 foreach ( @rdg_wits ) {
303 my $start = @words ? $words[0]->name : "PH-$current_app";
304 my $end = @words ? $words[-1]->name : "PH-$current_app";
305 $app_anchors->{$current_app}->{$_}->{'start'} = $start;
306 $app_anchors->{$current_app}->{$_}->{'end'} = $end;
307 push( @{$text->{$_}}, $start ) unless @words;
310 push( @new_readings, @words );
311 } elsif( $xn->nodeName eq 'witStart' ) {
312 # Add the relevant wit(s) to the active list.
313 #print STDERR "Handling witStart\n";
314 push( @active_wits, @cur_wits );
315 } elsif( $xn->nodeName eq 'witEnd' ) {
316 # Take the relevant wit(s) out of the list.
317 #print STDERR "Handling witEnd\n";
318 my $regexp = '^(' . join( '|', @cur_wits ) . ')$';
319 @active_wits = grep { $_ !~ /$regexp/ } @active_wits;
320 # Record a lacuna, unless this is the last app.
321 unless( $seen_apps == $app_count ) {
322 foreach my $i ( 0 .. $#cur_wits ) {
323 my $w = $cur_wits[$i];
324 my $l = $tradition->collation->add_lacuna( $current_app . "_$i" );
325 push( @{$text->{$w}}, $l );
328 } elsif( $xn->nodeName eq 'witDetail' ) {
329 # Ignore these for now.
332 # Recurse as if this tag weren't there.
333 #print STDERR "Recursing on tag " . $xn->nodeName . "\n";
334 foreach( $xn->childNodes ) {
335 push( @new_readings, _get_readings( $tradition, $_, $in_var, $ac, @cur_wits ) );
338 return @new_readings;
343 # Helper to extract a list of witness sigla from a reading element.
346 # Cope if we have been handed a NodeList. There is only
348 if( ref( $rdg ) eq 'XML::LibXML::NodeList' ) {
353 if( ref( $rdg ) eq 'XML::LibXML::Element' ) {
354 my $witstr = $rdg->getAttribute( 'wit' );
357 @wits = split( /\s+/, $witstr );
358 map { $_ =~ s/^\#// } @wits;
363 # Helper with its counters to actually make the readings.
368 sub save_preexisting_nodeids {
370 $used_nodeids{$_->getValue()} = 1;
375 my( $graph, $word, $xml_id ) = @_;
377 if( exists $used_nodeids{$xml_id} ) {
378 if( $used_nodeids{$xml_id} != 1 ) {
379 warn "Already used assigned XML ID somewhere else!";
383 warn "Undetected pre-existing XML ID";
388 my $try_id = 'w'.$word_ctr++;
389 next if exists $used_nodeids{$try_id};
393 my $rdg = $graph->add_reading( $xml_id );
395 $used_nodeids{$xml_id} = $rdg;