1 package Text::Tradition::Parser::TEI;
5 use Text::Tradition::Error;
6 use Text::Tradition::Parser::Util qw( collate_variants );
8 use XML::LibXML::XPathContext;
12 Text::Tradition::Parser::TEI
18 my $t_from_file = Text::Tradition->new(
21 'file' => '/path/to/parallel_seg_file.xml'
24 my $t_from_string = Text::Tradition->new(
27 'string' => $parallel_seg_xml,
33 Parser module for Text::Tradition, given a TEI parallel-segmentation file
34 that describes a text and its variants. Normally called upon
35 initialization of Text::Tradition.
37 The witnesses for the tradition are taken from the <listWit/> element
38 within the TEI header; the readings are taken from any <p/> element that
39 appears in the text body (including <head/> elements therein.)
43 =head2 B<parse>( $tradition, $option_hash )
45 Takes an initialized tradition and a set of options; creates the
46 appropriate nodes and edges on the graph, as well as the appropriate
47 witness objects. The $option_hash must contain either a 'file' or a
48 'string' argument with the XML to be parsed.
53 binmode STDOUT, ":utf8";
54 binmode STDERR, ":utf8";
55 eval { no warnings; binmode $DB::OUT, ":utf8"; };
57 my $par_seg = 't/data/florilegium_tei_ps.xml';
58 my $t = Text::Tradition->new(
64 is( ref( $t ), 'Text::Tradition', "Parsed parallel-segmentation TEI" );
66 is( scalar $t->collation->readings, 311, "Collation has all readings" );
67 is( scalar $t->collation->paths, 361, "Collation has all paths" );
74 my $text = {}; # Hash of arrays, one per eventual witness we find.
75 my $substitutions = {}; # Keep track of merged readings
76 my $app_anchors = {}; # Track apparatus references
77 my $app_ac = {}; # Save a.c. readings
78 my $app_count; # Keep track of how many apps we have
80 # Create the package variables for tag names.
82 # Would really like to do this with varname variables, but apparently this
83 # is considered a bad idea. The long way round then.
84 my( $LISTWIT, $WITNESS, $TEXT, $W, $SEG, $APP, $RDG, $LEM )
85 = ( 'listWit', 'witness', 'text', 'w', 'seg', 'app', 'rdg', 'lem' );
89 $LISTWIT = "$ns:$LISTWIT";
90 $WITNESS = "$ns:$WITNESS";
100 # Parse the TEI file.
102 my( $tradition, $opts ) = @_;
104 # First, parse the XML.
105 my $parser = XML::LibXML->new();
107 if( exists $opts->{'string'} ) {
108 $doc = $parser->parse_string( $opts->{'string'} );
109 } elsif ( exists $opts->{'file'} ) {
110 $doc = $parser->parse_file( $opts->{'file'} );
111 } elsif ( exists $opts->{'xmlobj'} ) {
112 $doc = $opts->{'xmlobj'};
114 warn "Could not find string or file option to parse";
117 my $tei = $doc->documentElement();
118 unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
119 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
121 my $xpc = XML::LibXML::XPathContext->new( $tei );
123 if( $tei->namespaceURI ) {
125 $xpc->registerNs( $ns, $tei->namespaceURI );
127 _make_tagnames( $ns );
129 # Then get the witnesses and create the witness objects.
130 foreach my $wit_el ( $xpc->findnodes( "//$LISTWIT/$WITNESS" ) ) {
131 my $sig = $wit_el->getAttribute( 'xml:id' );
132 my $source = $wit_el->toString();
133 $tradition->add_witness( sigil => $sig, sourcetype => 'collation' );
135 map { $text->{$_->sigil} = [] } $tradition->witnesses;
137 # Look for all word/seg node IDs and note their pre-existence.
138 my @attrs = $xpc->findnodes( "//$W/attribute::xml:id" );
139 _save_preexisting_nodeids( @attrs );
141 # Count up how many apps we have.
142 my @apps = $xpc->findnodes( "//$APP" );
143 $app_count = scalar( @apps );
145 # Now go through the children of the text element and pull out the
147 foreach my $xml_el ( $xpc->findnodes( "//$TEXT" ) ) {
148 foreach my $xn ( $xml_el->childNodes ) {
149 _get_readings( $tradition, $xn );
152 # Our $text global now has lists of readings, one per witness.
154 my $c = $tradition->collation;
155 foreach my $sig ( keys %$text ) {
156 # Determine the list of readings for
157 my $sequence = $text->{$sig};
158 my @real_sequence = ( $c->start );
159 push( @$sequence, $c->end );
160 foreach( _clean_sequence( $sig, $sequence, 1 ) ) {
161 push( @real_sequence, _return_rdg( $_ ) );
163 # See if we need to make an a.c. version of the witness.
164 if( exists $app_ac->{$sig} ) {
166 push( @uncorrected, @real_sequence );
167 # Get rid of any remaining placeholders.
168 @real_sequence = _clean_sequence( $sig, \@uncorrected );
169 # Do the uncorrections
170 foreach my $app ( keys %{$app_ac->{$sig}} ) {
171 my $start = _return_rdg( $app_anchors->{$app}->{$sig}->{'start'} );
172 my $end = _return_rdg( $app_anchors->{$app}->{$sig}->{'end'} );
173 my @new = map { _return_rdg( $_ ) } @{$app_ac->{$sig}->{$app}};
174 _replace_sequence( \@uncorrected, $start, $end, @new );
176 # and record the results.
177 $tradition->witness( $sig )->uncorrected_path( \@uncorrected );
178 $tradition->witness( $sig )->is_layered( 1 );
180 $tradition->witness( $sig )->path( \@real_sequence );
182 # Now make our witness paths.
183 $tradition->collation->make_witness_paths();
185 unless( $opts->{'nocalc'} ) {
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();
193 # And now that we've done that, calculate the common nodes.
194 $tradition->collation->calculate_common_readings();
196 # Save the text for each witness so that we can ensure consistency
198 $tradition->collation->text_from_paths();
202 sub _clean_sequence {
203 my( $wit, $sequence, $keep_ac ) = @_;
205 foreach my $rdg ( @$sequence ) {
206 if( $rdg =~ /^PH-(.*)$/ ) {
207 # It is a placeholder. Keep it only if we need it for a later
210 if( $keep_ac && exists $app_ac->{$wit} &&
211 exists $app_ac->{$wit}->{$app_id} ) {
212 # print STDERR "Retaining empty placeholder for $app_id\n";
213 push( @clean_sequence, $rdg );
216 push( @clean_sequence, $rdg );
219 return @clean_sequence;
222 sub _replace_sequence {
223 my( $arr, $start, $end, @new ) = @_;
224 my( $start_idx, $end_idx );
225 foreach my $i ( 0 .. $#{$arr} ) {
226 # If $arr->[$i] is a placeholder, cope.
227 my $iid = ref( $arr->[$i] ) ? $arr->[$i]->id : $arr->[$i];
228 $start_idx = $i if( $iid eq $start );
234 unless( $start_idx && $end_idx ) {
235 warn "Could not find start and end";
238 my $length = $end_idx - $start_idx + 1;
239 splice( @$arr, $start_idx, $length, @new );
244 # If we were passed a reading name, return the name. If we were
245 # passed a reading object, return the object.
246 my $wantobj = ref( $rdg ) eq 'Text::Tradition::Collation::Reading';
248 if( exists $substitutions->{ $wantobj ? $rdg->id : $rdg } ) {
249 $real = $substitutions->{ $wantobj ? $rdg->id : $rdg };
250 $real = $real->id unless $wantobj;
255 ## TODO test specific sorts of nodes of the parallel-seg XML.
257 ## Recursive helper function to help us navigate through nested XML,
258 ## picking out the text. $tradition is the tradition, needed for
259 ## making readings; $xn is the XML node currently being looked at,
260 ## $in_var is a flag to say that we are inside a variant, $ac is a
261 ## flag to say that we are inside an ante-correctionem reading, and
262 ## @cur_wits is the list of witnesses to which this XML node applies.
263 ## Returns the list of readings, if any, created on the run.
271 my( $tradition, $xn, $in_var, $ac, @cur_wits ) = @_;
272 @cur_wits = grep { $active_wits{$_} } keys %active_wits unless $in_var;
275 if( $xn->nodeType == XML_TEXT_NODE ) {
276 # Some words, thus make some readings.
278 return unless $str =~ /\S/; # skip whitespace-only text nodes
279 #print STDERR "Handling text node " . $str . "\n";
280 # Check that all the witnesses we have are active.
281 foreach my $c ( @cur_wits ) {
282 warn "$c is not among active wits" unless $active_wits{$c};
285 my $final = $str =~ s/\s+$//;
286 foreach my $w ( split( /\s+/, $str ) ) {
287 # For now, skip punctuation.
288 next if $w !~ /[[:alnum:]]/;
289 my $rdg = _make_reading( $tradition->collation, $w );
290 push( @new_readings, $rdg );
291 foreach ( @cur_wits ) {
292 warn "Empty wit!" unless $_;
293 warn "Empty reading!" unless $rdg;
294 push( @{$text->{$_}}, $rdg ) unless $ac;
297 } elsif( $xn->nodeName eq 'w' ) {
298 # Everything in this tag is one word. Also save any original XML ID.
299 #print STDERR "Handling word " . $xn->toString . "\n";
300 # Check that all the witnesses we have are active.
301 foreach my $c ( @cur_wits ) {
302 warn "$c is not among active wits" unless $active_wits{$c};
304 my $xml_id = $xn->getAttribute( 'xml:id' );
305 my $rdg = _make_reading( $tradition->collation, $xn->textContent, $xml_id );
306 push( @new_readings, $rdg );
307 foreach( @cur_wits ) {
308 warn "Empty wit!" unless $_;
309 warn "Empty reading!" unless $rdg;
310 push( @{$text->{$_}}, $rdg ) unless $ac;
312 } elsif ( $xn->nodeName eq 'app' ) {
314 $current_app = $xn->getAttribute( 'xml:id' );
315 # print STDERR "Handling app $current_app\n";
316 # Keep the reading sets in this app.
318 # Recurse through all children (i.e. rdgs) for sets of words.
319 foreach ( $xn->childNodes ) {
320 my @rdg_set = _get_readings( $tradition, $_, $in_var, $ac, @cur_wits );
321 push( @sets, \@rdg_set ) if @rdg_set;
323 # Now collate these sets if we have more than one.
324 my $subs = collate_variants( $tradition->collation, @sets ) if @sets > 1;
325 map { $substitutions->{$_} = $subs->{$_} } keys %$subs;
326 # Return the entire set of unique readings.
328 foreach my $s ( @sets ) {
329 map { $unique{$_->id} = $_ } @$s;
331 push( @new_readings, values( %unique ) );
332 # Exit the current app.
334 } elsif ( $xn->nodeName eq 'lem' || $xn->nodeName eq 'rdg' ) {
335 # Alter the current witnesses and recurse.
336 #print STDERR "Handling reading for " . $xn->getAttribute( 'wit' ) . "\n";
337 # TODO handle p.c. and s.l. designations too
338 $ac = $xn->getAttribute( 'type' ) && $xn->getAttribute( 'type' ) eq 'a.c.';
339 my @rdg_wits = _get_sigla( $xn );
340 return unless @rdg_wits; # Skip readings that appear in no witnesses
342 foreach ( $xn->childNodes ) {
343 my @rdg_set = _get_readings( $tradition, $_, 1, $ac, @rdg_wits );
344 push( @words, @rdg_set ) if @rdg_set;
346 # If we have more than one word in a reading, it should become a segment.
347 # $tradition->collation->add_segment( @words ) if @words > 1;
350 # Add the reading set to the a.c. readings.
351 foreach ( @rdg_wits ) {
352 $app_ac->{$_}->{$current_app} = \@words;
355 # Add the reading set to the app anchors for each witness
356 # or put in placeholders for empty p.c. readings
357 foreach ( @rdg_wits ) {
358 my $start = @words ? $words[0]->id : "PH-$current_app";
359 my $end = @words ? $words[-1]->id : "PH-$current_app";
360 $app_anchors->{$current_app}->{$_}->{'start'} = $start;
361 $app_anchors->{$current_app}->{$_}->{'end'} = $end;
362 push( @{$text->{$_}}, $start ) unless @words;
365 push( @new_readings, @words );
366 } elsif( $xn->nodeName eq 'witStart' ) {
367 # Add the relevant wit(s) to the active list.
368 #print STDERR "Handling witStart\n";
369 map { $active_wits{$_} = 1 } @cur_wits;
370 # Record a lacuna in all non-active witnesses if this is
371 # the first app. Get the full list from $text.
372 if( $seen_apps == 1 ) {
374 foreach my $sig ( keys %$text ) {
375 next if $active_wits{$sig};
376 my $l = $tradition->collation->add_reading( {
377 'id' => $current_app . "_$i",
378 'is_lacuna' => 1 } );
380 push( @{$text->{$sig}}, $l );
383 } elsif( $xn->nodeName eq 'witEnd' ) {
384 # Take the relevant wit(s) out of the list.
385 #print STDERR "Handling witEnd\n";
386 map { $active_wits{$_} = undef } @cur_wits;
387 # Record a lacuna, unless this is the last app.
388 unless( $seen_apps == $app_count ) {
389 foreach my $i ( 0 .. $#cur_wits ) {
390 my $w = $cur_wits[$i];
391 my $l = $tradition->collation->add_reading( {
392 'id' => $current_app . "_$i",
393 'is_lacuna' => 1 } );
394 push( @{$text->{$w}}, $l );
397 } elsif( $xn->nodeName eq 'witDetail'
398 || $xn->nodeName eq 'note' ) {
399 # Ignore these for now.
402 # Recurse as if this tag weren't there.
403 #print STDERR "Recursing on tag " . $xn->nodeName . "\n";
404 foreach( $xn->childNodes ) {
405 push( @new_readings, _get_readings( $tradition, $_, $in_var, $ac, @cur_wits ) );
408 return @new_readings;
416 use XML::LibXML::XPathContext;
417 use Text::Tradition::Parser::TEI;
419 my $xml_str = '<tei><rdg wit="#A #B #C #D">some text</rdg></tei>';
420 my $el = XML::LibXML->new()->parse_string( $xml_str )->documentElement;
421 my $xpc = XML::LibXML::XPathContext->new( $el );
422 my $obj = $xpc->find( '//rdg' );
424 my @wits = Text::Tradition::Parser::TEI::_get_sigla( $obj );
425 is( join( ' ', @wits) , "A B C D", "correctly parsed reading wit string" );
431 # Helper to extract a list of witness sigla from a reading element.
434 # Cope if we have been handed a NodeList. There is only
436 if( ref( $rdg ) eq 'XML::LibXML::NodeList' ) {
441 if( ref( $rdg ) eq 'XML::LibXML::Element' ) {
442 my $witstr = $rdg->getAttribute( 'wit' );
443 return () unless $witstr;
446 @wits = split( /\s+/, $witstr );
447 map { $_ =~ s/^\#// } @wits;
452 # Helper with its counters to actually make the readings.
457 sub _save_preexisting_nodeids {
459 $used_nodeids{$_->getValue()} = 1;
464 my( $graph, $word, $xml_id ) = @_;
466 if( exists $used_nodeids{$xml_id} ) {
467 if( $used_nodeids{$xml_id} != 1 ) {
468 warn "Already used assigned XML ID somewhere else!";
472 warn "Undetected pre-existing XML ID";
477 my $try_id = 'w'.$word_ctr++;
478 next if exists $used_nodeids{$try_id};
482 my $rdg = $graph->add_reading(
486 $used_nodeids{$xml_id} = $rdg;
494 Text::Tradition::Error->throw(
495 'ident' => 'Parser::TEI error',
504 =item * More unit testing
506 =item * Handle special designations apart from a.c.
508 =item * Mark common nodes within collated variants
514 This package is free software and is provided "as is" without express
515 or implied warranty. You can redistribute it and/or modify it under
516 the same terms as Perl itself.
520 Tara L Andrews E<lt>aurum@cpan.orgE<gt>