calculate common readings when we parse
[scpubgit/stemmatology.git] / lib / Text / Tradition / Parser / JSON.pm
1 package Text::Tradition::Parser::JSON;
2
3 use strict;
4 use warnings;
5 use JSON qw/ from_json /;
6
7 =head1 NAME
8
9 Text::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
23 Parser module for Text::Tradition to read a JSON alignment table format such
24 as that produced by CollateX.
25
26 =head1 METHODS
27
28 =head2 B<parse>( $tradition, $option_hash )
29
30 Takes an initialized tradition and a set of options; creates the
31 appropriate nodes and edges on the graph, as well as the appropriate
32 witness objects.  The $option_hash must contain either a 'file' or a
33 'string' argument with the JSON structure to be parsed.
34
35 The 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
45 Longer lacunae in the text, to be disregarded in cladistic analysis, may be 
46 represented with the meta-reading '#LACUNA#'.  Multiple lacuna tags in sequence
47 are collapsed into a single multi-reading lacuna.
48
49 If a witness name ends in the collation's ac_label, it will be treated as
50 an extra layer of the 'main' witness whose sigil it shares.
51
52 =begin testing
53
54 use Text::Tradition;
55 binmode STDOUT, ":utf8";
56 binmode STDERR, ":utf8";
57 eval { no warnings; binmode $DB::OUT, ":utf8"; };
58
59 use_ok( 'Text::Tradition::Parser::JSON' );
60
61 open( JSFILE, 't/data/cx16.json' );
62 binmode JSFILE, ':utf8';
63 my @lines = <JSFILE>;
64 close JSFILE;
65
66 my $t = Text::Tradition->new(
67     'name' => 'json',
68     'input' => 'JSON',
69     'string' => join( '', @lines ),
70 );
71
72 is( ref( $t ), 'Text::Tradition', "Parsed a JSON alignment" );
73 if( $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
79 my %seen_wits;
80 map { $seen_wits{$_} = 0 } qw/ A B C /;
81 # Check that we have the right witnesses
82 foreach my $wit ( $t->witnesses ) {
83         $seen_wits{$wit->sigil} = 1;
84 }
85 is( scalar keys %seen_wits, 3, "No extra witnesses were made" );
86 foreach 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
91 foreach 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
97 =end testing
98
99 =cut
100
101 sub parse {
102         my( $tradition, $opts ) = @_;
103         my $c = $tradition->collation;
104         
105         my $table = from_json( $opts->{'string'} );
106         
107         # Create the witnesses
108         my @witnesses; # Keep the ordered list of our witnesses
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$/ ) {
116             $ac_wits{$sigil} = $1;
117         }
118     }
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         }
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 ) {
172         my $ac_wit = $tradition->witness( $a );
173         my $main_wit = $tradition->witness( $ac_wits{$a} );
174         next unless $main_wit;
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
189 Create 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
194 sub make_nodes {
195         my( $c, $idx, @tokens ) = @_;
196         my %unique;
197         my @readings;
198         my $commonctr = 0;
199         foreach my $j ( 0 .. $#tokens ) {
200                 if( $tokens[$j] ) {
201                         my $word = _restore_punct( $tokens[$j] );
202                         my $rdg;
203                         if( exists( $unique{$word} ) ) {
204                                 $rdg = $unique{$word};
205                         } else {
206                                 my %args = ( 'id' => join( ',', $idx, $j+1 ),
207                                         'rank' => $idx,
208                                         'text' => $word,
209                                         'collation' => $c );
210                                 if( $word eq '#LACUNA#' ) {
211                                         $args{'is_lacuna'} = 1 
212                                 } else {
213                                         $commonctr++;
214                                 }
215                                 $rdg = Text::Tradition::Collation::Reading->new( %args );
216                                 $unique{$word} = $rdg;
217                         }
218                         push( @readings, $rdg );
219                 } else {
220                         $commonctr++;
221                         push( @readings, undef );
222                 }
223         }
224         if( $commonctr == 1 ) {
225                 # Whichever reading isn't a lacuna is a common node.
226                 foreach my $rdg ( values %unique ) {
227                         next if $rdg->is_lacuna;
228                         $rdg->is_common( 1 );
229                 }
230         }
231         map { $c->add_reading( $_ ) } values( %unique );
232         return @readings;
233 }
234
235 # Utility function for parsing JSON from nCritic
236 sub _restore_punct {
237         my( $token ) = @_;
238         my $word = $token->{'t'};
239         return $word unless exists $token->{'punctuation'};
240         foreach my $p ( sort { $a->{pos} <=> $b->{pos} } @{$token->{'punctuation'}} ) {
241                 substr( $word, $p->{pos}, 0, $p->{char} );
242         }
243         return $word;
244 }       
245
246 1;
247
248 =head1 LICENSE
249
250 This package is free software and is provided "as is" without express
251 or implied warranty.  You can redistribute it and/or modify it under
252 the same terms as Perl itself.
253
254 =head1 AUTHOR
255
256 Tara L Andrews E<lt>aurum@cpan.orgE<gt>