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.
34 my $substitutions = {}; # Keep track of merged readings
35 my $app_anchors = {}; # Track apparatus references
36 my $app_ac = {}; # Save a.c. readings
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 );
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 );
86 # Now go through the children of the text element and pull out the
88 foreach my $xml_el ( $xpc->findnodes( "//$TEXT" ) ) {
89 foreach my $xn ( $xml_el->childNodes ) {
90 _get_readings( $tradition, $xn );
93 # Our $text global now has lists of readings, one per witness.
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 );
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} ) {
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 );
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 );
130 $tradition->witness( $sig )->uncorrected_path( \@uncorrected );
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( $_ ) );
138 $tradition->collation->calculate_positions( @common_readings );
141 sub _clean_sequence {
142 my( $wit, $sequence ) = @_;
144 foreach my $rdg ( @$sequence ) {
145 if( $rdg =~ /^PH-(.*)$/ ) {
146 # It is a placeholder. Keep it only if we need it.
148 if( exists $app_ac->{$wit}->{$app_id} ) {
149 print STDERR "Retaining empty placeholder for $app_id\n";
150 push( @clean_sequence, $rdg );
153 push( @clean_sequence, $rdg );
156 return @clean_sequence;
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 ) {
169 unless( $start_idx && $end_idx ) {
170 warn "Could not find start and end";
173 my $length = $end_idx - $start_idx + 1;
174 splice( @$arr, $start_idx, $length, @new );
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';
183 if( exists $substitutions->{ $wantobj ? $rdg->name : $rdg } ) {
184 $real = $substitutions->{ $wantobj ? $rdg->name : $rdg };
185 $real = $real->name unless $wantobj;
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.
203 my( $tradition, $xn, $in_var, $ac, @cur_wits ) = @_;
204 @cur_wits = @active_wits unless $in_var;
207 if( $xn->nodeType == XML_TEXT_NODE ) {
208 # Some words, thus make some readings.
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;
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 );
225 push( @common_readings, $rdg );
228 foreach ( @cur_wits ) {
229 warn "Empty wit!" unless $_;
230 warn "Empty reading!" unless $rdg;
231 push( @{$text->{$_}}, $rdg ) unless $ac;
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;
242 my $xml_id = $xn->getAttribute( 'xml:id' );
243 my $rdg = make_reading( $tradition->collation, $xn->textContent, $xml_id );
244 push( @new_readings, $rdg );
246 push( @common_readings, $rdg );
249 foreach( @cur_wits ) {
250 warn "Empty wit!" unless $_;
251 warn "Empty reading!" unless $rdg;
252 push( @{$text->{$_}}, $rdg ) unless $ac;
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.
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;
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.
270 foreach my $s ( @sets ) {
271 map { $unique{$_->name} = $_ } @$s;
273 push( @new_readings, values( %unique ) );
274 # Exit the 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
283 foreach ( $xn->childNodes ) {
284 my @rdg_set = _get_readings( $tradition, $_, 1, $ac, @rdg_wits );
285 push( @words, @rdg_set ) if @rdg_set;
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;
291 # Add the reading set to the a.c. readings.
292 foreach ( @rdg_wits ) {
293 $app_ac->{$_}->{$current_app} = \@words;
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;
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.
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 ) );
326 return @new_readings;
331 # Helper to extract a list of witness sigla from a reading element.
334 # Cope if we have been handed a NodeList. There is only
336 if( ref( $rdg ) eq 'XML::LibXML::NodeList' ) {
341 if( ref( $rdg ) eq 'XML::LibXML::Element' ) {
342 my $witstr = $rdg->getAttribute( 'wit' );
345 @wits = split( /\s+/, $witstr );
346 map { $_ =~ s/^\#// } @wits;
351 # Helper with its counters to actually make the readings.
356 sub save_preexisting_nodeids {
358 $used_nodeids{$_->getValue()} = 1;
363 my( $graph, $word, $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!";
371 warn "Undetected pre-existing XML ID";
376 my $try_id = 'w'.$word_ctr++;
377 next if exists $used_nodeids{$try_id};
381 my $rdg = $graph->add_reading( $xml_id );
383 $used_nodeids{$xml_id} = $rdg;