start using witness->text and ->layertext for consistency checking
[scpubgit/stemmatology.git] / lib / Text / Tradition / Parser / JSON.pm
CommitLineData
a731e73a 1package Text::Tradition::Parser::JSON;
2
3use strict;
4use warnings;
5use JSON qw/ from_json /;
6
7=head1 NAME
8
9Text::Tradition::Parser::JSON
10
11=head1 SYNOPSIS
12
13 use Text::Tradition;
14
15 my $tradition = Text::Tradition->new(
16 'name' => 'my text',
17 'input' => 'JSON',
18 'string' => $json_encoded_utf8,
19 );
20
21=head1 DESCRIPTION
22
23Parser module for Text::Tradition to read a JSON alignment table format such
24as that produced by CollateX.
25
26=head1 METHODS
27
28=head2 B<parse>( $tradition, $option_hash )
29
30Takes an initialized tradition and a set of options; creates the
31appropriate nodes and edges on the graph, as well as the appropriate
32witness objects. The $option_hash must contain either a 'file' or a
33'string' argument with the JSON structure to be parsed.
34
35The structure of the JSON is thus:
36
37 { alignment => [ { witness => "SIGIL",
38 tokens => [ { t => "TEXT" }, ... ] },
39 { witness => "SIG2",
40 tokens => [ { t => "TEXT" }, ... ] },
41 ... ],
42 };
43
44
45Longer lacunae in the text, to be disregarded in cladistic analysis, may be
46represented with the meta-reading '#LACUNA#'. Multiple lacuna tags in sequence
47are collapsed into a single multi-reading lacuna.
48
49If a witness name ends in the collation's ac_label, it will be treated as
50an extra layer of the 'main' witness whose sigil it shares.
51
52=begin testing
53
54use Text::Tradition;
55binmode STDOUT, ":utf8";
56binmode STDERR, ":utf8";
57eval { no warnings; binmode $DB::OUT, ":utf8"; };
58
59use_ok( 'Text::Tradition::Parser::JSON' );
60
61open( JSFILE, 't/data/cx16.json' );
62binmode JSFILE, ':utf8';
63my @lines = <JSFILE>;
64close JSFILE;
65
66my $t = Text::Tradition->new(
67 'name' => 'json',
68 'input' => 'JSON',
69 'string' => join( '', @lines ),
70);
71
72is( ref( $t ), 'Text::Tradition', "Parsed a JSON alignment" );
73if( $t ) {
74 is( scalar $t->collation->readings, 26, "Collation has all readings" );
75 is( scalar $t->collation->paths, 32, "Collation has all paths" );
76 is( scalar $t->witnesses, 3, "Collation has all witnesses" );
77}
78
b0b4421a 79my %seen_wits;
80map { $seen_wits{$_} = 0 } qw/ A B C /;
81# Check that we have the right witnesses
82foreach my $wit ( $t->witnesses ) {
83 $seen_wits{$wit->sigil} = 1;
84}
85is( scalar keys %seen_wits, 3, "No extra witnesses were made" );
86foreach my $k ( keys %seen_wits ) {
87 ok( $seen_wits{$k}, "Witness $k still exists" );
88}
89
90# Check that the witnesses have the right texts
91foreach my $wit ( $t->witnesses ) {
92 my $origtext = join( ' ', @{$wit->text} );
93 my $graphtext = $t->collation->path_text( $wit->sigil );
94 is( $graphtext, $origtext, "Collation matches original for witness " . $wit->sigil );
95}
96
a731e73a 97=end testing
98
99=cut
100
101sub parse {
102 my( $tradition, $opts ) = @_;
103 my $c = $tradition->collation;
104
105 my $table = from_json( $opts->{'string'} );
106
107 # Create the witnesses
30f0df34 108 my @witnesses; # Keep the ordered list of our witnesses
a731e73a 109 my %ac_wits; # Track these for later removal
110 foreach my $sigil ( map { $_->{'witness'} } @{$table->{'alignment'}} ) {
111 my $wit = $tradition->add_witness( 'sigil' => $sigil );
112 $wit->path( [ $c->start ] );
113 push( @witnesses, $wit );
114 my $aclabel = $c->ac_label;
115 if( $sigil =~ /^(.*)\Q$aclabel\E$/ ) {
b0b4421a 116 $ac_wits{$sigil} = $1;
a731e73a 117 }
118 }
b0b4421a 119
120 # Save the original witness text for consistency checking. We do this
121 # in a separate loop to make sure we have all base witnesses defined,
122 # and to make sure that our munging and comparing later doesn't affect
123 # the original text.
124 foreach my $intext ( @{$table->{'alignment'}} ) {
125 my $rs = $intext->{'witness'};
126 my $is_layer = exists $ac_wits{$rs};
127 my $wit = $tradition->witness( $is_layer ? $ac_wits{$rs} : $rs );
128 my @tokens = grep { $_ && $_->{'t'} !~ /^\#.*\#$/ } @{$intext->{'tokens'}};
129 my @words = map { _restore_punct( $_ ) } @tokens;
130 $is_layer ? $wit->layertext( \@words ) : $wit->text( \@words );
131 }
a731e73a 132
133 # Create the readings in each row
134 my $length = exists $table->{'length'}
135 ? $table->{'length'}
136 : scalar @{$table->{'alignment'}->[0]->{'tokens'}};
137
138 foreach my $idx ( 0 .. $length - 1 ) {
139 my @tokens = map { $_->{'tokens'}->[$idx] } @{$table->{'alignment'}};
140 my @readings = make_nodes( $c, $idx, @tokens );
141 foreach my $w ( 0 .. $#readings ) {
142 # push the appropriate node onto the appropriate witness path
143 my $rdg = $readings[$w];
144 if( $rdg ) {
145 my $wit = $witnesses[$w];
146 push( @{$wit->path}, $rdg );
147 } # else skip it for empty readings.
148 }
149 }
150
151 # Collapse our lacunae into a single node and
152 # push the end node onto all paths.
153 $c->end->rank( $length );
154 foreach my $wit ( @witnesses ) {
155 my $p = $wit->path;
156 my $last_rdg = shift @$p;
157 my $new_p = [ $last_rdg ];
158 foreach my $rdg ( @$p ) {
159 # Omit the reading if we are in a lacuna already.
160 next if $rdg->is_lacuna && $last_rdg->is_lacuna;
161 # Save the reading otherwise.
162 push( @$new_p, $rdg );
163 $last_rdg = $rdg;
164 }
165 push( @$new_p, $c->end );
166 $wit->path( $new_p );
167 }
168
169 # Fold any a.c. witnesses into their main witness objects, and
170 # delete the independent a.c. versions.
171 foreach my $a ( keys %ac_wits ) {
b0b4421a 172 my $ac_wit = $tradition->witness( $a );
173 my $main_wit = $tradition->witness( $ac_wits{$a} );
a731e73a 174 next unless $main_wit;
a731e73a 175 $main_wit->uncorrected_path( $ac_wit->path );
176 $tradition->del_witness( $ac_wit );
177 }
178
179 # Join up the paths.
180 $c->make_witness_paths;
181 # Delete our unused lacuna nodes.
182 foreach my $rdg ( grep { $_->is_lacuna } $c->readings ) {
183 $c->del_reading( $rdg ) unless $c->reading_witnesses( $rdg );
184 }
185}
186
187=head2 make_nodes( $collation, $index, @tokenlist )
188
189Create readings from the unique tokens in @tokenlist, and set their rank to
190$index. Returns an array of readings of the same size as the original @tokenlist.
191
192=cut
193
194sub make_nodes {
195 my( $c, $idx, @tokens ) = @_;
196 my %unique;
30f0df34 197 my @readings;
198 foreach my $j ( 0 .. $#tokens ) {
199 if( $tokens[$j] ) {
b0b4421a 200 my $word = _restore_punct( $tokens[$j] );
30f0df34 201 my $rdg;
b0b4421a 202 if( exists( $unique{$word} ) ) {
203 $rdg = $unique{$word};
30f0df34 204 } else {
205 my %args = ( 'id' => join( ',', $idx, $j+1 ),
b0b4421a 206 'text' => $word,
30f0df34 207 'collation' => $c );
b0b4421a 208 $args{'is_lacuna'} = 1 if $word eq '#LACUNA#';
30f0df34 209 $rdg = Text::Tradition::Collation::Reading->new( %args );
b0b4421a 210 $unique{$word} = $rdg;
30f0df34 211 }
212 push( @readings, $rdg );
213 } else {
214 push( @readings, undef );
215 }
a731e73a 216 }
217 map { $c->add_reading( $_ ) } values( %unique );
30f0df34 218 return @readings;
a731e73a 219}
220
b0b4421a 221# Utility function for parsing JSON from nCritic
222sub _restore_punct {
223 my( $token ) = @_;
224 my $word = $token->{'t'};
225 return $word unless exists $token->{'punctuation'};
226 foreach my $p ( sort { $a->{pos} <=> $b->{pos} } @{$token->{'punctuation'}} ) {
227 substr( $word, $p->{pos}, 0, $p->{char} );
228 }
229 return $word;
230}
231
a731e73a 2321;
233
234=head1 LICENSE
235
236This package is free software and is provided "as is" without express
237or implied warranty. You can redistribute it and/or modify it under
238the same terms as Perl itself.
239
240=head1 AUTHOR
241
242Tara L Andrews E<lt>aurum@cpan.orgE<gt>