forked from mideind/GreynirServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcorrect.html
660 lines (588 loc) · 23 KB
/
correct.html
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
{% extends "container-normal.html" %}
{% block styles %}
<link href="{{ url_for('static', filename='css/main-bootstrap.css') }}" rel='stylesheet' type='text/css'>
{% endblock %}
{% block content %}
<div class="input-correct">
<div class="row">
<div class="col-xs-12" id="txt-div">
<textarea rows="12" class="form-control input-lg"
id="txt" tabindex="1" maxlength="16384" autofocus required
placeholder="Sláðu inn texta eða veldu skjal til að lesa yfir...">
{{- default_text -}}
</textarea>
</div>
</div>
<div id="correct-buttons" class="row buttons">
<div class="col-xs-4 col-sm-3 col-md-2 pull-right">
<button class="btn btn-info btn-lg btn-block"
id="txt-ok" title="Lesa yfir texta" tabindex="3"
onclick="correct()">
<span class='glyphicon glyphicon-restart glyphicon-spin-white' style="display:none;"></span>
<span class="glyphicon glyphicon-eye-open normal"></span> Lesa yfir
</button>
</div>
<form class="hidden" enctype="multipart/form-data" method="post" action="#">
<input id="file-input" type="file" name="filename" onChange="uploadFile()" accept="">
</form>
<div class="col-xs-4 col-sm-3 col-md-2 pull-right">
<button class="btn btn-success btn-lg btn-block" id="file-ok"
title="Smelltu hér til þess að hlaða upp skjali til yfirlestrar (styður TXT, RTF, HTML og DOCX snið)"
tabindex="3" onclick="selectFile()">
<span class='glyphicon glyphicon-restart glyphicon-spin-white' style="display:none;"></span>
<span class="glyphicon glyphicon-upload normal"></span> Skjal
</button>
</div>
</div>
<div id="correct-progress" class="row">
<div class="col-xs-12">
<h4>Lestur texta stendur yfir...</h4>
</div>
<div class="col-xs-12">
<div class="progress">
<div id="correct-progress-value"
class="progress-bar progress-bar-warning progress-bar-striped active"
role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"
style="min-width: 2em; width: 0%">
0%
</div>
</div>
</div>
</div>
</div>
<div id="output" style="display: none;">
<div class="row">
<div class="col-xs-12">
<h3 class="help">Yfirlesinn texti</h3>
<!--
The result div contains a list of paragraph divs, each
consisting of two side-by-side divs for the text
and its annotations
-->
<div id="result">
<div class="background">
<span id="no-annotations">
Engar athugasemdir <span class="glyphicon glyphicon-circle-ok"></span>
</span>
</div>
<div id="pgs"></div>
<!-- Annotation detail hover box -->
<div id="detail"></div>
</div>
<div id="statistics">
<!-- Statistics go here -->
<h3>Tölfræði</h3>
<ul id="statistics-summary">
<!-- Statistics get populated in page.js -->
</ul>
</div>
</div>
</div>
</div>
{% endblock %}
{% block endscripts %}
<script src="{{ url_for('static', filename='js/common.js') }}"></script>
<script src="{{ url_for('static', filename='js/page.js') }}"></script>
<script>
var supported_mime_types = {{ supported_mime_types | tojson }};
// Global array linking annotations to token span indices
var annSpan = [];
var CorrectionTask = (function() {
"use strict";
/* Class to wrap the status and progress of a correction task
that is being run asynchronously on the server */
function CorrectionTask() {
this.url = null;
this.progress = 0.0;
this.ival = null;
}
CorrectionTask.prototype.submitText = function(txt) {
this.clearResult();
this.updateProgress();
// Note: the following should not be a serverJsonQuery call,
// this is done via a HTTP form post
// Endpoints with .task suffix are not cached
serverQuery('/correct.task',
{
text : txt
},
this.start.bind(this),
null,
this.handleError.bind(this)
);
};
CorrectionTask.prototype.submitFile = function(fd) {
this.clearResult();
this.updateProgress();
// Send off ajax request
$.ajax({
url: '/correct.task',
type: 'POST',
data: fd,
success: this.start.bind(this),
error: this.handleError.bind(this),
cache: false,
contentType: false,
processData: false
});
/*
serverQuery('/correct.task',
fd,
this.start.bind(this),
null,
this.handleError.bind(this)
);
*/
};
CorrectionTask.prototype.clearResult = function() {
// Clear previous result
$("div#pgs").html("");
$("#no-annotations").hide();
$(window).off("resize");
annSpan = [];
$("div#statistics").hide();
this.wait(true);
};
CorrectionTask.prototype.start = function(json, status, resp) {
// Called when the task has been started and we're being informed
// of the status (polling) URL to use
if (resp.status == 202) {
// This is the expected status: obtain the status URL
// from the Location header
this.url = resp.getResponseHeader("Location");
this.updateProgress();
// Initiate a progress check every 1.5 seconds
this.ival = setInterval(this.poll.bind(this), 1500);
}
else {
// Something is wrong here
this.wait(false);
showError("<b>Samband næst ekki</b> við netþjón Greynis");
}
};
CorrectionTask.prototype.handleError = function(resp) {
// An error occurred: stop polling and update the UI
this.stop();
// Progress complete
this.progress = 1.0;
this.updateProgress();
// An error occurred on the server or in the communications
var msg;
// http status code 413: Payload too large
if (resp.status == 413)
msg = "<b>Skjalið er of stórt</b> (>1.0 megabæti)";
else
msg = "<b>Villa kom upp</b> í samskiptum við netþjón Greynis";
this.wait(false);
showError(msg);
};
CorrectionTask.prototype.poll = function() {
// Called every few seconds to query the server about its progress
serverGet(this.url,
this.checkProgress.bind(this),
this.handleError.bind(this)
);
};
CorrectionTask.prototype.checkProgress = function(json, status, resp) {
// Response from the server to a progress check
if (resp.status == 202) {
// Still in progress
this.progress = json.progress;
this.updateProgress();
return;
}
// Either we're done, or an error has occurred
this.stop();
// Progress complete
this.progress = 1.0;
this.updateProgress();
if (resp.status == 200) {
// This is the final and complete response
// Show the results after a 0.5-second wait
setTimeout(this.populateResult.bind(this), 500, json)
}
else {
// Something is wrong
this.wait(false);
showError("<b>Villa kom upp</b> í samskiptum við netþjón Greynis");
}
};
CorrectionTask.prototype.updateProgress = function() {
// Update the UI with the current progress
var percent = "" + Math.round(this.progress * 100.0);
$("#correct-progress-value")
.css("width", percent + "%")
.attr("aria-valuenow", percent)
.html(percent + "%");
};
CorrectionTask.prototype.stop = function () {
// Stop the progress polling and quiet down
if (this.ival !== null) {
clearInterval(this.ival);
this.ival = null;
}
};
CorrectionTask.prototype.wait = function(state) {
// Update UI when waiting for result vs. showing it
if (state) {
// Waiting for result: disable textarea and buttons
$("#txt-ok, #file-ok, #txt").attr("disabled", "disabled");
$("div#output").hide();
// Hide buttons
$("div#correct-buttons").css("display", "none");
// Show progress bar
$("div#correct-progress").css("display", "block");
}
else {
// Re-enable textarea and buttons
$("#txt-ok, #file-ok, #txt").removeAttr("disabled");
$("div#output").show();
// Show buttons
$("div#correct-buttons").css("display", "block");
// Show progress bar
$("div#correct-progress").css("display", "none");
}
};
CorrectionTask.prototype.populateResult = function(json) {
// Processing completed: display the result
this.wait(false);
if (!json.valid || json.result === undefined || json.result === null) {
showError("<b>Villa kom upp</b> í samskiptum við netþjón Greynis");
}
else {
// Display the paragraphs, sentences and tokens
// along with the sentence-level annotations
displayAnnotations(json.result);
populateStats(json.stats);
// Replace text in text field
if (json.text) {
$("#txt").val(json.text);
}
}
};
return CorrectionTask;
} ());
function showError(errStr) {
// Hide any current results and show error message
$("div#output").show();
$("#no-annotations").hide();
$("div#statistics").hide();
$("div#pgs").html("<p style='color:#cc0000'>" + errStr + "</p>");
}
function formatAnnotation(txt) {
// Hack to convert all text within single quotation marks in
// an annotation to bold, while also escaping the annotation
// text to valid HTML
var fmt = txt.replace(/'[^']*'/g, function (s) {
// Be careful to not use characters that will be HTML-escaped
// in the dummy markers
return "[bold]" + s.slice(1, -1) + "[~bold]";
});
fmt = escapeHtml(fmt);
// Replace the dummy markers with HTML tags
return fmt.replace(/\[bold\]/g, "<b>").replace(/\[~bold\]/g, "</b>");
}
function annHoverIn(ev) {
// Hovering over an annotation
var wId = $(this).attr("id");
if (wId === null || wId === undefined) {
// No id: nothing to do
return;
}
var ix = parseInt(wId.slice(1));
var span = annSpan[ix];
if (!span) {
// No annotation: nothing to do
return;
}
// Add a highlight to all tokens spanned by this annotation
for (var i = span.start; i <= span.end; i++)
$("#w" + i).addClass("highlight");
// Emphasize the path associated with this annotation
// Note: addClass() doesn't work on SVG elements until jQuery 3.0.
$("#p" + ix)[0].classList.add("highlight");
}
function annHoverOut(ev) {
// No longer hovering over an annotation
var wId = $(this).attr("id");
if (wId === null || wId === undefined) {
// No id: nothing to do
return;
}
var ix = parseInt(wId.slice(1));
var span = annSpan[ix];
if (!span) {
// No annotation: nothing to do
return;
}
// Remove highlight from all tokens spanned by this annotation
for (var i = span.start; i <= span.end; i++)
$("#w" + i).removeClass("highlight");
// De-emphasize the path associated with this annotation
$("#p" + ix)[0].classList.remove("highlight");
}
function isWarning(code) {
// Return true if the annotation code should be displayed as a warning,
// not as an error
return code.endsWith("/w");
}
function detailHoverIn() {
// Hovering over an annotation text div that has a detail (info) icon
// Obtain html to display from the ann-detail div
var html = $(this).parent().find("div.ann-detail").html();
var frame = $(this).parent().parent().parent();
$("#detail").html(html);
var top = frame.position().top
- ($("#detail").height() + 30)
+ $(this).position().top;
var left = $(this).offset().left - frame.offset().left;
// Position the detail popup
$("#detail")
.css("top", "" + top + "px")
.css("left", "" + left + "px")
.css("visibility", "visible");
}
function detailHoverOut() {
// Stop hovering over an annotation text div
$("#detail").css("visibility", "hidden");
}
function displayAnnotations(j) {
// Generate HTML for the token list given in j,
// and insert it into the <div> with id 'pgs'.
// Also, populate the global w array with the
// token list.
// Also, display annotations alongside the original text.
// The variable x accumulates the content of the #pgs div
var x = "";
var lastSp;
w = []; // Token array (declared as a global in page.js)
annSpan = []; // Array of annotation token spans
var unknownWords = {}; // Dict of already seen unknown words
$.each(j, function(pix, p) {
// We create a div for each paragraph
x += "<div class='correct'>\n";
// Left column: paragraph text
var left = "";
// Right column: paragraph annotations
var right = "";
// Third child: SVG drawing stuff
var canvas = "";
$.each(p, function(sentence_index, s) {
// Sentence s
lastSp = TP_NONE;
left += "<span class='sent'>";
// Note where the sentence starts in the token array
var six = w.length;
$.each(s.tokens, function(tix, t) {
// Token t
var thisSp = spacing(t);
// Insert a space in front of this word if required
// (but never at the start of a sentence)
if (TP_SPACE[lastSp - 1][thisSp - 1] && tix)
left += " ";
lastSp = thisSp;
var tx = t.x;
var cls = [];
if (t.k === TOK_PUNCTUATION) {
// Add space around em-dash
if (tx === "—")
tx = " — ";
cls.push("p");
}
else {
cls.push("c");
tx = tx.replace(" - ", "-"); // Tight hyphen, no whitespace
}
// Check whether the token occurs inside an annotation
// This is fairly inefficient but that is not a problem in practice
$.each(s.annotations, function(aix, a) {
// Annotation a
if (tix >= a.start && tix <= a.end) {
// The annotation applies to this token:
// mark the token
if (isWarning(a.code))
// Suggestion or taboo word warning
cls.push("warntok");
else
// Other error
cls.push("errtok");
return false; // break from $each loop
}
});
left += "<i id='w" + w.length +
"' class='" + cls.join(" ") + "'>" + tx + "</i>";
// Append to word/token list
w.push(t);
});
// Accumulate annotations into the right column
$.each(s.annotations, function(aix, a) {
// Annotation a
// We do not show repeated annotations for unknown words
if (a.code !== "U001" || unknownWords[a.text] === undefined) {
var cls = isWarning(a.code) ? " warning" : "";
var detail = "";
var info = "";
if (a.detail) {
// Add detailed text to the annotation, if available,
// along with an info icon
detail = "<div class='ann-detail'>" +
formatAnnotation(a.detail) +
"</div>";
info = "<span class='ann-info glyphicon glyphicon-info'></span>";
}
right += "<div id='a" + annSpan.length + "'>" +
"<div class='ann-text" + cls + "'>" + info + formatAnnotation(a.text) + "</div>" +
detail +
"</div>\n";
// Add a path to the canvas (empty at this point
// but will be defined in repositionAnnotations())
canvas += "<path id='p" + annSpan.length + "'" + cls + "></path>\n";
// Note the token span to which the annotation applies,
// within the global token list
annSpan.push({start: six + a.start, end: six + a.end});
if (a.code === "U001")
// Note that we have have now annotated this unknown word
unknownWords[a.text] = true;
}
});
// Finish sentence
left += "</span>\n";
});
x += "<div class='result'>" + left + "</div>\n";
x += "<div class='annotation'>" + right + "</div>\n";
if (canvas) {
// Encapsulate the paths in svg/g elements...
canvas = "\n<svg width='100%' height='100%'><g>\n" + canvas + "</g></svg>\n";
// and then within a canvas div
x += "<div class='canvas'>" + canvas + "</div>\n";
}
// Finish paragraph
x += "</div>\n"; // div class='correct'
});
// Show the text and annotation columns
$("div#pgs").html(x);
if (!annSpan.length) {
// No annotations: show that fact
$("#no-annotations").css("display", "inline-block");
}
// Fix the annotations so that they are never
// above their respective start token
repositionAnnotations();
$(window).resize(repositionAnnotations);
// Put a hover handler on each annotation
$("div.annotation div").hover(annHoverIn, annHoverOut);
// Put a hover handler on each annotation text that has an info button
$("span.ann-info").closest("div.ann-text").hover(detailHoverIn, detailHoverOut);
// Put a click handler on each sentence
$("span.sent").click(showParse);
}
function repositionAnnotations() {
// Reposition the annotations to align
// with their respective tokens. This function
// is called both when the annotations are originally
// positioned, and when the browser window is resized.
// Begin by clearing any previous top margins
$.each(annSpan, function(six) {
var ann = $("#a" + six);
ann.css("margin-top", "0");
});
// Then, align with tokens as necessary
$.each(annSpan, function(six, span) {
var tokenTop = $("#w" + span.start).offset().top;
var spanEnd = span.end;
// If the last token is a punctuation token,
// try to go back to the previous word token
// (it looks nicer and more consistent)
while (spanEnd > span.start && w[spanEnd].k == TOK_PUNCTUATION)
spanEnd--;
var endToken = $("#w" + spanEnd);
var tokenOffset = endToken.offset();
var tokenY = tokenOffset.top + endToken.outerHeight();
var tokenX = tokenOffset.left + endToken.outerWidth() / 2;
var ann = $("#a" + six);
var annOffset = ann.offset();
var annTop = annOffset.top;
var annX = annOffset.left;
if (annTop < tokenTop) {
// Put a top margin on the annotation to make its
// top align with the token's top
ann.css("margin-top", "" + (tokenTop - annTop) + "px");
annTop = tokenTop;
}
// Work out the coordinates of a path from the span's
// end token to the corresponding annotation
var annY = annTop + ann.outerHeight() / 2;
// Make the coordinates relative to the parent div.correct
var parentOffset = ann.parents("div.correct").offset();
tokenX -= parentOffset.left;
tokenY -= parentOffset.top + 2; // Small upwards nudge for the start point
annX -= parentOffset.left;
annY -= parentOffset.top;
// Make the path point from the end token to the
// associated annotation. We position the Bezier curve
// handles 40 pixels from the end points, below the end
// token and to the left of the annotation.
var path = $("#p" + six);
path.attr("d",
"M " + tokenX + " " + tokenY +
" C " + tokenX + " " + (tokenY + 40) +
" " + (annX - 40) + " " + annY +
" " + annX + " " + annY
);
});
}
function correct() {
// Submit the contents of the textarea to the server
// for tokenization and parsing
var s = $("#txt").val().trim();
if (s && s.length) {
// Ask the server to tokenize and parse the given text, asynchronously
new CorrectionTask().submitText(s);
} else {
$("#txt").focus();
}
}
function selectFile() {
$('#file-input').trigger('click');
}
function isSupportedFileType(file) {
// Document types supported for uploading
return supported_mime_types.indexOf(file.type) > -1;
}
function uploadFile(file) {
var fd = new FormData();
var f = (file === undefined) ? $('#file-input')[0].files[0] : file;
if (f === undefined) {
return;
}
// Make sure file type is supported
if (!isSupportedFileType(f)) {
showError("Greynir styður ekki yfirlestur á skjölum á þessu sniði.");
return;
}
fd.set('file', f);
$("#txt").val("");
new CorrectionTask().submitFile(fd);
}
function init() {
// Activate the top navbar
$("#navid-correct").addClass("active");
// Drag and drop handling for textarea
$("#file-input").attr("accept", supported_mime_types.join(","));
$("#txt").on("drop", function(event) {
event.preventDefault();
event.stopPropagation();
var file = event.originalEvent.dataTransfer.files[0];
uploadFile(file);
});
// Clicking on the annotation detail popup should make it disappear
$("#detail").on("click touchend", function(ev) {
$(this).css("visibility", "hidden");
ev.stopPropagation();
ev.preventDefault();
return false;
});
}
$(document).ready(init);
</script>
{% endblock %}