nlphub/src/main/webapp/index.jsp

775 lines
24 KiB
Plaintext

<!DOCTYPE html>
<html>
<head>
<!-- input=http%3A%2F%2Fws1-clarind.esc.rzg.mpg.de%2Fdrop-off%2Fstorage%2F1513257926038.txt&lang=en&analysis=const-parsing -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>NLPHub v1.2</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet" />
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css"
media="screen,projection" />
<link type="text/css" rel="stylesheet" href="css/custom.css" />
<!-- jQuery library -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
<script type="text/javascript" src="js/jquery.simple.websocket.min.js"></script>
<script type="text/javascript" src="js/jquery.uploadfile.min.js"></script>
<script type="text/javascript" src="js/merge.js"></script>
<!-- <script type="text/javascript" src="js/main.js"></script> -->
<!-- scripting code -->
<script type="text/javascript">
var tableRawSize = 5;
var annotations = [];
var algorithms = [];
var languages = [];
var publicLink = null;
var pageGreen = "#4CAF50";
var pageGray = "#A0A0A0";
var savedAnnotations = "";
var jsonContent = null;
var named = null;
var resultText = "";
// ------------------------------------------------------------------------------------------------------
// Starting point: get the csv file with algorithm parameters and set the page with valid algs info.
// ------------------------------------------------------------------------------------------------------
$
.ajax({
url : "http://data.d4science.org/bnp4UDNyb21lSURkQXdDUnlSS0JkVWgzWk1KMUxWVGZHbWJQNStIS0N6Yz0",
type : "GET",
async : true,
contentType : "text/plain; charset=utf-8",
success : function(data, stato) {
$("#ner-result-container").hide();
var lineTokens = manageCsvData(data);
getAlgorithms(lineTokens);
buildAnnotationsAndLanguages();
resizeTable();
resizeLogo();
buildLanguageList();
$("#back-ner-ui-button").click(function() {
$("#ner-result-container").hide();
$("#ner-ui").show();
$("#input-textarea").val("");
publicLink = null;
jsonContent = null;
});
// the following line is only for develop
/*
var devData = "{\"link\":\"http://data.d4science.org/Wm5XY1p0TlFIM3NXZnZ1SkhLRlRMK3l6N05jVFhiSXFHbWJQNStIS0N6Yz0\",\"output\":"
+ "{\"text\":\"yes, we can do it tomorrow in the evening.\",\"annotations\":\"Date,Sentence\",\"language\":\"English\",\"result\":"
+ "[{\"algorithm\":\"ENGLISH_NAMED_ENTITY_RECOGNIZER\",\"entities\":[{\"Date\":[{\"indices\":[18,26],\"ruleFinal\":\"DateOnlyFinal\",\"kind\":\"date\",\"rule\":\"GazDateWords\"}]},{\"Sentence\":[{\"indices\":[0,42]}]}]}]}}";
devData = "{\"link\":\"http://data.d4science.org/dXZ5L3RrRjYyTWNXZnZ1SkhLRlRMeXZzd1prOVFqWDFHbWJQNStIS0N6Yz0\",\"output\":"
+ "{\"text\":\"In the 1970s, Iraq under Baath Party dictator Brigadier General Ahmad Hassan al-Bakr had grown close to the Soviet Union, "
+ "with which it signed a treaty of friendship in 1972 and from which it began importing arms. In 1973, al-Bakr supported the Syrians in their war with Israel.\","
+ "\"annotations\":\"Date,Person\",\"language\":\"English\",\"result\": [{\"algorithm\":\"ENGLISH_NAMED_ENTITY_RECOGNIZER\",\"entities\":[{\"Date\":[{\"indices\":[3,12],"
+ "\"ruleFinal\":\"DateOnlyFinal\",\"kind\":\"date\",\"rule\":\"YearSpan1\"},{\"indices\":[169,173],\"ruleFinal\":\"DateOnlyFinal\",\"kind\":\"date\",\"rule\":\"YearContext1\"},"
+ "{\"indices\":[217,221],\"ruleFinal\":\"YearOnlyFinal\",\"kind\":\"date\",\"rule\":\"TempYear2\"}]},{\"Person\":[{\"indices\":[46,76],\"firstName\":\"Ahmad\",\"ruleFinal\":\""
+ "PersonFinal\",\"gender\":\"unknown\",\"surname\":\"Hassan\",\"kind\":\"personName\",\"rule\":\"PersonTitleGenderUnknown\",\"title\":\"Brigadier\"},{\"indices\":[77,84],\"firstName\":"
+ "\"al\",\"ruleFinal\":\"PersonFinal\",\"gender\":\"male\",\"surname\":\"Bakr\",\"kind\":\"fullName\",\"rule\":\"PersonFull\"},{\"indices\":[223,230],\"firstName\":\"al\",\"ruleFinal\":\"PersonFinal\",\"gender\":\"male\",\"surname\":\"Bakr\",\"kind\":\"fullName\",\"rule\":\"PersonFull\"}]}]}]}}";
showResult(devData);
*/
// --------------------------------------
$("#execute-button").css("background-color", pageGray);
$("#upload-button")
.uploadFile(
{
url : "/nlphub/nlphub-uploader-servlet",
fileName : "mytxtfile",
maxFileCount : 100,
multiple : false,
maxFileSize : 1024 * 1000 * 6.14,
showFileCounter : false,
showCancel : true,
dragDropStr : "<img class='img-prompt' src='img/upload.png' width='60px' height='60px' style='display:block; margin:auto; padding: 10px'>",
extErrorStr : "Error. Text file only",
sizeErrorStr : "Error. Max size: 6 Mb",
onLoad : function(obj) {
$("#file-info").remove();
$("#reset-upload").remove();
$("#fu-container")
.append(
"<div id=\"right-child\" class=\"float-right-div\"></div>");
$("#right-child")
.append(
"<div id=\"file-info\" class=\"centered\"></div>");
$("#right-child")
.append(
"<div id=\"reset-upload\" class=\"centered\">Cancel</div>");
$("#reset-upload").hide();
$("#reset-upload")
.click(
function() {
resetExecuteButton();
$("#file-info")
.empty();
$(
"#reset-upload")
.css(
"display",
"none");
textAreaEnable(true);
});
savedAnnotations = "";
setEventListeners();
},
onSelect : function(files) {
showProgress();
textAreaEnable(false);
$("#input-textarea").val("");
},
onSuccess : function(files, data, xhr) {
hideProgress();
$("#reset-upload").css("display",
"inline");
console.log("files: " + files);
$("#file-info").empty();
$("#file-info")
.append(
"Uploaded: <span style=\"color:#4CAF50; letter-spacing: 1px; font-weight: bold;\">"
+ files
+ "</span>");
publicLink = data.message;
$("#execute-button").css(
"background-color",
pageGreen);
if (publicLink == null) {
alert("Error uploading file.");
}
},
onError : function(files, status,
errMsg, pd) {
hideProgress();
textAreaEnable(true);
alert(errMsg);
}
});
},
error : function(richiesta, stato, errori) {
alert("Unexpected Error. Status: " + richiesta.status);
}
});
manageCsvData = function(data) {
// first of all: split on the "newline" character in order to
// get all lines.
var lines = data.split("\n");
var tokens = [], lineTokens = [];
// second: parse each line
for (i in lines) {
var line = ',' + lines[i];
var tokenStart = -1;
for (var j = 0; j < line.length; j++) {
if (line.charAt(j) == '\"') {
j = line.indexOf('\"', j + 1);
if (j < 0)
return;
continue;
}
if (line.charAt(j) == ',') {
if (tokenStart == -1) {
tokenStart = j;
} else {
tokens[tokens.length] = line.substring(tokenStart + 1,
j);
tokenStart = j;
}
}
}
// get the new token and push it in the array
tokens[tokens.length] = line.substring(tokenStart + 1);
lineTokens[lineTokens.length] = tokens;
tokens = [];
}
return lineTokens;
}
getAlgorithms = function(lineTokens) {
// build the list of supported algorithms
for (i = 0; i < lineTokens.length; i++) {
if ((i == 0) || (lineTokens[i].length != 8))
continue; // skip the header
if (lineTokens[i][7].trim().toUpperCase() == "OK") {
var algName = lineTokens[i][0].trim();
var algDescription = lineTokens[i][1].trim();
var algId = lineTokens[i][2].trim();
var annotationList = lineTokens[i][3].replace(/"/g, " ").trim();
var language = lineTokens[i][4].replace(/"/g, " ").trim();
algorithms[algorithms.length] = {
"name" : algName,
"description" : algDescription,
"id" : algId,
"lang" : language,
"annotations" : annotationList
};
}
}
}
buildAnnotationsAndLanguages = function() {
// extract data about languages and annotations in order to populate the proper
// controls in the page
for (i in algorithms) {
var annotationList = algorithms[i].annotations;
var a = annotationList.split(/\s|,/);
for (j in a) {
a[j] = a[j].trim();
if (a[j].length > 0) {
var thereIs = false;
for (k in annotations) {
if (annotations[k].toUpperCase() == a[j].toUpperCase()) {
thereIs = true;
break;
}
}
if (!thereIs)
annotations[annotations.length] = a[j];
}
}
var languageList = algorithms[i].lang;
var langs = languageList.split(/\s|,/);
for (j in langs) {
langs[j] = langs[j].trim();
if (langs[j].length > 0) {
var thereIs = false;
for (k in languages) {
if (languages[k].toUpperCase() == langs[j].toUpperCase()) {
thereIs = true;
break;
}
}
if (!thereIs)
languages[languages.length] = langs[j];
}
}
}
}
setEventListeners = function() {
$("#input-textarea").on("keyup", function() {
if ($("#input-textarea").val() == "")
$("#execute-button").css("background-color", pageGray);
else
$("#execute-button").css("background-color", pageGreen);
});
$("#execute-button")
.click(
function() {
if ((publicLink == null)
&& ($("#input-textarea").val() == "")) {
alert("You must upload a file or write some text in the text area before submit a request.");
return;
}
showProgress();
// if some text has been written in the text area, then a corresponding text file
// must be written in the workspace and the public link is set.
if ($("#input-textarea").val().length > 0) {
freeText = $("#input-textarea").val();
$
.ajax({
url : "/nlphub/nlphub-uploader-servlet?freetext="
+ encodeURI(freeText),
type : "POST",
async : true,
contentType : "text/plain; charset=utf-8",
success : function(data, stato) {
publicLink = data.message;
if (publicLink == null) {
alert("Error uploading file.");
}
launchAlgorithm();
},
error : function(richiesta, stato,
errori) {
alert("Unexpected Error. Status: "
+ richiesta.status);
hideProgress();
textAreaEnable(true);
$("#file-info").empty();
}
});
}
else {
launchAlgorithm();
}
});
}
showProgress = function() {
var width = $(".progress-circular-div").width();
var height = $(".progress-circular-div").height();
var left = parseInt((window.innerWidth - width) / 2);
var top = parseInt((window.innerHeight - height) / 2);
$(".progress-circular-div").css("left", left);
$(".progress-circular-div").css("top", top);
$(".hidden-div").css("display", "block");
}
hideProgress = function() {
$(".hidden-div").css("display", "none");
}
launchAlgorithm = function() {
if (publicLink == null) {
alert("No input text available for the service.");
return;
}
var list = buildInputAnnotationList();
var annList = "";
for (i in list) {
annList += list[i] + ",";
}
annList = annList.substring(0, annList.length - 1);
savedAnnotations = annList;
var algList = "";
for (j in algorithms) {
algList += encodeURI(algorithms[j].id) + ",";
}
algList = algList.substring(0, algList.length - 1);
var parameters = "annotations=" + annList;
parameters += "&lang=" + $("#language-select").val();
parameters += "&plink=" + encodeURI(publicLink);
parameters += "&algs=" + algList;
$.ajax({
url : "/nlphub/nlphub-servlet?" + parameters,
type : "POST",
async : true,
success : function(data, stato) {
hideProgress();
textAreaEnable(true);
$("#file-info").empty();
if (typeof (data.response) != 'undefined') {
var jsonOut = getOutputJson(data.message);
} else if (typeof (data.error) != 'undefined') {
alert(data.message);
} else {
alert("Unexpected response");
}
resetExecuteButton();
},
error : function(richiesta, stato, errori) {
hideProgress();
textAreaEnable(true);
alert("Unexpected Error. Status: " + richiesta.status);
resetExecuteButton();
}
});
}
getOutputJson = function(message) {
var tobemap = "";
for (var i = 0; i < message.length; i++) {
tobemap += message[i] + "|";
}
tobemap = tobemap.substring(0, tobemap.length - 1);
var parameters = "annotations=" + savedAnnotations;
parameters += "&plink=" + encodeURI(publicLink);
parameters += "&lang=" + $("#language-select").val();
parameters += "&tobemap=" + encodeURI(tobemap);
console.log(parameters);
$.ajax({
url : "/nlphub/nlphub-mapper-servlet?" + parameters,
type : "POST",
async : true,
success : function(data, stato) {
console.log(data);
if((typeof (data.response) != "undefined") && (data.response.trim().toUpperCase() == "ERROR")) {
alert ("ERROR\n" + data.message);
}
else {
$("#reset-upload").hide();
savedAnnotations = "";
publicLink = null;
showResult(data);
}
},
error : function(richiesta, stato, errori) {
$("#reset-upload").hide();
savedAnnotations = "";
publicLink = null;
alert("Unexpected Error. Status: " + richiesta.status);
}
});
}
showResult = function(data) {
$("#ner-ui").hide();
$("#ner-result-container").show();
jsonContent = data;
//jsonContent = JSON.parse(purgeJson(data));
//resultText = jsonToText(jsonContent.output.text);
resultText = jsonContent.output.text;
$("#result-header").empty();
$("#result-params-div").empty();
$("#result-text-div").empty();
$("#result-header")
.append(
"<p>You can download the result file from <a href='" + jsonContent.link +"'>here</a></p>");
var localText = resultText;
localText = resultText.replace(/\n/g, "<br>");
$("#result-text-div").empty();
$("#result-text-div").append("<p>" + localText + "</p>");
showAnnotationList(jsonContent.output.annotations);
}
showAnnotationList = function(list) {
var colors = [];
var annotations = list.split(",");
for (var i = 0; i < annotations.length; i++) {
colors[colors.length] = randomRGB();
}
$("#result-params-div")
.append("<form id='colored-annotations'></form>");
for (var i = 0; i < annotations.length; i++) {
var cb = "<input type='radio' name='foo' named='" + annotations[i] + "' value='" + colors[i] + "' id='color-" + i + "' class='filled-in'>";
cb += "<label for='color-" + i + "'><span style='font-weight:bold; color:#" + colors[i] + "'>"
+ annotations[i] + "</span></label><br>";
$("#colored-annotations").append(cb);
}
$("#colored-annotations :radio").change(function() {
if (this.checked) {
rewriteText(this.getAttribute("named"), "#" + this.value);
}
});
}
countSubstringOccurrencies = function(string, substring) {
var occurrencies = 0;
var index = 0;
var s = string;
while(index >= 0) {
index = s.indexOf(substring);
if(index >= 0) {
occurrencies++;
s = s.substring(index + 1);
}
}
return occurrencies;
}
rewriteText = function(annotation, color) {
$("#result-text-div").empty();
console.log(annotation + " " + color);
var complement = "#"
+ (0xFFFFFF - eval("0x" + color.substring(1))).toString(16);
complement = "#F0F0F0";
var indices = getIndices(annotation);
var indexedText = "";
if ((typeof (indices) == 'undefined' ) || (indices.length == 0)) {
indexedText = resultText;
indexedText = indexedText.replace(/\n/g, "<br>");
$("#result-text-div").append("<p>" + indexedText + "</p>");
return;
}
var t = 0;
var offset = 0;
for (var i = 0; i < indices.length; i++) {
var index = indices[i];
var start = index[0];
var end = index[1];
indexedText += resultText.substring(t, start);
offset += countSubstringOccurrencies(resultText.substring(t, start), "\n");
offset += countSubstringOccurrencies(resultText.substring(t, start), "\r");
offset += countSubstringOccurrencies(resultText.substring(t, start), "\t");
start += offset;
end += offset;
var colored = "<span style='color:" + color + "; background:" + complement + "; font-weight:bold;'>"
+ resultText.substring(start, end) + "</span>";
indexedText += colored;
t = end;
}
if (t < resultText.length)
indexedText += resultText.substring(t);
indexedText = indexedText.replace(/\n/g, "<br>");
$("#result-text-div").append("<p>" + indexedText + "</p>");
}
getIndices = function(annotation) {
var indices = [];
// get indices
for (var i = 0; i < jsonContent.output.result.length; i++) {
var entities = jsonContent.output.result[i].entities;
for (var j = 0; j < entities.length; j++) {
a = entities[j][annotation];
if (typeof a != 'undefined') {
indices[i] = [];
for (var k = 0; k < a.length; k++) {
var index = a[k].indices;
indices[i][k] = index;
}
}
}
}
return mergeIndices(indices);
}
mergeIndices = function(indices) {
// GESTIONE MULTIDIMENSIONALE DA FARE !!!!
var newIndices = []
if (indices.length <= 1)
newIndices = indices[0];
else
newIndices = mergeAll(indices);
return newIndices;
}
resetExecuteButton = function() {
publicLink = null;
$("#execute-button").css("background-color", pageGray);
}
resizeTable = function() {
// resize the annotation table
$("#annotations-table").empty();
var rowId = "";
var ratio = window.innerWidth / window.innerHeight;
if (ratio <= 0.35) {
tableRawSize = 1;
} else if ((ratio > 0.35) && (ratio <= 0.75)) {
tableRawSize = 2;
} else if ((ratio > 0.75) && (ratio <= 1)) {
tableRawSize = 3;
} else if ((ratio > 1) && (ratio <= 1.5)) {
tableRawSize = 4;
} else {
tableRawSize = 5;
}
for (var i = 0; i < annotations.length; i++) {
if (i % tableRawSize == 0) {
rowId = "row-" + i;
$("#annotations-table").append("<tr id=\"" + rowId +"\"></tr>");
}
var annotationElement = "<input type=\"checkbox\" id=\"check-" + i + "\" value=\"" + annotations[i] + "\" checked=\"checked\"></input> <label for=\"check-" + i + "\">"
+ annotations[i] + "</label>";
$("#" + rowId).append("<td>" + annotationElement + "</td>");
}
}
resizeLogo = function() {
if (window.innerWidth < 200)
$("#logo-image").width(window.innerWidth - 10);
}
buildInputAnnotationList = function() {
var list = [];
for (var i = 0; i < annotations.length; i++) {
if ($("#check-" + i).is(":Checked"))
list[list.length] = $("#check-" + i).val();
}
return list;
}
// event handlers
window.onresize = function(event) {
resizeTable();
resizeLogo();
};
$(".ajax-file-upload-abort").on("DOMAttrModified", function(event) {
$(".ajax-file-upload-abort").css("display", "none");
if (event.attributeName == "display") { // which attribute you want to watch for changes
$(".ajax-file-upload-abort").css("display", "none");
}
});
buildLanguageList = function() {
// build the language selection input control
for (i in languages) {
var opt = "<option value=\"" + languages[i] + "\" selected=\"selected\">"
+ languages[i] + "</option>";
if (i > 1)
opt = "<option value=\"" + languages[i] + "\">" + languages[i]
+ "</option>";
$("#language-select").append(opt);
}
}
textAreaEnable = function(enable) {
if (enable == true)
$("#input-textarea").prop('disabled', false);
else
$("#input-textarea").prop('disabled', true);
}
purgeJson = function(json) {
console.log("purgeJson:before: " + json.length);
var purged = json.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r")
.replace(/\t/g, "\\\\t");
console.log("purgeJson:after : " + purged.length);
return purged;
}
jsonToText = function(json) {
console.log("jsonToText:before: " + json.length);
var purged = json.replace(/\\n/g, "");
console.log("jsonToText:after : " + purged.length);
return purged;
//return json.replace(/\\n/g, "\n");
}
randomRGB = function() {
var letters = '0123456789ABCDEF';
var color = '';
var couple = '';
for(var i=0; i < 3; i++) {
do {
couple = '';
for(j=0; j<2; j++) {
couple += letters[Math.floor(Math.random() * 16)];
}
} while((255 - parseInt("0x" + couple)) < 48)
color += couple;
}
return color;
}
</script>
</head>
<body style="padding: 0 15px;">
<div class="logo">
<img id="logo-image" src="img/nlphub-logo-3.png">
</div>
<!-- the "main-div" contains all tabs and contents -->
<div class="main-div">
<!-- tabs div: each tab must refer a page div -->
<div class="col s12">
<ul class="tabs">
<li class="tab col s3"><a href="#ner">NER</a></li>
<li class="tab col s3"><a href="#other">other</a></li>
</ul>
</div>
<!-- "ner" div: contains the name entity recognizer interface -->
<div id="ner">
<div id="ner-ui">
<p class="flow-text">Name Entity Recognition</p>
<fieldset>
<legend>Language selection</legend>
<div class="row">
<div class="clearfix">
<div class="column half-width">
<p class="margin-3 text-align-right">Select the desired
language:</p>
</div>
<div class="column half-width">
<select id="language-select" class="margin-3 align-left">
</select>
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Input text</legend>
<div class="row">
<div class="clearfix">
<div class="column margin-right-10px">
<p>To upload a text file you can use the button or drag a
file on the "upload arrow". Otherwise, write some text in the
text area.</p>
</div>
<div class="column margin-left-10px">
<div class="centered full-width" id="fu-container">
<!-- <div class="waves-effect waves-light btn green darken-1"
id="upload-button">Upload text file</div>-->
<div class="waves-effect waves-light darken-1"
id="upload-button">Upload text file</div>
</div>
</div>
</div>
<div class="input-field col s12">
<textarea id="input-textarea" class="my-textarea" rows="8"
placeholder="paste your text here"></textarea>
</div>
</div>
</fieldset>
<fieldset>
<legend>Annotations (mark annotation you want to use)</legend>
<div class="vscrollable">
<table id="annotations-table">
</table>
</div>
</fieldset>
<!-- this is the "execute button" -->
<div style="text-align: center; padding: 5px;">
<a id="execute-button">Execute</a>
</div>
</div>
<!-- this is the main result container -->
<div id="ner-result-container">
<div id="result-header" class="header-side"></div>
<div class="left-side" id="result-text-div"></div>
<div class="right-side" id="result-params-div"></div>
<div style="text-align: left;">
<div class="green-button float-right-div" id="back-ner-ui-button">back</div>
</div>
</div>
</div>
<!-- end "#ner" -->
<div id="#other"></div>
<!-- this section is used only for the operation progress indicator -->
<div class="hidden-div progress-circular-div">
<div class="preloader-wrapper big active">
<div class="spinner-layer spinner-blue-only">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="gap-patch">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
</div>
<div id="progress-caption">In progress</div>
</div>
</div>
<!-- end "#main-div" -->
</body>
</html>