add error handling for reading morphology update
[scpubgit/stemmatology.git] / stemmaweb / lib / stemmaweb / Controller / Relation.pm
CommitLineData
5c9ecf66 1package stemmaweb::Controller::Relation;
2376359f 2use Moose;
75ae2b25 3use Module::Load;
2376359f 4use namespace::autoclean;
581aee24 5use TryCatch;
2376359f 6
7BEGIN { extends 'Catalyst::Controller' }
8
9
10=head1 NAME
11
5c9ecf66 12stemmaweb::Controller::Relation - Controller for the relationship mapper
2376359f 13
14=head1 DESCRIPTION
15
581aee24 16The reading relationship mapper with draggable nodes.
2376359f 17
18=head1 METHODS
19
581aee24 20=head2 index
21
2376359f 22 GET relation/$textid
23
24Renders the application for the text identified by $textid.
25
2376359f 26=cut
27
72874569 28sub index :Path :Args(0) {
29 my( $self, $c ) = @_;
581aee24 30 $c->stash->{'template'} = 'relate.tt';
31}
32
72874569 33=head2 definitions
581aee24 34
1c0900ef 35 GET relation/definitions
581aee24 36
37Returns a data structure giving the valid types and scopes for a relationship.
38
39=cut
40
1c0900ef 41sub definitions :Local :Args(0) {
581aee24 42 my( $self, $c ) = @_;
d81fdda0 43 my $valid_relationships = [ qw/ spelling orthographic grammatical lexical transposition / ];
581aee24 44 my $valid_scopes = [ qw/ local global / ];
45 $c->stash->{'result'} = { 'types' => $valid_relationships, 'scopes' => $valid_scopes };
46 $c->forward('View::JSON');
2376359f 47}
48
72874569 49=head2 text
581aee24 50
72874569 51 GET relation/$textid/
52
53 Runs the relationship mapper for the specified text ID.
54
581aee24 55=cut
56
72874569 57sub text :Chained('/') :PathPart('relation') :CaptureArgs(1) {
58 my( $self, $c, $textid ) = @_;
93daee83 59 # If the tradition has more than 500 ranks or so, split it up.
60 my $tradition = $c->model('Directory')->tradition( $textid );
cccbf476 61 # Account for a bad interaction between FastCGI and KiokuDB
62 unless( $tradition->collation->tradition ) {
63 $c->log->warn( "Fixing broken tradition link" );
64 $tradition->collation->_set_tradition( $tradition );
65 $c->model('Directory')->save( $tradition );
66 }
22bb5720 67 # See how big the tradition is. Edges are more important than nodes
68 # when it comes to rendering difficulty.
69 my $numnodes = scalar $tradition->collation->readings;
70 my $numedges = scalar $tradition->collation->paths;
93daee83 71 my $length = $tradition->collation->end->rank;
22bb5720 72 # We should display no more than roughly 500 nodes, or roughly 700
73 # edges, at a time.
74 my $segments = $numnodes / 500;
75 if( $numedges / 700 > $segments ) {
76 $segments = $numedges / 700;
77 }
78 my $segsize = sprintf( "%.0f", $length / $segments );
79 my $margin = sprintf( "%.0f", $segsize / 10 );
80 if( $segments > 1 ) {
93daee83 81 # Segment the tradition in order not to overload the browser.
93daee83 82 my @divs;
83 my $r = 0;
22bb5720 84 while( $r + $margin < $length ) {
93daee83 85 push( @divs, $r );
22bb5720 86 $r += $segsize;
93daee83 87 }
88 $c->stash->{'textsegments'} = [];
22bb5720 89 $c->stash->{'segsize'} = $segsize;
90 $c->stash->{'margin'} = $margin;
0d51383b 91 foreach my $i ( 0..$#divs ) {
92 my $seg = { 'start' => $divs[$i] };
93 $seg->{'display'} = "Segment " . ($i+1);
93daee83 94 push( @{$c->stash->{'textsegments'}}, $seg );
95 }
96 }
97 $c->stash->{'textid'} = $textid;
98 $c->stash->{'tradition'} = $tradition;
72874569 99}
100
101sub main :Chained('text') :PathPart('') :Args(0) {
581aee24 102 my( $self, $c ) = @_;
93daee83 103 my $startseg = $c->req->param('start');
1c0900ef 104 my $tradition = delete $c->stash->{'tradition'};
105 my $collation = $tradition->collation;
93daee83 106 my $svgopts;
107 if( $startseg ) {
22bb5720 108 # Only render the subgraph from startseg to endseg or to END,
93daee83 109 # whichever is less.
22bb5720 110 my $endseg = $startseg + $c->stash->{'segsize'} + $c->stash->{'margin'};
93daee83 111 $svgopts = { 'from' => $startseg };
22bb5720 112 $svgopts->{'to'} = $endseg if $endseg < $collation->end->rank;
93daee83 113 } elsif( exists $c->stash->{'textsegments'} ) {
114 # This is the unqualified load of a long tradition. We implicitly start
115 # at zero, but go only as far as 550.
22bb5720 116 my $endseg = $c->stash->{'segsize'} + $c->stash->{'margin'};
0d51383b 117 $startseg = 0;
22bb5720 118 $svgopts = { 'to' => $endseg };
93daee83 119 }
120 my $svg_str = $collation->as_svg( $svgopts );
72874569 121 $svg_str =~ s/\n//gs;
0d51383b 122 $c->stash->{'startseg'} = $startseg if defined $startseg;
72874569 123 $c->stash->{'svg_string'} = $svg_str;
124 $c->stash->{'text_title'} = $tradition->name;
75ae2b25 125 $c->stash->{'text_lang'} = $tradition->language;
72874569 126 $c->stash->{'template'} = 'relate.tt';
581aee24 127}
128
75ae2b25 129=head2 help
130
131 GET relation/help/$language
132
133Returns the help window HTML.
134
135=cut
136
137sub help :Local :Args(1) {
138 my( $self, $c, $lang ) = @_;
139 # Display the morphological help for the language if it is defined.
140 if( $lang && $lang ne 'Default' ) {
141 my $mod = 'Text::Tradition::Language::' . $lang;
142 try {
143 load( $mod );
144 } catch {
145 $c->log->debug("Warning: could not load $mod");
146 }
147 my $has_mod = $mod->can('morphology_tags');
75ae2b25 148 if( $has_mod ) {
149 my $tagset = &$has_mod;
150 $c->stash->{'tagset'} = $tagset;
151 }
152 }
153 $c->stash->{'template'} = 'relatehelp.tt';
154}
155
581aee24 156=head2 relationships
157
93daee83 158 GET relation/$textid/relationships
72874569 159
160Returns the list of relationships defined for this text.
581aee24 161
93daee83 162 POST relation/$textid/relationships { request }
72874569 163
164Attempts to define the requested relationship within the text. Returns 200 on
165success or 403 on error.
581aee24 166
93daee83 167 DELETE relation/$textid/relationships { request }
72874569 168
581aee24 169
170=cut
171
72874569 172sub relationships :Chained('text') :PathPart :Args(0) {
581aee24 173 my( $self, $c ) = @_;
bff7bb42 174 my $tradition = delete $c->stash->{'tradition'};
175 my $collation = $tradition->collation;
7c280843 176 my $m = $c->model('Directory');
72874569 177 if( $c->request->method eq 'GET' ) {
178 my @pairs = $collation->relationships; # returns the edges
179 my @all_relations;
180 foreach my $p ( @pairs ) {
181 my $relobj = $collation->relations->get_relationship( @$p );
9251a7be 182 next if $relobj->type eq 'collated'; # Don't show these
cccbf476 183 next if $p->[0] eq $p->[1]; # HACK until bugfix
31aaf446 184 my $relhash = { source => $p->[0], target => $p->[1],
185 type => $relobj->type, scope => $relobj->scope };
186 $relhash->{'note'} = $relobj->annotation if $relobj->has_annotation;
187 push( @all_relations, $relhash );
72874569 188 }
189 $c->stash->{'result'} = \@all_relations;
190 } elsif( $c->request->method eq 'POST' ) {
191 my $node = $c->request->param('source_id');
192 my $target = $c->request->param('target_id');
193 my $relation = $c->request->param('rel_type');
194 my $note = $c->request->param('note');
195 my $scope = $c->request->param('scope');
196
197 my $opts = { 'type' => $relation,
31aaf446 198 'scope' => $scope };
199 $opts->{'annotation'} = $note if $note;
72874569 200
201 try {
202 my @vectors = $collation->add_relationship( $node, $target, $opts );
203 $c->stash->{'result'} = \@vectors;
7c280843 204 $m->save( $tradition );
72874569 205 } catch( Text::Tradition::Error $e ) {
206 $c->response->status( '403' );
207 $c->stash->{'result'} = { 'error' => $e->message };
208 }
209 } elsif( $c->request->method eq 'DELETE' ) {
210 my $node = $c->request->param('source_id');
211 my $target = $c->request->param('target_id');
212
213 try {
214 my @vectors = $collation->del_relationship( $node, $target );
7c280843 215 $m->save( $tradition );
72874569 216 $c->stash->{'result'} = \@vectors;
217 } catch( Text::Tradition::Error $e ) {
218 $c->response->status( '403' );
219 $c->stash->{'result'} = { 'error' => $e->message };
220 }
581aee24 221 }
581aee24 222 $c->forward('View::JSON');
a8928d1d 223}
224
225=head2 readings
226
227 GET relation/$textid/readings
228
229Returns the list of readings defined for this text along with their metadata.
230
231=cut
232
3ba238d4 233my %read_write_keys = (
234 'id' => 0,
235 'text' => 0,
236 'is_meta' => 0,
237 'grammar_invalid' => 1,
238 'is_nonsense' => 1,
239 'normal_form' => 1,
240);
241
a8928d1d 242sub _reading_struct {
243 my( $reading ) = @_;
244 # Return a JSONable struct of the useful keys. Keys meant to be writable
245 # have a true value; read-only keys have a false value.
a8928d1d 246 my $struct = {};
247 map { $struct->{$_} = $reading->$_ } keys( %read_write_keys );
248 # Special case
249 $struct->{'lexemes'} = [ $reading->lexemes ];
3ba238d4 250 # Look up any words related via spelling or orthography
251 my $sameword = sub {
252 my $t = $_[0]->type;
253 return $t eq 'spelling' || $t eq 'orthographic';
254 };
255 my @variants;
256 foreach my $sr ( $reading->related_readings( $sameword ) ) {
257 push( @variants, $sr->text );
258 }
259 $struct->{'variants'} = \@variants;
a8928d1d 260 return $struct;
261}
262
263sub readings :Chained('text') :PathPart :Args(0) {
264 my( $self, $c ) = @_;
265 my $tradition = delete $c->stash->{'tradition'};
266 my $collation = $tradition->collation;
267 my $m = $c->model('Directory');
268 if( $c->request->method eq 'GET' ) {
269 my $rdginfo = {};
270 foreach my $rdg ( $collation->readings ) {
271 $rdginfo->{$rdg->id} = _reading_struct( $rdg );
272 }
273 $c->stash->{'result'} = $rdginfo;
274 }
275 $c->forward('View::JSON');
276}
277
278=head2 reading
279
280 GET relation/$textid/reading/$id
281
282Returns the list of readings defined for this text along with their metadata.
283
284 POST relation/$textid/reading/$id { request }
285
286Alters the reading according to the values in request. Returns 403 Forbidden if
287the alteration isn't allowed.
288
289=cut
290
291sub reading :Chained('text') :PathPart :Args(1) {
292 my( $self, $c, $reading_id ) = @_;
293 my $tradition = delete $c->stash->{'tradition'};
294 my $collation = $tradition->collation;
3ba238d4 295 my $rdg = $collation->reading( $reading_id );
a8928d1d 296 my $m = $c->model('Directory');
297 if( $c->request->method eq 'GET' ) {
a8928d1d 298 $c->stash->{'result'} = $rdg ? _reading_struct( $rdg )
299 : { 'error' => "No reading with ID $reading_id" };
300 } elsif ( $c->request->method eq 'POST' ) {
a7f4020a 301 my $errmsg;
3ba238d4 302 # Are we re-lemmatizing?
303 if( $c->request->param('relemmatize') ) {
304 my $nf = $c->request->param('normal_form');
305 # TODO throw error unless $nf
306 $rdg->normal_form( $nf );
4aed7cc5 307 # TODO throw error if lemmatization fails
a7f4020a 308 # TODO skip this if normal form hasn't changed
3ba238d4 309 $rdg->lemmatize();
310 } else {
311 # Set all the values that we have for the reading.
312 # TODO error handling
313 foreach my $p ( keys %{$c->request->params} ) {
314 if( $p =~ /^morphology_(\d+)$/ ) {
315 # Set the form on the correct lexeme
316 my $midx = $1;
317 $c->log->debug( "Fetching lexeme $midx" );
318 my $lx = $rdg->lexeme( $midx );
319 my $strrep = $rdg->language . ' // '
320 . $c->request->param( $p );
321 my $idx = $lx->has_form( $strrep );
322 unless( defined $idx ) {
323 # Make the word form and add it to the lexeme.
324 $c->log->debug("Adding new form for $strrep");
a7f4020a 325 try {
326 $idx = $lx->add_matching_form( $strrep ) - 1;
327 } catch( Text::Tradition::Error $e ) {
328 $c->response->status( '403' );
329 $errmsg = $e->message;
330 }
3ba238d4 331 }
a7f4020a 332 $lx->disambiguate( $idx ) if defined $idx;
3ba238d4 333 } elsif( $read_write_keys{$p} ) {
4aed7cc5 334 my $val = _clean_booleans( $rdg, $p, $c->request->param( $p ) );
335 $rdg->$p( $val );
3ba238d4 336 }
337 }
338 }
339 $m->save( $tradition );
a7f4020a 340 $c->stash->{'result'} = $errmsg ? { 'error' => $errmsg }
341 : _reading_struct( $rdg );
3ba238d4 342
a8928d1d 343 }
344 $c->forward('View::JSON');
345
346}
581aee24 347
4aed7cc5 348sub _clean_booleans {
349 my( $rdg, $param, $val ) = @_;
350 if( $rdg->meta->get_attribute( $param )->type_constraint->name eq 'Bool' ) {
351 $val = 1 if $val eq 'true';
352 $val = undef if $val eq 'false';
353 }
354 return $val;
355}
356
2376359f 357=head2 end
358
359Attempt to render a view, if needed.
360
361=cut
362
363sub end : ActionClass('RenderView') {}
364
365=head1 AUTHOR
366
367Tara L Andrews
368
369=head1 LICENSE
370
371This library is free software. You can redistribute it and/or modify
372it under the same terms as Perl itself.
373
374=cut
375
376__PACKAGE__->meta->make_immutable;
377
3781;