-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathstructure.py
executable file
·680 lines (579 loc) · 27.4 KB
/
structure.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
The main interface for editing RST structures. Reads a document and sets up the initial layout of
HTML elements representing RST nodes and their connections (using calls to jsPlumb). Further
manipulations of the interface are managed by script/structure.js.
Author: Amir Zeldes
"""
import cgitb
from modules.rstweb_sql import *
import codecs
import sys
import cgi
import os
import datetime
import json
import _version
from six import itervalues
from modules.configobj import ConfigObj
from modules.pathutils import *
from modules.logintools import login
def build_canvas(current_doc, current_project, rels, nodes, secedge_data="", def_rstrel="", def_multirel="", signal_data=None, user=None, show_signals=True, validations=None, signal_type_dict=None):
###GRAPHICAL PARAMETERS###
top_spacing = 20
layer_spacing = 60
if signal_data is None:
signal_data = []
if validations is None:
validations = get_project_validations(current_project)
cpout = '<div id="container" class="container">\n'
if show_signals:
cpout += ''' <button id="show-all-signals">
Show All Signal Tokens
</button>\n'''
cpout += '''<ul class='custom-menu' data-action="">
<li data-action="quick_delete_signals">Delete signals</li>
</ul>\n''' # Signal context menu on right click token
cpout += ''' <div class="signal-drawer">
<div id="signal-list"> </div>
<div class="signal-drawer__row">
<button id="new-signal" class="signal-drawer__create-new-button">
<i class="fa fa-plus" title="New Signal"> </i>
New Signal
</button>
</div>
<div class="signal-drawer__row" style="text-align: center;padding-top:20px;">
<button id="save-signals" class="signal-drawer__save-button">
<i class="fa fa-check"> </i>
Save Changes
</button>
<button id="cancel-signals" class="signal-drawer__cancel-button">
<i class="fa fa-ban"> </i>
Cancel
</button>
</div>
</div>
'''
cpout += '''<div id="canvas" class="canvas">'''
cpout += '\t<p id="document_name">Document: <b>' + current_doc + '</b> (project: <i>' + current_project + '</i>)</p>'
cpout += '''<div id="inner_canvas">'''
cpout += '<script src="./script/structure.js"></script>'
multi_options = ""
rst_options = ""
rel_list = []
rel_kinds = {}
if def_rstrel == "":
def_rstrel = sorted([rel[0] for rel in rels if rel[1] != "multinuc"])[0] # Take alphabetically first rel
if def_rstrel == "":
def_rstrel = "elaboration-additional_r"
if def_multirel == "":
multirels = sorted([rel[0] for rel in rels if rel[1] == "multinuc"])
if len(multirels) > 0:
def_multirel = multirels[0] # Take alphabetically first rel
if def_multirel == "":
def_multirel = "joint-other_m"
for rel in rels:
rel_list.append(rel[0])
if rel[1] == "multinuc":
multi_options += "<option value='" + rel[0] + "'>" + rel[0].replace("_m", "") + '</option>\n'
rel_kinds[rel[0]] = "multinuc"
else:
rst_options += "<option value='" + rel[0] + "'>" + rel[0].replace("_r", "") + '</option>\n'
rel_kinds[rel[0]] = "rst"
rel_list.sort()
multi_options += "<option value='" + def_rstrel + "'>(satellite...)</option>\n"
for key in nodes:
node = nodes[key]
get_depth(node, node, nodes, doc=current_doc, project=current_project, user=user)
for key in nodes:
if nodes[key].kind == "edu":
get_left_right(key, nodes, 0, 0, rel_kinds)
signals = {}
for signal in signal_data:
s_id, s_type, subtype, tokens = signal
if s_id not in signals:
signals[s_id] = list()
if tokens:
tokens = list(map(int, tokens.split(",")))
else:
tokens = []
signals[s_id].append({'type': s_type,
'subtype': subtype,
'tokens': tokens})
if signal_type_dict is None:
signal_type_dict = get_signal_types_dict(current_doc, current_project)
cpout += '<script>'
cpout += 'window.rstWebSignals = ' + json.dumps(signals) + ';'
cpout += 'window.rstWebSignalTypes = ' + json.dumps(signal_type_dict,
sort_keys=True) + ';'
cpout += 'window.rstWebDefaultSignalType = Object.keys(window.rstWebSignalTypes)[0];'
cpout += 'if (window.rstWebDefaultSignalType != null) {window.rstWebDefaultSignalSubtype = window.rstWebSignalTypes[window.rstWebDefaultSignalType][0];}'
cpout += '</script>'
anchors = {}
pix_anchors = {}
#dbpath = os.path.dirname(os.path.realpath(__file__)) + os.sep + "rstweb.db"
#conn = sqlite3.connect(dbpath)
#cur = conn.cursor()
# Calculate anchor points for nodes
# First get proportional position for anchor
#nodes_data = get_multinuc_nodes_data(cur, current_doc, current_project, user)
#id, parent, left, right
nodes_data = [[n.id, n.parent, n.left, n.right] for n in itervalues(nodes) if n.relkind == "multinuc"]
#doc_relname_to_reltype = get_doc_relname_to_reltype(cur, current_doc, current_project)
doc_relname_to_reltype = {"span": "span", "": "span"}
doc_relname_to_reltype.update(rel_kinds)
node_to_lr = {}
for node in nodes_data:
if not node[1] in node_to_lr:
node_to_lr[node[1]] = {
'left': {},
'right': {}
}
if not node[2] in node_to_lr[node[1]]['left']:
node_to_lr[node[1]]['left'][node[2]] = node[0]
if not node[3] in node_to_lr[node[1]]['right']:
node_to_lr[node[1]]['right'][node[3]] = node[0]
for key in sorted(nodes, key=lambda id: nodes[id].depth, reverse=True):
node = nodes[key]
if node.kind == "edu":
anchors[node.id] = "0.5"
if node.parent != "0":
parent = nodes[node.parent]
parent_wid = (parent.right - parent.left + 1) * 100 - 4
child_wid = (node.right - node.left + 1) * 100 - 4
if node.relname == "span":
if node.id in anchors:
anchors[parent.id] = str(
((node.left - parent.left) * 100) / parent_wid + float(anchors[node.id]) * float(
child_wid / parent_wid))
else:
anchors[parent.id] = str(
((node.left - parent.left) * 100) / parent_wid + (0.5 * child_wid) / parent_wid)
elif node.relkind == "multinuc" and parent.kind == "multinuc":
# For multinucs, the anchor is in the middle between leftmost and rightmost of the multinuc children
# (not including other rst children)
node_lr = node_to_lr[node.parent]
lr = [min(node_lr['left'].keys()), max(node_lr['right'].keys())]
lr_wid = (lr[0] + lr[1]) / 2
lr_ids = (node_to_lr[node.parent]['left'][lr[0]], node_to_lr[node.parent]['right'][lr[1]])
left_child = lr_ids[0]
right_child = lr_ids[1]
if left_child == right_child:
anchors[parent.id] = "0.5"
else:
if left_child in anchors and right_child in anchors: # both leftmost and rightmost multinuc children have been found
len_left = nodes[left_child].right - nodes[left_child].left + 1
len_right = nodes[right_child].right - nodes[right_child].left + 1
anchors[parent.id] = str(((float(anchors[left_child]) * len_left * 100 + float(
anchors[right_child]) * len_right * 100 + (nodes[
right_child].left - parent.left) * 100) / 2) / parent_wid)
else:
anchors[parent.id] = str((lr_wid - parent.left + 1) / (parent.right - parent.left + 1))
else:
if not parent.id in anchors:
anchors[parent.id] = "0.5"
# Place anchor element to center on proportional position relative to parent
for key in nodes:
node = nodes[key]
pix_anchors[node.id] = str(
int(3 + node.left * 100 - 100 - 39 + float(anchors[node.id]) * ((node.right - node.left + 1) * 100 - 4)))
# Check that span and multinuc buttons should be used (if the interface is not used for RST, they may be disabled)
if int(get_schema()) > 2:
use_span_buttons = True if get_setting("use_span_buttons") == "True" else False
use_multinuc_buttons = True if get_setting("use_multinuc_buttons") == "True" else False
else:
use_span_buttons = True
use_multinuc_buttons = True
# Check whether secondary edges should be allowed
if int(get_schema()) > 6:
use_secedges = True if get_setting("use_secedges") == "True" else False
else:
use_secedges = False
if sys.version_info[0] == 2:
lambda_button = "Λ".decode("utf-8")
else:
lambda_button = "Λ"
tok_count = 0
for key in sorted(nodes.keys(), key=int):
node = nodes[key]
if node.kind != "edu":
g_wid = str(int((node.right - node.left + 1) * 100 - 4))
cpout += '<div id="lg' + node.id + '" class="group" style="left: ' + str(
int(node.left * 100 - 100)) + '; width: ' + g_wid + '; top:' + str(int(
top_spacing + layer_spacing + node.depth * layer_spacing)) + 'px; z-index:1"><div id="wsk' + node.id + '" class="whisker" style="width:' + g_wid + ';"></div></div>'
cpout += '<div id="g' + node.id + '" class="num_cont" style="position: absolute; left:' + pix_anchors[
node.id] + 'px; top:' + str(
int(4 + top_spacing + layer_spacing + node.depth * layer_spacing)) + 'px; z-index:' + str(int(200 - (
node.right - node.left))) + '"><table class="btn_tb"><tr><td rowspan="2"><button id="unlink_' + node.id + '" title="unlink this node" class="minibtn" onclick="act(' + "'up:" + node.id + ",0'" + ');">X</button></td><td rowspan="2"><span class="num_id">' + str(
int(node.left)) + "-" + str(int(node.right)) + '</span></td>'
if use_span_buttons:
cpout += '<td><button id="aspan_' + node.id + '" title="add span above" class="minibtn" onclick="act(' + "'sp:" + node.id + "'" + ');">T</button></td>'
cpout += '</tr>'
if use_multinuc_buttons:
cpout += '<tr><td><button id="amulti_' + node.id + '" title="add multinuc above" class="minibtn" onclick="act(' + "'mn:" + node.id + "'" + ');">' + lambda_button + '</button></td></tr>'
cpout += '</table></div><br/>'
elif node.kind == "edu":
cpout += '<div id="edu' + str(node.id) + '" class="edu" title="' + str(node.id) + '" style="left:' + str(
int(node.id) * 100 - 100) + '; top:' + str(
int(top_spacing + layer_spacing + node.depth * layer_spacing)) + '; width: 96px">'
cpout += '<div id="wsk' + node.id + '" class="whisker" style="width:96px;"></div><div class="edu_num_cont"><table class="btn_tb"><tr><td rowspan="2"><button id="unlink_' + node.id + '" title="unlink this node" class="minibtn" onclick="act(' + "'up:" + node.id + ",0'" + ');">X</button></td><td rowspan="2"><span class="num_id"> ' + str(
int(node.left)) + ' </span></td>'
if use_span_buttons:
cpout += '<td><button id="aspan_' + node.id + '" title="add span above" class="minibtn" onclick="act(' + "'sp:" + node.id + "'" + ');">T</button></td>'
cpout += '</tr>'
if use_multinuc_buttons:
cpout += '<tr><td><button id="amulti_' + node.id + '" title="add multinuc above" class="minibtn" onclick="act(' + "'mn:" + node.id + "'" + ');">' + lambda_button + '</button></td></tr>'
cpout += '</table></div>'
for tok in node.text.split(" "):
tok_count += 1
cpout += '<span id="tok' + str(tok_count) + '" class="tok">' + tok + '</span> '
cpout += '</div>'
# Serialize data in hidden input for JavaScript
cpout += '<input id="data" name="data" type="hidden" '
hidden_val = ""
#doc_relname_to_reltype = get_doc_relname_to_reltype(cur, current_doc, current_project)
for key in nodes:
node = nodes[key]
reltype = doc_relname_to_reltype.get(node.relname)
if node.relname:
safe_relname = node.relname
else:
safe_relname = "none"
if node.kind == "edu":
hidden_val += "n" + node.id + ",n" + node.parent + ",e," + str(
int(node.left)) + "," + safe_relname + "," + reltype + ";"
elif node.kind == "span":
hidden_val += "n" + node.id + ",n" + node.parent + ",s,0," + safe_relname + "," + reltype + ";"
else:
hidden_val += "n" + node.id + ",n" + node.parent + ",m,0," + safe_relname + "," + reltype + ";"
hidden_val = hidden_val[0:len(hidden_val) - 1]
cpout += 'value="' + hidden_val + '"/>'
# secondary edges, if any
cpout += '<input id="secedges" name="secedges" type="hidden" '
hidden_val = secedge_data
cpout += 'value="' + hidden_val + '"/>'
cpout += '<input id="def_multi_rel" type="hidden" value="' + def_multirel + '"/>\n'
cpout += '<input id="def_rst_rel" type="hidden" value="' + def_rstrel + '"/>\n'
cpout += '<input id="undo_log" type="hidden" value=""/>\n'
cpout += '<input id="redo_log" type="hidden" value=""/>\n'
cpout += '<input id="undo_state" type="hidden" value=""/>\n'
cpout += '<input id="logging" type="hidden" value=""/>\n'
cpout += '<input id="validations" type="hidden" value="' + validations + '"/>\n'
cpout += '<input id="use_span_buttons" type="hidden" value="' + str(use_span_buttons) + '"/>\n'
cpout += '<input id="use_multinuc_buttons" type="hidden" value="' + str(use_multinuc_buttons) + '"/>\n'
cpout += '<input id="use_secedges" type="hidden" value="' + str(use_secedges) + '"/>\n'
cpout += ''' <script src="./script/jquery.jsPlumb-1.7.5-min.js"></script>
<script>
'''
cpout += 'function list_rels(){return "' + ",".join(rel_list) + '";}'
cpout += 'function select_my_rel(options,my_rel){'
cpout += 'var multi_options = `' + multi_options + '`;\n'
cpout += 'var rst_options = `' + rst_options + '`;\n'
cpout += 'var relname_mapping = {"adversative-antithesis":"antithesis","adversative-concession":"concession","adversative-contrast":"contrast","attribution-negative":"attrib.-negative","attribution-positive":"attrib.-positive","causal-cause":"cause","causal-result":"result","context-background":"background","context-circumstance":"circumstance","contingency-condition":"condition","elaboration-additional":"elab.-additional","elaboration-attribute":"elab.-attribute","evaluation-comment":"eval.-comment","explanation-evidence":"evidence","explanation-justify":"justify","explanation-motivation":"motivation","joint-disjunction":"disjunction","joint-list":"list","joint-other":"other","joint-sequence":"sequence","mode-manner":"manner","mode-means":"means","organization-heading":"heading","organization-phatic":"phatic","organization-preparation":"preparation","purpose-attribute":"purp.-attribute","purpose-goal":"purp.-goal","restatement-partial":"restat.-partial","restatement-repetition":"restat.-repetition","same-unit":"same-unit","topic-question":"question","topic-solutionhood":"solutionhood"}\n'
cpout += '''if (options =="both"){options = multi_options.replace(/<option value=[^<>]+?>.?(satellite|same-unit)[^<>]*<.option>/g,"").replace(/\\n+/g,"\\n").replace(/_m'/g,"_r'") + rst_options;}\n'''
cpout += 'else if (options =="multi"){options = multi_options;} else {options=rst_options;}\n'
cpout += ' replaced = options.replace("<option value=' + "'" + '"' + '+my_rel+' + '"' + "'" + '","<option selected=' + "'" + 'selected' + "'" + ' value=' + "'" + '"' + '+my_rel+' + '"' + "'" + '");\n'
cpout += ' const longrel = /([a-z]{4})[a-z]+-([a-z]+<.option)/gi;\n'
cpout += ' for (f in relname_mapping) {replaced = replaced.replace(">" + f + "<",">" + relname_mapping[f] + "<");}\n'
#cpout += ' replaced = replaced.replace(longrel,"$1-$2"); //shorten long names\n'
cpout += ' replaced = replaced.trim().split("\\n").sort( (a,b) => a.match(/>([^<>]+)</)[1] > b.match(/>([^<>]+)</)[1] ).join("\\n"); \n'
cpout += ' return replaced + "\\n";\n'
cpout += ' }\n'
cpout += '''function make_relchooser(id,option_type,rel){
var s = "<div id='seldiv"+id.replace("n","")+"' style='white-space:nowrap;'>";
s += make_signal_button(id);
s += "<select id='sel"+id.replace("n","")+"' class='rst_rel' onchange='crel(" + id.replace("n","") + ",this.options[this.selectedIndex].value);'>" + select_my_rel(option_type,rel) + "</select>";
return $(s);
}'''
# todo: make a flag that controls whether signals are on
cpout += 'var signalsEnabled = ' + ('true;' if get_setting("signals") == "True" else 'false;')
cpout += '''function make_signal_button(id) {
if (signalsEnabled) {
var text = window.rstWebSignals[id]
? window.rstWebSignals[id].length
: "S";
var classes = window.rstWebSignals[id] && window.rstWebSignals[id].length > 0
? "minibtn minibtn--with-signals"
: "minibtn";
return '<button title="add signals" class="' + classes + '" onclick="open_signal_drawer(\\'' + id.replace('n','') + '\\')">' + text + '</button>';
} else {
return '';
}
}'''
cpout += '''
jsPlumb.importDefaults({
PaintStyle : {
lineWidth:2,
strokeStyle: 'rgba(0,0,0,0.5)'
},
Endpoints : [ [ "Dot", { radius:1 } ], [ "Dot", { radius:1 } ] ],
EndpointStyles : [{ fillStyle:"#000000" }, { fillStyle:"#000000" }],
Anchor:"Top",
Connector : [ "Bezier", { curviness:50 } ]
})
var loading_done = false;
jsPlumb.ready(function() {
if (loading_done){return;}
loading_done = true;
jsPlumb.setContainer(document.getElementById("inner_canvas"));
'''
cpout += "jsPlumb.setSuspendDrawing(true);"
for key in nodes:
node = nodes[key]
if node.kind == "edu":
node_id_str = "edu" + node.id
else:
node_id_str = "g" + node.id
cpout += 'jsPlumb.makeSource("' + node_id_str + '", {anchor: "Top", filter: ".num_id", allowLoopback:false});'
cpout += 'jsPlumb.makeTarget("' + node_id_str + '", {anchor: "Top", filter: ".num_id", allowLoopback:false});'
# Connect nodes
for key in nodes:
node = nodes[key]
if node.parent != "0":
parent = nodes[node.parent]
if node.kind == "edu":
node_id_str = "edu" + node.id
else:
node_id_str = "g" + node.id
if parent.kind == "edu":
parent_id_str = "edu" + parent.id
else:
parent_id_str = "g" + parent.id
if node.relname == "span":
cpout += 'jsPlumb.connect({source:"' + node_id_str + '",target:"' + parent_id_str + '", connector:"Straight", anchors: ["Top","Bottom"]});'
elif parent.kind == "multinuc" and node.relkind == "multinuc":
cpout += 'jsPlumb.connect({source:"' + node_id_str + '",target:"' + parent_id_str + '", connector:"Straight", anchors: ["Top","Bottom"], overlays: [ ["Custom", {create:function(component) {return make_relchooser("' + node.id + '","multi","' + node.relname + '");},location:0.2,id:"customOverlay"}]]});'
else:
cpout += 'jsPlumb.connect({source:"' + node_id_str + '",target:"' + parent_id_str + '", overlays: [ ["Arrow" , { width:12, length:12, location:0.95 }],["Custom", {create:function(component) {return make_relchooser("' + node.id + '","rst","' + node.relname + '");},location:0.1,id:"customOverlay"}]]});'
cpout += '''
jsPlumb.setSuspendDrawing(false,true);
jsPlumb.bind("connection", function(info) {
source = info.sourceId.replace(/edu|g/,"")
target = info.targetId.replace(/edu|g/g,"")
});
jsPlumb.bind("beforeDrop", function(info) {
$(".minibtn").prop("disabled",true);
'''
cpout += '''
var node_id = "n"+info.sourceId.replace(/edu|g|lg/,"");
var new_parent_id = "n"+info.targetId.replace(/edu|g|lg/,"");
if (ctrlPressed.value && $('#use_secedges').val().toLowerCase() == "true"){
defrel = get_def_rstrel();
act("sc:"+node_id.replace(/n/,'') + "-"+new_parent_id.replace(/n/,'')+"," + defrel);
return;
}
nodes = parse_data();
new_parent = nodes[new_parent_id];
relname = nodes[node_id].relname;
new_parent_kind = new_parent.kind;
if (nodes[node_id].parent != "n0"){
old_parent_kind = nodes[nodes[node_id].parent].kind;
}
else
{
old_parent_kind ="none";
}
if (info.sourceId != info.targetId){
if (!(is_ancestor(new_parent_id,node_id))){
jsPlumb.select({source:info.sourceId}).detach();
if (new_parent_kind == "multinuc"){
relname = get_multirel(new_parent_id,node_id,nodes);
jsPlumb.connect({source:info.sourceId, target:info.targetId, connector:"Straight", anchors: ["Top","Bottom"], overlays: [ ["Custom", {create:function(component) {return make_relchooser(node_id,"multi",relname);},location:0.2,id:"customOverlay"}]]});
}
else{
jsPlumb.connect({source:info.sourceId, target:info.targetId, overlays: [ ["Arrow" , { width:12, length:12, location:0.95 }],["Custom", {create:function(component) {return make_relchooser(node_id,"rst",relname);},location:0.1,id:"customOverlay"}]]});
}
new_rel = document.getElementById("sel"+ node_id.replace("n","")).value;
act('up:' + node_id.replace("n","") + ',' + new_parent_id.replace("n",""));
update_rel(node_id,new_rel,nodes);
recalculate_depth(parse_data());
}
}
$(".minibtn").prop("disabled",false);
});
loading_done = true;
nodes = parse_data();
render_all_secedges(nodes);
});
nodes = parse_data();
show_warnings(nodes);
</script>
'''
cpout += '''
</div>
</div>
</div>
<div id="anim_catch" class="anim_catch"> </div>
'''
return cpout
def structure_main(user, admin, mode, **kwargs):
scriptpath = os.path.dirname(os.path.realpath(__file__)) + os.sep
userdir = scriptpath + "users" + os.sep
theform = kwargs
cgitb.enable()
config = ConfigObj(userdir + 'config.ini')
templatedir = scriptpath + config['controltemplates'].replace("/",os.sep)
template = "main_header.html"
header = readfile(templatedir+template)
header = header.replace("**page_title**","Structure editor")
header = header.replace("**user**",user)
cpout = ""
if mode == "server":
cpout += "Content-Type: text/html\n\n\n"
header = header.replace("**logout_control**",'(<a href="logout.py">log out</a>)')
else:
header = header.replace("**logout_control**",'')
cpout += header
if "current_doc" in theform:
current_doc = theform["current_doc"]
current_project = theform["current_project"]
current_guidelines = get_guidelines_url(current_project)
else:
current_doc = ""
current_project = ""
current_guidelines = ""
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
edit_bar = "edit_bar.html"
edit_bar = readfile(templatedir+edit_bar)
edit_bar = edit_bar.replace("**doc**",current_doc)
edit_bar = edit_bar.replace("**project**",current_project)
edit_bar = edit_bar.replace("**structure_disabled**",'disabled="disabled"')
edit_bar = edit_bar.replace("**segment_disabled**",'')
edit_bar = edit_bar.replace("**relations_disabled**",'')
edit_bar = edit_bar.replace("**screenshot_disabled**",'')
edit_bar = edit_bar.replace("**quickexp_disabled**",'')
edit_bar = edit_bar.replace("**current_guidelines**",current_guidelines)
if mode == "server":
edit_bar = edit_bar.replace("**submit_target**",'structure.py')
else:
edit_bar = edit_bar.replace("**submit_target**",'structure')
edit_bar = edit_bar.replace("**action_type**",'action')
edit_bar = edit_bar.replace("**serve_mode**",mode)
edit_bar = edit_bar.replace("**open_disabled**",'')
edit_bar = edit_bar.replace('id="nav_edit" class="nav_button"','id="nav_edit" class="nav_button nav_button_inset"')
if admin == "3":
edit_bar = edit_bar.replace("**admin_disabled**",'')
else:
edit_bar = edit_bar.replace("**admin_disabled**",'disabled="disabled"')
cpout += edit_bar
help = "help.html"
help = readfile(templatedir+help)
help_match = re.search(r'(<div id="help_edit".*?</div>)',help,re.MULTILINE|re.DOTALL)
help = help_match.group(1)
if sys.version_info[0] == 2:
cpout += help.decode("utf-8")
else:
cpout += help
about = "about.html"
about = readfile(templatedir+about)
about = about.replace("**version**", _version.__version__)
cpout += about
if current_guidelines != "":
cpout += '<script>enable_guidelines();</script>'
if current_doc =="":
cpout += '<p class="warn">No file found - please select a file to open</p>'
return cpout
# Remove floating non-terminal nodes if found
# (e.g. due to browsing back and re-submitting old actions or other data corruption)
clean_floating_nodes(current_doc, current_project, user)
rels = get_rst_rels(current_doc, current_project)
def_multirel = get_def_rel("multinuc", current_doc, current_project)
def_rstrel = get_def_rel("rst", current_doc, current_project)
timestamp = ""
if "timestamp" in theform:
if len(theform["timestamp"]) > 1:
timestamp = theform["timestamp"]
refresh = check_refresh(user, timestamp)
if "action" in theform and not refresh:
if len(theform["action"]) > 1:
action_log = theform["action"]
if len(action_log) > 0:
actions = action_log.split(";")
set_timestamp(user, timestamp)
for action in actions:
action_type = action.split(":")[0]
action_params = action.split(":")[1] if len(action.split(":")) > 1 else ""
params = action_params.split(",")
if action_type == "up":
update_parent(params[0], params[1], current_doc, current_project, user)
elif action_type == "sp":
insert_parent(params[0], "span", "span", current_doc, current_project, user)
elif action_type == "mn":
insert_parent(params[0], def_multirel, "multinuc", current_doc, current_project, user)
elif action_type == "rl":
update_rel(params[0], params[1], current_doc, current_project, user)
elif action_type == "sg":
update_signals(action.split(":")[1:], current_doc, current_project, user)
elif action_type == "sc": # Add secedge
update_secedge(params[0].split("-")[0], params[0].split("-")[1], params[1], current_doc, current_project, user)
elif action_type == "xs": # Delete secedge
update_secedge(params[0].split("-")[0], params[0].split("-")[1], "-ERASE-", current_doc, current_project, user)
else:
cpout += '<script>alert("the action was: " + theform["action"]);</script>\n'
if "logging" in theform and not refresh:
if len(theform["logging"]) > 1:
if get_setting("logging") == "on":
logging = theform["logging"]
if len(logging) > 0:
update_log(current_doc, current_project, user, logging, "structure", str(datetime.datetime.now()))
if "reset" in theform or user == "demo":
if len(theform["reset"]) > 1 or user == "demo":
reset_rst_doc(current_doc, current_project, user)
rows = get_rst_doc(current_doc, current_project, user)
signal_data = get_signals(current_doc, current_project, user)
nodes = {}
secedge_data = []
for row in rows:
relkind = "span"
if row[7].endswith("_m"):
relkind = "multinuc"
elif row[7].endswith("_r"):
relkind = "rst"
if row[5] == "edu":
nodes[row[0]] = NODE(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], relkind, row[8])
else:
nodes[row[0]] = NODE(row[0], 0, 0, row[3], row[4], row[5], row[6], row[7], relkind, row[8])
if row[8] is not None:
sec = row[8]
if sec.startswith(";"):
sec = sec[1:]
if row[8].endswith(";"):
sec = sec[:-1]
if len(sec) > 0:
secedge_data += sec.split(";")
secedge_data = ";".join(sorted(list(set(secedge_data))))
cpout += build_canvas(current_doc, current_project, rels, nodes, secedge_data=secedge_data, user=user, def_rstrel=def_rstrel, def_multirel=def_multirel, signal_data=signal_data)
cpout += ''' </body>
</html>
'''
if mode != "server":
cpout = cpout.replace(".py","")
return cpout
# Main script when running from Apache
def structure_main_server():
thisscript = os.environ.get('SCRIPT_NAME', '')
action = None
theform = cgi.FieldStorage()
scriptpath = os.path.dirname(os.path.realpath(__file__)) + os.sep
userdir = scriptpath + "users" + os.sep
action, userconfig = login(theform, userdir, thisscript, action)
user = userconfig["username"]
admin = userconfig["admin"]
kwargs={}
for key in theform:
kwargs[key] = theform[key].value
output = structure_main(user, admin, 'server', **kwargs)
if sys.version_info[0] < 3:
print(output)
else:
sys.stdout.buffer.write(output.encode("utf8"))
#ka = {'current_doc': 'GUM_academic_librarians.rs3', 'current_project': 'asd', 'serve_mode': 'local', 'current_guidelines': '**current_guidelines**', 'logging': '', 'reset': '', 'dirty': '', 'timestamp': ''}
#structure_main("local",1,'server',**ka)
if "/" in os.environ.get('SCRIPT_NAME', ''):
mode = "server"
else:
mode = "local"
if mode == "server" and __name__ == "__main__":
structure_main_server()