load extensions statically to avoid bad object wrapping interactions
[scpubgit/stemmatology.git] / base / lib / Text / Tradition.pm
1 package Text::Tradition;
2
3 use JSON qw / from_json /;
4 use Module::Load;
5 use Moose;
6 use Moose::Util qw/ does_role apply_all_roles /;
7 use Text::Tradition::Collation;
8 use Text::Tradition::Error;
9 use Text::Tradition::Witness;
10 use Text::Tradition::User;
11 use TryCatch;
12
13 use vars qw( $VERSION );
14 $VERSION = "1.1";
15
16 # Enable plugin(s) if available
17 eval { with 'Text::Tradition::HasStemma'; };
18 if( $@ ) {
19         warn "Text::Tradition::Analysis not found. Disabling stemma analysis functionality";
20 };
21
22 has 'collation' => (
23     is => 'ro',
24     isa => 'Text::Tradition::Collation',
25     writer => '_save_collation',
26     );
27
28 has 'witness_hash' => (
29     traits => ['Hash'],
30     isa => 'HashRef[Text::Tradition::Witness]',
31     handles => {
32         witness     => 'get',
33         add_witness => 'set',
34         del_witness => 'delete',
35         has_witness => 'exists',
36         witnesses   => 'values',
37     },
38     default => sub { {} },
39     );
40
41 has 'name' => (
42     is => 'rw',
43     isa => 'Str',
44     default => 'Tradition',
45     );
46     
47 has 'language' => (
48         is => 'rw',
49         isa => 'Str',
50         predicate => 'has_language',
51         );
52     
53 has '_initialized' => (
54         is => 'ro',
55         isa => 'Bool',
56         default => undef,
57         writer => '_init_done',
58         ); 
59
60 has 'user' => (
61     is => 'rw',
62     isa => 'Text::Tradition::User',
63     required => 0,
64     predicate => 'has_user',
65     clearer => 'clear_user',
66     weak_ref => 1
67     );
68
69 has 'public' => (
70     is => 'rw',
71     isa => 'Bool',
72     required => 0,
73     default => sub { 0; },
74     );
75
76 # Create the witness before trying to add it
77 around 'add_witness' => sub {
78     my $orig = shift;
79     my $self = shift;
80     # TODO allow add of a Witness object?
81     my %args = @_ == 1 ? %{$_[0]} : @_;
82     $args{'tradition'} = $self;
83     $args{'language'} = $self->language 
84         if( $self->language && !exists $args{'language'} );
85     my $new_wit = Text::Tradition::Witness->new( %args );
86     $self->$orig( $new_wit->sigil => $new_wit );
87     return $new_wit;
88 };
89
90 # Allow deletion of witness by object as well as by sigil
91 around 'del_witness' => sub {
92     my $orig = shift;
93     my $self = shift;
94     my @key_args;
95     foreach my $arg ( @_ ) {
96         push( @key_args, 
97               ref( $arg ) eq 'Text::Tradition::Witness' ? $arg->sigil : $arg );
98     }
99     return $self->$orig( @key_args );
100 };
101
102 # Don't allow an empty hash value
103 around 'witness' => sub {
104     my( $orig, $self, $arg ) = @_;
105     return unless $self->has_witness( $arg );
106     return $self->$orig( $arg );
107 };
108
109 =head1 NAME
110
111 Text::Tradition - a software model for a set of collated texts
112
113 =head1 SYNOPSIS
114
115   use Text::Tradition;
116   my $t = Text::Tradition->new( 
117     'name' => 'this is a text',
118     'input' => 'TEI',
119     'file' => '/path/to/tei_parallel_seg_file.xml' );
120
121   my @text_wits = $t->witnesses();
122   my $manuscript_a = $t->witness( 'A' );
123
124   $t = Text::Tradition->new();
125   $t->add_witness( 'sourcetype' => 'xmldesc', 
126     'file' => '/path/to/teitranscription.xml' );
127   $t->add_witness( 'sourcetype => 'plaintext', 'sigil' => 'Q',
128     'string' => 'The quick brown fox jumped over the lazy dogs' );
129   ## TODO
130   $t->collate_texts;
131   
132   my $text_path_svg = $t->collation->as_svg();
133   ## See Text::Tradition::Collation for more on text collation itself
134     
135 =head1 DESCRIPTION
136
137 Text::Tradition is a library for representation and analysis of collated
138 texts, particularly medieval ones.  A 'tradition' refers to the aggregation
139 of surviving versions of a text, generally preserved in multiple
140 manuscripts (or 'witnesses').  A Tradition object thus has one more more
141 Witnesses, as well as a Collation that represents the unity of all versions
142 of the text.
143
144 =head1 METHODS
145
146 =head2 new
147
148 Creates and returns a new text tradition object.  The following options are
149 accepted.
150
151 General options:
152
153 =over 4
154
155 =item B<name> - The name of the text.
156
157 =back
158
159 Initialization based on a collation file:
160
161 =over 4
162
163 =item B<input> - The input format of the collation file.  Can be one of the
164 following:
165
166 =over 4
167
168 =item * Self - a GraphML format produced by this module
169
170 =item * CollateX - a GraphML format produced by CollateX
171
172 =item * CTE - a TEI XML format produced by Classical Text Editor
173
174 =item * JSON - an alignment table in JSON format, as produced by CollateX and 
175 other tools
176
177 =item * TEI - a TEI parallel segmentation format file
178
179 =item * Tabular - a spreadsheet collation.  See the documentation for 
180 L<Text::Tradition::Parser::Tabular> for an explanation of additional options.
181
182 =back
183
184 =item B<file> - The name of the file that contains the data.  One of 'file'
185 or 'string' should be specified.
186
187 =item B<string> - A text string that contains the data.  One of 'file' or
188 'string' should be specified.
189
190 =back
191
192 Initialization based on a list of witnesses [NOT YET IMPLEMENTED]:
193
194 =over 4
195
196 =item B<witnesses> - A reference to an array of Text::Tradition::Witness
197 objects that carry the text to be collated.
198
199 =item B<collator> - A reference to a collation program that will accept
200 Witness objects.
201
202 =back
203
204 =head2 B<witnesses>
205
206 Return the Text::Tradition::Witness objects associated with this tradition,
207 as an array.
208
209 =head2 B<witness>( $sigil )
210
211 Returns the Text::Tradition::Witness object whose sigil is $sigil, or undef
212 if there is no such object within the tradition.
213
214 =head2 B<add_witness>( %opts )
215
216 Instantiate a new witness with the given options (see documentation for
217 Text::Tradition::Witness) and add it to the tradition.
218
219 =head2 B<del_witness>( $sigil )
220
221 Delete the witness with the given sigil from the tradition.  Returns the
222 witness object for the deleted witness.
223
224 =begin testing
225
226 use_ok( 'Text::Tradition', "can use module" );
227
228 my $t = Text::Tradition->new( 'name' => 'empty' );
229 is( ref( $t ), 'Text::Tradition', "initialized an empty Tradition object" );
230 is( $t->name, 'empty', "object has the right name" );
231 is( scalar $t->witnesses, 0, "object has no witnesses" );
232
233 my $simple = 't/data/simple.txt';
234 my $s = Text::Tradition->new( 
235     'name'  => 'inline', 
236     'input' => 'Tabular',
237     'file'  => $simple,
238     );
239 is( ref( $s ), 'Text::Tradition', "initialized a Tradition object" );
240 is( $s->name, 'inline', "object has the right name" );
241 is( scalar $s->witnesses, 3, "object has three witnesses" );
242
243 my $wit_a = $s->witness('A');
244 is( ref( $wit_a ), 'Text::Tradition::Witness', "Found a witness A" );
245 if( $wit_a ) {
246     is( $wit_a->sigil, 'A', "Witness A has the right sigil" );
247 }
248 is( $s->witness('X'), undef, "There is no witness X" );
249 ok( !exists $s->{'witnesses'}->{'X'}, "Witness key X not created" );
250
251 my $wit_d = $s->add_witness( 'sigil' => 'D', 'sourcetype' => 'collation' );
252 is( ref( $wit_d ), 'Text::Tradition::Witness', "new witness created" );
253 is( $wit_d->sigil, 'D', "witness has correct sigil" );
254 is( scalar $s->witnesses, 4, "object now has four witnesses" );
255
256 my $del = $s->del_witness( 'D' );
257 is( $del, $wit_d, "Deleted correct witness" );
258 is( scalar $s->witnesses, 3, "object has three witnesses again" );
259
260 # TODO test initialization by witness list when we have it
261
262 =end testing
263
264 =cut
265     
266
267 sub BUILD {
268     my( $self, $init_args ) = @_;
269     
270     # First, make a collation object. This will use only those arguments in
271     # init_args that apply to the collation.
272         my $collation = Text::Tradition::Collation->new( %$init_args,
273                                                                                                         'tradition' => $self );
274         $self->_save_collation( $collation );
275
276     if( exists $init_args->{'input'} ) {
277         # Call the appropriate parser on the given data
278         my @format_standalone = qw/ Self CollateText CollateX CTE JSON TEI Tabular /;
279         my @format_basetext = qw/ KUL /;
280         my $use_base;
281         my $format = $init_args->{'input'};
282         if( $format && !( grep { $_ eq $format } @format_standalone )
283             && !( grep { $_ eq $format } @format_basetext ) ) {
284             warn "Unrecognized input format $format; not parsing";
285             return;
286         }
287         if( $format && grep { $_ eq $format } @format_basetext ) {
288             $use_base = 1;
289             if( !exists $init_args->{'base'} ) {
290                 warn "Cannot make a collation from $format without a base text";
291                 return;
292             }
293         }
294
295         # Now do the parsing. 
296         if( $format ) {
297             if( $use_base ) { 
298                 $format = 'BaseText';   # Use the BaseText module for parsing,
299                                         # but retain the original input arg.
300             }
301             my $mod = "Text::Tradition::Parser::$format";
302             load( $mod );
303             $mod->can('parse')->( $self, $init_args );
304         }
305     }
306     $self->_init_done( 1 );
307     return $self;
308 }
309
310 =head2 add_json_witnesses( $jsonstring, $options )
311
312 Adds a set of witnesses from a JSON array specification. This is a wrapper
313 to parse the JSON and call add_witness (with the specified $options) for
314 each element therein.
315
316 =cut
317
318 sub add_json_witnesses {
319         my( $self, $jsonstr, $extraopts ) = @_;
320         my $witarray = from_json( $jsonstr );
321         foreach my $witspec ( @{$witarray->{witnesses}} ) {
322                 my $opts = $extraopts || {};
323                 $opts->{'sourcetype'} = 'json';
324                 $opts->{'object'} = $witspec;
325                 $self->add_witness( $opts );
326         }
327 }
328
329 =head2 lemmatize
330
331 Calls the appropriate lemmatization function for the language of the
332 tradition. Will throw an error if the Morphology package is not installed.
333
334 =cut
335
336 # TODO find a better way to hook this
337 sub lemmatize {
338         my $self = shift;
339         unless( $self->has_language ) {
340                 warn "Please set a language to lemmatize a tradition";
341                 return;
342         }
343         my $mod = "Text::Tradition::Language::" . $self->language;
344         load( $mod );
345         $mod->can( 'lemmatize' )->( $self );
346 }
347
348 sub throw {
349         Text::Tradition::Error->throw( 
350                 'ident' => 'Tradition error',
351                 'message' => $_[0],
352                 );
353 }
354
355 no Moose;
356 __PACKAGE__->meta->make_immutable;
357
358
359 =head1 BUGS / TODO
360
361 =over
362
363 =item * Allow tradition to be initialized via passing to a collator.
364
365 =back
366
367 =head1 LICENSE
368
369 This package is free software and is provided "as is" without express
370 or implied warranty.  You can redistribute it and/or modify it under
371 the same terms as Perl itself.
372
373 =head1 AUTHOR
374
375 Tara L Andrews E<lt>aurum@cpan.orgE<gt>