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
17 my $t_from_file = Text::Tradition->new(
20 'file' => '/path/to/parallel_seg_file.xml'
23 my $t_from_string = Text::Tradition->new(
26 'string' => $parallel_seg_xml,
32 Parser module for Text::Tradition, given a TEI parallel-segmentation file
33 that describes a text and its variants. Normally called upon
34 initialization of Text::Tradition.
36 The witnesses for the tradition are taken from the <listWit/> element
37 within the TEI header; the readings are taken from any <p/> element that
38 appears in the text body (including <head/> elements therein.)
42 =head2 B<parse>( $tradition, $option_hash )
44 Takes an initialized tradition and a set of options; creates the
45 appropriate nodes and edges on the graph, as well as the appropriate
46 witness objects. The $option_hash must contain either a 'file' or a
47 'string' argument with the XML to be parsed.
52 binmode STDOUT, ":utf8";
53 binmode STDERR, ":utf8";
54 eval { no warnings; binmode $DB::OUT, ":utf8"; };
56 my $par_seg = 't/data/florilegium_tei_ps.xml';
57 my $t = Text::Tradition->new(
63 is( ref( $t ), 'Text::Tradition', "Parsed parallel-segmentation TEI" );
65 is( scalar $t->collation->readings, 319, "Collation has all readings" );
66 is( scalar $t->collation->paths, 374, "Collation has all paths" );
73 my $text = {}; # Hash of arrays, one per eventual witness we find.
74 my $substitutions = {}; # Keep track of merged readings
75 my $app_anchors = {}; # Track apparatus references
76 my $app_ac = {}; # Save a.c. readings
77 my $app_count; # Keep track of how many apps we have
79 # Create the package variables for tag names.
81 # Would really like to do this with varname variables, but apparently this
82 # is considered a bad idea. The long way round then.
83 my( $LISTWIT, $WITNESS, $TEXT, $W, $SEG, $APP, $RDG, $LEM )
84 = ( 'listWit', 'witness', 'text', 'w', 'seg', 'app', 'rdg', 'lem' );
88 $LISTWIT = "$ns:$LISTWIT";
89 $WITNESS = "$ns:$WITNESS";
101 my( $tradition, $opts ) = @_;
103 # First, parse the XML.
104 my $parser = XML::LibXML->new();
106 if( exists $opts->{'string'} ) {
107 $doc = $parser->parse_string( $opts->{'string'} );
108 } elsif ( exists $opts->{'file'} ) {
109 $doc = $parser->parse_file( $opts->{'file'} );
111 warn "Could not find string or file option to parse";
114 my $tei = $doc->documentElement();
115 my $xpc = XML::LibXML::XPathContext->new( $tei );
117 if( $tei->namespaceURI ) {
119 $xpc->registerNs( $ns, $tei->namespaceURI );
121 _make_tagnames( $ns );
123 # Then get the witnesses and create the witness objects.
124 foreach my $wit_el ( $xpc->findnodes( "//$LISTWIT/$WITNESS" ) ) {
125 my $sig = $wit_el->getAttribute( 'xml:id' );
126 my $source = $wit_el->toString();
127 $tradition->add_witness( sigil => $sig, source => $source );
129 map { $text->{$_->sigil} = [] } $tradition->witnesses;
131 # Look for all word/seg node IDs and note their pre-existence.
132 my @attrs = $xpc->findnodes( "//$W/attribute::xml:id" );
133 _save_preexisting_nodeids( @attrs );
135 # Count up how many apps we have.
136 my @apps = $xpc->findnodes( "//$APP" );
137 $app_count = scalar( @apps );
139 # Now go through the children of the text element and pull out the
141 foreach my $xml_el ( $xpc->findnodes( "//$TEXT" ) ) {
142 foreach my $xn ( $xml_el->childNodes ) {
143 _get_readings( $tradition, $xn );
146 # Our $text global now has lists of readings, one per witness.
148 my $c = $tradition->collation;
149 foreach my $sig ( keys %$text ) {
150 # Determine the list of readings for
151 my $sequence = $text->{$sig};
152 my @real_sequence = ( $c->start );
153 push( @$sequence, $c->end );
154 my $source = $c->start;
155 foreach( _clean_sequence( $sig, $sequence ) ) {
156 my $rdg = _return_rdg( $_ );
157 push( @real_sequence, $rdg );
158 $c->add_path( $source, $rdg, $sig );
161 # See if we need to make an a.c. version of the witness.
162 if( exists $app_ac->{$sig} ) {
164 push( @uncorrected, @real_sequence );
165 foreach my $app ( keys %{$app_ac->{$sig}} ) {
166 my $start = _return_rdg( $app_anchors->{$app}->{$sig}->{'start'} );
167 my $end = _return_rdg( $app_anchors->{$app}->{$sig}->{'end'} );
168 my @new = map { _return_rdg( $_ ) } @{$app_ac->{$sig}->{$app}};
169 _replace_sequence( \@uncorrected, $start, $end, @new );
171 my $source = $c->start;
172 foreach my $rdg ( @uncorrected ) {
173 my $has_base = grep { $_ eq $sig } $c->reading_witnesses( $rdg );
174 if( $rdg ne $c->start && !$has_base ) {
175 print STDERR sprintf( "Adding path %s from %s -> %s\n",
176 $sig.$c->ac_label, $source->id, $rdg->id );
177 $c->add_path( $source, $rdg, $sig.$c->ac_label );
181 print STDERR "Adding a.c. version for witness $sig\n";
182 $tradition->witness( $sig )->is_layered( 1 );
186 # Calculate the ranks for the nodes.
187 $tradition->collation->calculate_ranks();
189 # Now that we have ranks, see if we have distinct nodes with identical
190 # text and identical rank that can be merged.
191 $tradition->collation->flatten_ranks();
194 sub _clean_sequence {
195 my( $wit, $sequence ) = @_;
197 foreach my $rdg ( @$sequence ) {
198 if( $rdg =~ /^PH-(.*)$/ ) {
199 # It is a placeholder. Keep it only if we need it.
201 if( exists $app_ac->{$wit} &&
202 exists $app_ac->{$wit}->{$app_id} ) {
203 print STDERR "Retaining empty placeholder for $app_id\n";
204 push( @clean_sequence, $rdg );
207 push( @clean_sequence, $rdg );
210 return @clean_sequence;
213 sub _replace_sequence {
214 my( $arr, $start, $end, @new ) = @_;
215 my( $start_idx, $end_idx );
216 foreach my $i ( 0 .. $#{$arr} ) {
217 $start_idx = $i if( $arr->[$i]->id eq $start );
218 if( $arr->[$i]->id eq $end ) {
223 unless( $start_idx && $end_idx ) {
224 warn "Could not find start and end";
227 my $length = $end_idx - $start_idx + 1;
228 splice( @$arr, $start_idx, $length, @new );
233 # If we were passed a reading name, return the name. If we were
234 # passed a reading object, return the object.
235 my $wantobj = ref( $rdg ) eq 'Text::Tradition::Collation::Reading';
237 if( exists $substitutions->{ $wantobj ? $rdg->id : $rdg } ) {
238 $real = $substitutions->{ $wantobj ? $rdg->id : $rdg };
239 $real = $real->id unless $wantobj;
244 ## TODO test specific sorts of nodes of the parallel-seg XML.
246 ## Recursive helper function to help us navigate through nested XML,
247 ## picking out the text. $tradition is the tradition, needed for
248 ## making readings; $xn is the XML node currently being looked at,
249 ## $in_var is a flag to say that we are inside a variant, $ac is a
250 ## flag to say that we are inside an ante-correctionem reading, and
251 ## @cur_wits is the list of witnesses to which this XML node applies.
252 ## Returns the list of readings, if any, created on the run.
260 my( $tradition, $xn, $in_var, $ac, @cur_wits ) = @_;
261 @cur_wits = grep { $active_wits{$_} } keys %active_wits unless $in_var;
264 if( $xn->nodeType == XML_TEXT_NODE ) {
265 # Some words, thus make some readings.
267 return unless $str =~ /\S/; # skip whitespace-only text nodes
268 #print STDERR "Handling text node " . $str . "\n";
269 # Check that all the witnesses we have are active.
270 foreach my $c ( @cur_wits ) {
271 warn "$c is not among active wits" unless $active_wits{$c};
274 my $final = $str =~ s/\s+$//;
275 foreach my $w ( split( /\s+/, $str ) ) {
276 # For now, skip punctuation.
277 next if $w !~ /[[:alnum:]]/;
278 my $rdg = _make_reading( $tradition->collation, $w );
279 push( @new_readings, $rdg );
280 foreach ( @cur_wits ) {
281 warn "Empty wit!" unless $_;
282 warn "Empty reading!" unless $rdg;
283 push( @{$text->{$_}}, $rdg ) unless $ac;
286 } elsif( $xn->nodeName eq 'w' ) {
287 # Everything in this tag is one word. Also save any original XML ID.
288 #print STDERR "Handling word " . $xn->toString . "\n";
289 # Check that all the witnesses we have are active.
290 foreach my $c ( @cur_wits ) {
291 warn "$c is not among active wits" unless $active_wits{$c};
293 my $xml_id = $xn->getAttribute( 'xml:id' );
294 my $rdg = _make_reading( $tradition->collation, $xn->textContent, $xml_id );
295 push( @new_readings, $rdg );
296 foreach( @cur_wits ) {
297 warn "Empty wit!" unless $_;
298 warn "Empty reading!" unless $rdg;
299 push( @{$text->{$_}}, $rdg ) unless $ac;
301 } elsif ( $xn->nodeName eq 'app' ) {
303 $current_app = $xn->getAttribute( 'xml:id' );
304 # print STDERR "Handling app $current_app\n";
305 # Keep the reading sets in this app.
307 # Recurse through all children (i.e. rdgs) for sets of words.
308 foreach ( $xn->childNodes ) {
309 my @rdg_set = _get_readings( $tradition, $_, $in_var, $ac, @cur_wits );
310 push( @sets, \@rdg_set ) if @rdg_set;
312 # Now collate these sets if we have more than one.
313 my $subs = collate_variants( $tradition->collation, @sets ) if @sets > 1;
314 map { $substitutions->{$_} = $subs->{$_} } keys %$subs;
315 # TODO Look through substitutions to see if we can make anything common now.
316 # Return the entire set of unique readings.
318 foreach my $s ( @sets ) {
319 map { $unique{$_->id} = $_ } @$s;
321 push( @new_readings, values( %unique ) );
322 # Exit the current app.
324 } elsif ( $xn->nodeName eq 'lem' || $xn->nodeName eq 'rdg' ) {
325 # Alter the current witnesses and recurse.
326 #print STDERR "Handling reading for " . $xn->getAttribute( 'wit' ) . "\n";
327 # TODO handle p.c. and s.l. designations too
328 $ac = $xn->getAttribute( 'type' ) && $xn->getAttribute( 'type' ) eq 'a.c.';
329 my @rdg_wits = _get_sigla( $xn );
330 return unless @rdg_wits; # Skip readings that appear in no witnesses
332 foreach ( $xn->childNodes ) {
333 my @rdg_set = _get_readings( $tradition, $_, 1, $ac, @rdg_wits );
334 push( @words, @rdg_set ) if @rdg_set;
336 # If we have more than one word in a reading, it should become a segment.
337 # $tradition->collation->add_segment( @words ) if @words > 1;
340 # Add the reading set to the a.c. readings.
341 foreach ( @rdg_wits ) {
342 $app_ac->{$_}->{$current_app} = \@words;
345 # Add the reading set to the app anchors for each witness
346 # or put in placeholders for empty p.c. readings
347 foreach ( @rdg_wits ) {
348 my $start = @words ? $words[0]->id : "PH-$current_app";
349 my $end = @words ? $words[-1]->id : "PH-$current_app";
350 $app_anchors->{$current_app}->{$_}->{'start'} = $start;
351 $app_anchors->{$current_app}->{$_}->{'end'} = $end;
352 push( @{$text->{$_}}, $start ) unless @words;
355 push( @new_readings, @words );
356 } elsif( $xn->nodeName eq 'witStart' ) {
357 # Add the relevant wit(s) to the active list.
358 #print STDERR "Handling witStart\n";
359 map { $active_wits{$_} = 1 } @cur_wits;
360 # Record a lacuna in all non-active witnesses if this is
361 # the first app. Get the full list from $text.
362 if( $seen_apps == 1 ) {
364 foreach my $sig ( keys %$text ) {
365 next if $active_wits{$sig};
366 my $l = $tradition->collation->add_reading( {
367 'id' => $current_app . "_$i",
368 'is_lacuna' => 1 } );
370 push( @{$text->{$sig}}, $l );
373 } elsif( $xn->nodeName eq 'witEnd' ) {
374 # Take the relevant wit(s) out of the list.
375 #print STDERR "Handling witEnd\n";
376 map { $active_wits{$_} = undef } @cur_wits;
377 # Record a lacuna, unless this is the last app.
378 unless( $seen_apps == $app_count ) {
379 foreach my $i ( 0 .. $#cur_wits ) {
380 my $w = $cur_wits[$i];
381 my $l = $tradition->collation->add_reading( {
382 'id' => $current_app . "_$i",
383 'is_lacuna' => 1 } );
384 push( @{$text->{$w}}, $l );
387 } elsif( $xn->nodeName eq 'witDetail'
388 || $xn->nodeName eq 'note' ) {
389 # Ignore these for now.
392 # Recurse as if this tag weren't there.
393 #print STDERR "Recursing on tag " . $xn->nodeName . "\n";
394 foreach( $xn->childNodes ) {
395 push( @new_readings, _get_readings( $tradition, $_, $in_var, $ac, @cur_wits ) );
398 return @new_readings;
406 use XML::LibXML::XPathContext;
407 use Text::Tradition::Parser::TEI;
409 my $xml_str = '<tei><rdg wit="#A #B #C #D">some text</rdg></tei>';
410 my $el = XML::LibXML->new()->parse_string( $xml_str )->documentElement;
411 my $xpc = XML::LibXML::XPathContext->new( $el );
412 my $obj = $xpc->find( '//rdg' );
414 my @wits = Text::Tradition::Parser::TEI::_get_sigla( $obj );
415 is( join( ' ', @wits) , "A B C D", "correctly parsed reading wit string" );
421 # Helper to extract a list of witness sigla from a reading element.
424 # Cope if we have been handed a NodeList. There is only
426 if( ref( $rdg ) eq 'XML::LibXML::NodeList' ) {
431 if( ref( $rdg ) eq 'XML::LibXML::Element' ) {
432 my $witstr = $rdg->getAttribute( 'wit' );
433 return () unless $witstr;
436 @wits = split( /\s+/, $witstr );
437 map { $_ =~ s/^\#// } @wits;
442 # Helper with its counters to actually make the readings.
447 sub _save_preexisting_nodeids {
449 $used_nodeids{$_->getValue()} = 1;
454 my( $graph, $word, $xml_id ) = @_;
456 if( exists $used_nodeids{$xml_id} ) {
457 if( $used_nodeids{$xml_id} != 1 ) {
458 warn "Already used assigned XML ID somewhere else!";
462 warn "Undetected pre-existing XML ID";
467 my $try_id = 'w'.$word_ctr++;
468 next if exists $used_nodeids{$try_id};
472 my $rdg = $graph->add_reading(
476 $used_nodeids{$xml_id} = $rdg;
487 =item * More unit testing
489 =item * Handle special designations apart from a.c.
491 =item * Mark common nodes within collated variants
497 This package is free software and is provided "as is" without express
498 or implied warranty. You can redistribute it and/or modify it under
499 the same terms as Perl itself.
503 Tara L Andrews E<lt>aurum@cpan.orgE<gt>