cope with some parsing niggles
[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
3b853983 13=head1 SYNOPSIS
14
15 use Text::Tradition;
16
17 my $t_from_file = Text::Tradition->new(
18 'name' => 'my text',
19 'input' => 'TEI',
20 'file' => '/path/to/parallel_seg_file.xml'
21 );
22
23 my $t_from_string = Text::Tradition->new(
24 'name' => 'my text',
25 'input' => 'TEI',
26 'string' => $parallel_seg_xml,
27 );
28
29
f6066bac 30=head1 DESCRIPTION
31
3b853983 32Parser module for Text::Tradition, given a TEI parallel-segmentation file
33that describes a text and its variants. Normally called upon
34initialization of Text::Tradition.
35
36The witnesses for the tradition are taken from the <listWit/> element
37within the TEI header; the readings are taken from any <p/> element that
38appears in the text body (including <head/> elements therein.)
f6066bac 39
40=head1 METHODS
41
e867486f 42=head2 B<parse>( $tradition, $option_hash )
3b853983 43
44Takes an initialized tradition and a set of options; creates the
45appropriate nodes and edges on the graph, as well as the appropriate
46witness objects. The $option_hash must contain either a 'file' or a
47'string' argument with the XML to be parsed.
48
49=begin testing
50
51use Text::Tradition;
52binmode STDOUT, ":utf8";
53binmode STDERR, ":utf8";
54eval { no warnings; binmode $DB::OUT, ":utf8"; };
55
56my $par_seg = 't/data/florilegium_tei_ps.xml';
57my $t = Text::Tradition->new(
58 'name' => 'inline',
59 'input' => 'TEI',
60 'file' => $par_seg,
61 );
f6066bac 62
3b853983 63is( ref( $t ), 'Text::Tradition', "Parsed parallel-segmentation TEI" );
64if( $t ) {
65 is( scalar $t->collation->readings, 319, "Collation has all readings" );
66 is( scalar $t->collation->paths, 2854, "Collation has all paths" );
67}
f6066bac 68
3b853983 69=end testing
f6066bac 70
71=cut
72
910a0a6d 73my $text = {}; # Hash of arrays, one per eventual witness we find.
910a0a6d 74my $substitutions = {}; # Keep track of merged readings
75my $app_anchors = {}; # Track apparatus references
76my $app_ac = {}; # Save a.c. readings
eca16057 77my $app_count; # Keep track of how many apps we have
910a0a6d 78
79# Create the package variables for tag names.
80
81# Would really like to do this with varname variables, but apparently this
82# is considered a bad idea. The long way round then.
83my( $LISTWIT, $WITNESS, $TEXT, $W, $SEG, $APP, $RDG, $LEM )
84 = ( 'listWit', 'witness', 'text', 'w', 'seg', 'app', 'rdg', 'lem' );
3b853983 85sub _make_tagnames {
910a0a6d 86 my( $ns ) = @_;
87 if( $ns ) {
88 $LISTWIT = "$ns:$LISTWIT";
89 $WITNESS = "$ns:$WITNESS";
90 $TEXT = "$ns:$TEXT";
91 $W = "$ns:$W";
92 $SEG = "$ns:$SEG";
93 $APP = "$ns:$APP";
94 $RDG = "$ns:$RDG";
95 $LEM = "$ns:$LEM";
96 }
97}
98
99# Parse the TEI file.
f6066bac 100sub parse {
dfc37e38 101 my( $tradition, $opts ) = @_;
f6066bac 102
103 # First, parse the XML.
104 my $parser = XML::LibXML->new();
dfc37e38 105 my $doc;
106 if( exists $opts->{'string'} ) {
107 $doc = $parser->parse_string( $opts->{'string'} );
108 } elsif ( exists $opts->{'file'} ) {
109 $doc = $parser->parse_file( $opts->{'file'} );
110 } else {
111 warn "Could not find string or file option to parse";
112 return;
113 }
f6066bac 114 my $tei = $doc->documentElement();
f2b9605f 115 my $xpc = XML::LibXML::XPathContext->new( $tei );
910a0a6d 116 my $ns;
117 if( $tei->namespaceURI ) {
118 $ns = 'tei';
119 $xpc->registerNs( $ns, $tei->namespaceURI );
120 }
3b853983 121 _make_tagnames( $ns );
910a0a6d 122
f6066bac 123 # Then get the witnesses and create the witness objects.
910a0a6d 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 );
f6066bac 128 }
910a0a6d 129 map { $text->{$_->sigil} = [] } $tradition->witnesses;
eca16057 130
910a0a6d 131 # Look for all word/seg node IDs and note their pre-existence.
a7fb3133 132 my @attrs = $xpc->findnodes( "//$W/attribute::xml:id" );
3b853983 133 _save_preexisting_nodeids( @attrs );
910a0a6d 134
eca16057 135 # Count up how many apps we have.
136 my @apps = $xpc->findnodes( "//$APP" );
137 $app_count = scalar( @apps );
138
910a0a6d 139 # Now go through the children of the text element and pull out the
140 # actual text.
141 foreach my $xml_el ( $xpc->findnodes( "//$TEXT" ) ) {
142 foreach my $xn ( $xml_el->childNodes ) {
143 _get_readings( $tradition, $xn );
144 }
145 }
146 # Our $text global now has lists of readings, one per witness.
147 # Join them up.
148 my $c = $tradition->collation;
149 foreach my $sig ( keys %$text ) {
910a0a6d 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 );
159 $source = $rdg;
160 }
161 $tradition->witness( $sig )->path( \@real_sequence );
162 # See if we need to make an a.c. version of the witness.
163 if( exists $app_ac->{$sig} ) {
164 my @uncorrected;
165 push( @uncorrected, @real_sequence );
166 foreach my $app ( keys %{$app_ac->{$sig}} ) {
167 my $start = _return_rdg( $app_anchors->{$app}->{$sig}->{'start'} );
168 my $end = _return_rdg( $app_anchors->{$app}->{$sig}->{'end'} );
169 my @new = map { _return_rdg( $_ ) } @{$app_ac->{$sig}->{$app}};
170 _replace_sequence( \@uncorrected, $start, $end, @new );
171 }
172 my $source = $c->start;
173 foreach my $rdg ( @uncorrected ) {
174 my $has_base = grep { $_->label eq $sig } $source->edges_to( $rdg );
175 if( $rdg ne $c->start && !$has_base ) {
176 print STDERR sprintf( "Adding path %s from %s -> %s\n",
177 $sig.$c->ac_label, $source->name, $rdg->name );
178 $c->add_path( $source, $rdg, $sig.$c->ac_label );
179 }
180 $source = $rdg;
181 }
78fab1cf 182 print STDERR "Adding a.c. version for witness $sig\n";
910a0a6d 183 $tradition->witness( $sig )->uncorrected_path( \@uncorrected );
184 }
185 }
3b853983 186
187 # Calculate the ranks for the nodes.
a7fb3133 188 $tradition->collation->calculate_ranks();
3bc0cd18 189
190 # Now that we have ranks, see if we have distinct nodes with identical
191 # text and identical rank that can be merged.
0e476982 192 $tradition->collation->flatten_ranks();
910a0a6d 193}
194
195sub _clean_sequence {
196 my( $wit, $sequence ) = @_;
197 my @clean_sequence;
198 foreach my $rdg ( @$sequence ) {
199 if( $rdg =~ /^PH-(.*)$/ ) {
200 # It is a placeholder. Keep it only if we need it.
201 my $app_id = $1;
78fab1cf 202 if( exists $app_ac->{$wit} &&
203 exists $app_ac->{$wit}->{$app_id} ) {
910a0a6d 204 print STDERR "Retaining empty placeholder for $app_id\n";
205 push( @clean_sequence, $rdg );
206 }
207 } else {
208 push( @clean_sequence, $rdg );
209 }
f6066bac 210 }
910a0a6d 211 return @clean_sequence;
212}
f6066bac 213
910a0a6d 214sub _replace_sequence {
215 my( $arr, $start, $end, @new ) = @_;
216 my( $start_idx, $end_idx );
217 foreach my $i ( 0 .. $#{$arr} ) {
218 $start_idx = $i if( $arr->[$i]->name eq $start );
219 if( $arr->[$i]->name eq $end ) {
220 $end_idx = $i;
221 last;
222 }
223 }
224 unless( $start_idx && $end_idx ) {
225 warn "Could not find start and end";
226 return;
f2b9605f 227 }
910a0a6d 228 my $length = $end_idx - $start_idx + 1;
229 splice( @$arr, $start_idx, $length, @new );
230}
f6066bac 231
910a0a6d 232sub _return_rdg {
233 my( $rdg ) = @_;
234 # If we were passed a reading name, return the name. If we were
235 # passed a reading object, return the object.
236 my $wantobj = ref( $rdg ) eq 'Text::Tradition::Collation::Reading';
237 my $real = $rdg;
238 if( exists $substitutions->{ $wantobj ? $rdg->name : $rdg } ) {
239 $real = $substitutions->{ $wantobj ? $rdg->name : $rdg };
240 $real = $real->name unless $wantobj;
241 }
242 return $real;
f6066bac 243}
244
3b853983 245## TODO test specific sorts of nodes of the parallel-seg XML.
246
910a0a6d 247## Recursive helper function to help us navigate through nested XML,
248## picking out the text. $tradition is the tradition, needed for
249## making readings; $xn is the XML node currently being looked at,
250## $in_var is a flag to say that we are inside a variant, $ac is a
251## flag to say that we are inside an ante-correctionem reading, and
252## @cur_wits is the list of witnesses to which this XML node applies.
253## Returns the list of readings, if any, created on the run.
254
255{
3bc0cd18 256 my %active_wits;
910a0a6d 257 my $current_app;
eca16057 258 my $seen_apps;
910a0a6d 259
260 sub _get_readings {
261 my( $tradition, $xn, $in_var, $ac, @cur_wits ) = @_;
3bc0cd18 262 @cur_wits = grep { $active_wits{$_} } keys %active_wits unless $in_var;
910a0a6d 263
264 my @new_readings;
265 if( $xn->nodeType == XML_TEXT_NODE ) {
266 # Some words, thus make some readings.
267 my $str = $xn->data;
268 return unless $str =~ /\S/; # skip whitespace-only text nodes
269 #print STDERR "Handling text node " . $str . "\n";
270 # Check that all the witnesses we have are active.
271 foreach my $c ( @cur_wits ) {
3bc0cd18 272 warn "$c is not among active wits" unless $active_wits{$c};
910a0a6d 273 }
274 $str =~ s/^\s+//;
275 my $final = $str =~ s/\s+$//;
276 foreach my $w ( split( /\s+/, $str ) ) {
277 # For now, skip punctuation.
278 next if $w !~ /[[:alnum:]]/;
3b853983 279 my $rdg = _make_reading( $tradition->collation, $w );
910a0a6d 280 push( @new_readings, $rdg );
281 unless( $in_var ) {
910a0a6d 282 $rdg->make_common;
283 }
284 foreach ( @cur_wits ) {
285 warn "Empty wit!" unless $_;
286 warn "Empty reading!" unless $rdg;
287 push( @{$text->{$_}}, $rdg ) unless $ac;
288 }
289 }
290 } elsif( $xn->nodeName eq 'w' ) {
291 # Everything in this tag is one word. Also save any original XML ID.
292 #print STDERR "Handling word " . $xn->toString . "\n";
293 # Check that all the witnesses we have are active.
294 foreach my $c ( @cur_wits ) {
3bc0cd18 295 warn "$c is not among active wits" unless $active_wits{$c};
910a0a6d 296 }
297 my $xml_id = $xn->getAttribute( 'xml:id' );
3b853983 298 my $rdg = _make_reading( $tradition->collation, $xn->textContent, $xml_id );
910a0a6d 299 push( @new_readings, $rdg );
300 unless( $in_var ) {
910a0a6d 301 $rdg->make_common;
302 }
303 foreach( @cur_wits ) {
304 warn "Empty wit!" unless $_;
305 warn "Empty reading!" unless $rdg;
306 push( @{$text->{$_}}, $rdg ) unless $ac;
307 }
308 } elsif ( $xn->nodeName eq 'app' ) {
eca16057 309 $seen_apps++;
910a0a6d 310 $current_app = $xn->getAttribute( 'xml:id' );
311 # print STDERR "Handling app $current_app\n";
312 # Keep the reading sets in this app.
313 my @sets;
314 # Recurse through all children (i.e. rdgs) for sets of words.
315 foreach ( $xn->childNodes ) {
316 my @rdg_set = _get_readings( $tradition, $_, $in_var, $ac, @cur_wits );
317 push( @sets, \@rdg_set ) if @rdg_set;
318 }
319 # Now collate these sets if we have more than one.
320 my $subs = collate_variants( $tradition->collation, @sets ) if @sets > 1;
321 map { $substitutions->{$_} = $subs->{$_} } keys %$subs;
322 # TODO Look through substitutions to see if we can make anything common now.
323 # Return the entire set of unique readings.
324 my %unique;
325 foreach my $s ( @sets ) {
326 map { $unique{$_->name} = $_ } @$s;
327 }
328 push( @new_readings, values( %unique ) );
329 # Exit the current app.
330 $current_app = '';
331 } elsif ( $xn->nodeName eq 'lem' || $xn->nodeName eq 'rdg' ) {
332 # Alter the current witnesses and recurse.
333 #print STDERR "Handling reading for " . $xn->getAttribute( 'wit' ) . "\n";
3bc0cd18 334 # TODO handle p.c. and s.l. designations too
910a0a6d 335 $ac = $xn->getAttribute( 'type' ) && $xn->getAttribute( 'type' ) eq 'a.c.';
3b853983 336 my @rdg_wits = _get_sigla( $xn );
a7fb3133 337 return unless @rdg_wits; # Skip readings that appear in no witnesses
910a0a6d 338 my @words;
339 foreach ( $xn->childNodes ) {
340 my @rdg_set = _get_readings( $tradition, $_, 1, $ac, @rdg_wits );
341 push( @words, @rdg_set ) if @rdg_set;
342 }
343 # If we have more than one word in a reading, it should become a segment.
344 # $tradition->collation->add_segment( @words ) if @words > 1;
345
346 if( $ac ) {
347 # Add the reading set to the a.c. readings.
348 foreach ( @rdg_wits ) {
349 $app_ac->{$_}->{$current_app} = \@words;
350 }
351 } else {
352 # Add the reading set to the app anchors for each witness
353 # or put in placeholders for empty p.c. readings
354 foreach ( @rdg_wits ) {
355 my $start = @words ? $words[0]->name : "PH-$current_app";
356 my $end = @words ? $words[-1]->name : "PH-$current_app";
357 $app_anchors->{$current_app}->{$_}->{'start'} = $start;
358 $app_anchors->{$current_app}->{$_}->{'end'} = $end;
359 push( @{$text->{$_}}, $start ) unless @words;
360 }
361 }
362 push( @new_readings, @words );
363 } elsif( $xn->nodeName eq 'witStart' ) {
364 # Add the relevant wit(s) to the active list.
365 #print STDERR "Handling witStart\n";
3bc0cd18 366 map { $active_wits{$_} = 1 } @cur_wits;
367 # Record a lacuna in all non-active witnesses if this is
368 # the first app. Get the full list from $text.
369 if( $seen_apps == 1 ) {
370 my $i = 0;
371 foreach my $sig ( keys %$text ) {
372 next if $active_wits{$sig};
373 my $l = $tradition->collation->add_lacuna( $current_app . "_$i" );
374 $i++;
375 push( @{$text->{$sig}}, $l );
376 }
377 }
910a0a6d 378 } elsif( $xn->nodeName eq 'witEnd' ) {
379 # Take the relevant wit(s) out of the list.
380 #print STDERR "Handling witEnd\n";
3bc0cd18 381 map { $active_wits{$_} = undef } @cur_wits;
eca16057 382 # Record a lacuna, unless this is the last app.
383 unless( $seen_apps == $app_count ) {
384 foreach my $i ( 0 .. $#cur_wits ) {
385 my $w = $cur_wits[$i];
386 my $l = $tradition->collation->add_lacuna( $current_app . "_$i" );
387 push( @{$text->{$w}}, $l );
388 }
389 }
a7fb3133 390 } elsif( $xn->nodeName eq 'witDetail'
391 || $xn->nodeName eq 'note' ) {
910a0a6d 392 # Ignore these for now.
393 return;
394 } else {
395 # Recurse as if this tag weren't there.
396 #print STDERR "Recursing on tag " . $xn->nodeName . "\n";
397 foreach( $xn->childNodes ) {
398 push( @new_readings, _get_readings( $tradition, $_, $in_var, $ac, @cur_wits ) );
399 }
400 }
401 return @new_readings;
402 }
403
404}
405
3b853983 406=begin testing
407
408use XML::LibXML;
409use XML::LibXML::XPathContext;
410use Text::Tradition::Parser::TEI;
411
412my $xml_str = '<tei><rdg wit="#A #B #C #D">some text</rdg></tei>';
413my $el = XML::LibXML->new()->parse_string( $xml_str )->documentElement;
414my $xpc = XML::LibXML::XPathContext->new( $el );
415my $obj = $xpc->find( '//rdg' );
416
417my @wits = Text::Tradition::Parser::TEI::_get_sigla( $obj );
418is( join( ' ', @wits) , "A B C D", "correctly parsed reading wit string" );
419
420=end testing
421
422=cut
423
910a0a6d 424# Helper to extract a list of witness sigla from a reading element.
3b853983 425sub _get_sigla {
f6066bac 426 my( $rdg ) = @_;
427 # Cope if we have been handed a NodeList. There is only
428 # one reading here.
429 if( ref( $rdg ) eq 'XML::LibXML::NodeList' ) {
910a0a6d 430 $rdg = $rdg->shift;
f6066bac 431 }
432
433 my @wits;
434 if( ref( $rdg ) eq 'XML::LibXML::Element' ) {
910a0a6d 435 my $witstr = $rdg->getAttribute( 'wit' );
a7fb3133 436 return () unless $witstr;
910a0a6d 437 $witstr =~ s/^\s+//;
438 $witstr =~ s/\s+$//;
439 @wits = split( /\s+/, $witstr );
440 map { $_ =~ s/^\#// } @wits;
f6066bac 441 }
442 return @wits;
443}
444
910a0a6d 445# Helper with its counters to actually make the readings.
f2b9605f 446{
447 my $word_ctr = 0;
448 my %used_nodeids;
449
3b853983 450 sub _save_preexisting_nodeids {
910a0a6d 451 foreach( @_ ) {
452 $used_nodeids{$_->getValue()} = 1;
453 }
454 }
455
3b853983 456 sub _make_reading {
910a0a6d 457 my( $graph, $word, $xml_id ) = @_;
458 if( $xml_id ) {
459 if( exists $used_nodeids{$xml_id} ) {
460 if( $used_nodeids{$xml_id} != 1 ) {
461 warn "Already used assigned XML ID somewhere else!";
462 $xml_id = undef;
463 }
464 } else {
465 warn "Undetected pre-existing XML ID";
466 }
467 }
468 if( !$xml_id ) {
469 until( $xml_id ) {
470 my $try_id = 'w'.$word_ctr++;
471 next if exists $used_nodeids{$try_id};
472 $xml_id = $try_id;
473 }
474 }
475 my $rdg = $graph->add_reading( $xml_id );
476 $rdg->text( $word );
477 $used_nodeids{$xml_id} = $rdg;
478 return $rdg;
f2b9605f 479 }
480}
481
f6066bac 4821;
3b853983 483
484=head1 BUGS / TODO
485
486=over
487
488=item * More unit testing
489
e867486f 490=item * Handle special designations apart from a.c.
491
492=item * Mark common nodes within collated variants
493
3b853983 494=back
495
496=head1 LICENSE
497
498This package is free software and is provided "as is" without express
499or implied warranty. You can redistribute it and/or modify it under
500the same terms as Perl itself.
501
502=head1 AUTHOR
503
504Tara L Andrews E<lt>aurum@cpan.orgE<gt>