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 = "";
var hexLetters = '0123456789ABCDEF';
var txtFlag = true;
// ------------------------------------------------------------------------------------------------------
// Starting point: get the csv file with algorithm parameters and set the page
// with valid algs info.
// ------------------------------------------------------------------------------------------------------
$(document).ready(function() {
disableExecuteButton();
$.ajax({
url : "https://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);
buildLanguageSelection();
buildLanguageList();
buildAnnotations();
resizeTable();
resizeLogo();
$("#back-ner-ui-button").click(function() {
$("#ner-result-container").hide();
$("#ner-ui").show();
$("#input-textarea").val("");
publicLink = null;
jsonContent = null;
});
disableExecuteButton();
$("#upload-button")
.uploadFile(
{
url : "/nlphub/nlphub-uploader-servlet",
fileName : "mytxtfile",
maxFileCount : 100,
multiple : false,
maxFileSize : 1024 * 1000 * 1,
showFileCounter : false,
showCancel : true,
//allowedTypes: "txt,.txt",
dragDropStr : " ",
extErrorStr : "Error. Text file only",
sizeErrorStr : "Error. Max size: 6 Mb",
onLoad : function(obj) {
txtFlag = true;
$("#file-info").remove();
$("#reset-upload").remove();
$("#fu-container")
.append(
"
");
$("#right-child")
.append(
"
");
$("#right-child")
.append(
"Cancel
");
$("#reset-upload").hide();
$("#reset-upload").click(
function() {
resetExecuteButton();
$("#file-info").empty();
$("#reset-upload").css(
"display", "none");
textAreaEnable(true);
});
savedAnnotations = "";
setEventListeners();
},
onSelect : function(files) {
var fileName = files[0].name;
var extension = "" + fileName.substring(fileName.lastIndexOf("."));
if(extension.toUpperCase() == ".TXT") {
showProgress();
textAreaEnable(false);
$("#input-textarea").val("");
} else {
txtFlag = false;
alert("The application supports text file only (.TXT)");
}
},
onSubmit: function(files) {
var submitFlag = txtFlag;
txtFlag = true;
return submitFlag;
},
onSuccess : function(files, data, xhr) {
hideProgress();
console.log('' + data.language);
checkLanguage(data.language);
selectAnnotationsByLanguage();
$("#reset-upload").css("display",
"inline");
console.log("files: " + files);
$("#file-info").empty();
$("#file-info")
.append(
"Uploaded: "
+ files
+ " ");
publicLink = data.message;
enableExecuteButton();
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);
}
});
});
/*
* Utility function processing the language indication returned by the language recognition service
*/
checkLanguage = function(lang) {
if(lang == 'unavailable')
return;
var options = $("#language-select option");
for(var i=0; i 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];
}
}
}
}
/*
* Build the language array
*/
buildLanguageSelection = function() {
for (i in algorithms) {
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];
}
}
}
}
enableExecuteButton = function() {
$("#execute-button").css("background-color", pageGreen);
$("#execute-button").attr("enable", "true");
}
disableExecuteButton = function() {
$("#execute-button").css("background-color", pageGray);
$("#execute-button").attr("enable", "false");
}
isEnabled = function() {
if($("#execute-button").attr("enable") == "true")
return true;
return false;
}
enableDisableTextArea = function() {
if ($("#input-textarea").val() == "")
disableExecuteButton();
else
enableExecuteButton();
}
/*
* Set the listeners on the text area and the execute button
*/
setEventListeners = function() {
$("#input-textarea").on("keyup", function() {
enableDisableTextArea();
});
$("#input-textarea").change(function() {
enableDisableTextArea();
});
window.addEventListener('contextmenu', function(e) {
//alert("You've tried to open context menu"); //here you draw your own menu
//e.preventDefault();
enableDisableTextArea();
}, false);
$("#execute-button")
.click(
function() {
if(!isEnabled())
return;
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;
}
disableExecuteButton();
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();
}
});
}
/*
* show the in-progress popup
*/
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");
}
/*
* hide the in-progress popup
*/
hideProgress = function() {
$(".hidden-div").css("display", "none");
}
/*
* run the algorithms selected by the chosen language
*/
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;
// build the algorithm list, selecting on:
// [1] the language
// [2] the annotations
var algList = "";
for (j in algorithms) {
if (algorithms[j].lang.toLowerCase().indexOf(
$("#language-select").val().toLowerCase()) >= 0) {
var algAnnotations = algorithms[j].annotations.toLowerCase();
for(k in list) {
var a = list[k].toLowerCase();
if(algAnnotations.indexOf(a) > -1) {
algList += encodeURI(algorithms[j].id) + ",";
break;
}
}
}
}
if (algList.length == 0) {
alert("Warning. No algorithm matching with selected language.");
return;
}
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) {
textAreaEnable(true);
$("#file-info").empty();
$("#reset-upload").css("display", "none");
if (typeof (data.response) != 'undefined') {
var jsonOut = getOutputJson(data.message);
} else if (typeof (data.error) != 'undefined') {
hideProgress();
alert(data.message);
} else {
hideProgress();
alert("Unexpected response");
}
resetExecuteButton();
},
error : function(richiesta, stato, errori) {
hideProgress();
textAreaEnable(true);
alert("Unexpected Error. Status: " + richiesta.status);
resetExecuteButton();
}
});
}
/*
* Get the final json returned by the server
*/
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) {
hideProgress();
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) {
hideProgress();
$("#reset-upload").hide();
savedAnnotations = "";
publicLink = null;
alert("Unexpected Error. Status: " + richiesta.status);
}
});
}
/*
* Show the computation result
*/
showResult = function(data) {
$("#ner-ui").hide();
$("#ner-result-container").show();
jsonContent = data;
resultText = jsonContent.output.text;
$("#result-header-left").empty();
$("#result-header-right").empty();
$("#result-params-div").empty();
$("#result-text-div").empty();
$("#result-header-left").append(
"You can download the overall result as a JSON file here ");
$("#result-header-right").append(" ");
var localText = resultText;
localText = resultText.replace(/\n/g, " ");
$("#result-text-div").empty();
$("#result-text-div").append("" + localText + "
");
showAnnotationList(jsonContent.output.annotations);
}
showAnnotationList = function(list) {
var colorDisabled = "CCCCCC";
var color;
var colors = [];
var annotations = list.split(",");
for (var i = 0; i < annotations.length; i++) {
do {
color = randomRGB();
} while (color == colorDisabled);
colors[colors.length] = color;
}
$("#result-params-div").append("");
for (var i = 0; i < annotations.length; i++) {
var cb = " ";
cb += ""
+ annotations[i] + " ";
$("#colored-annotations").append(cb);
}
$("#colored-annotations :radio").change(function() {
if (this.checked) {
rewriteText(this.getAttribute("named"), "#" + this.value);
}
});
}
/*
* Utility function
*/
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;
}
/*
* Utility
*/
enhanceColor = function(color) {
var c = eval("0x" + color);
var hi = Math.round(c / 16);
if(hi < 15) {
hi += Math.round((15 - hi) / 1.5);
}
if(hi > 15) hi = 15;
return '' + hexLetters[hi] + hexLetters[c%16];
}
/*
* Write the html paragraph containing the text highlighted on annotation value
*/
rewriteText = function(annotation, color) {
$("#result-text-div").empty();
var complemetar = 0xFFFFFF - eval("0x" + color.substring(1));
var complement = complemetar.toString(16);
var R = enhanceColor(complement.substring(0,2));
var G = enhanceColor(complement.substring(2,4));
var B = enhanceColor(complement.substring(4));
complement = "#" + R + G + B;
console.log("-getIndices: start");
var indices = getIndices(annotation);
console.log("-getIndices: end");
$("#result-header-right").empty();
$("#result-header-right").append("" + annotation + " occurs " + indices.length + " times.");
var indexedText = "";
if ((typeof (indices) == 'undefined') || (indices.length == 0)) {
indexedText = resultText;
indexedText = indexedText.replace(/\n/g, " ");
indexedText = indexedText.replace(//g, ">");
$("#result-text-div").append("
" + indexedText + "
");
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 = ""
+ resultText.substring(start, end) + " ";
indexedText += colored;
t = end;
}
if (t < resultText.length)
indexedText += resultText.substring(t);
indexedText = indexedText.replace(/\n/g, " ");
$("#result-text-div").append("" + indexedText + "
");
}
/*
* Find if the annotation is presente in the json
*/
checkAnnotation = function(annotation) {
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') {
if(a.length > 0)
return true;
}
}
}
return false;
}
/*
* Retrieve the annotation indices from the json
*/
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;
}
}
}
}
var indices2 = [];
for (var i = 0; i < indices.length; i++) {
if (typeof (indices[i]) != 'undefined')
indices2[indices2.length] = indices[i];
}
return mergeIndices(indices2);
}
/*
* Merge the indices
*/
mergeIndices = function(indices) {
console.log("--mergeIndices start");
var newIndices = [];
//console.log("--mergeIndices: indices.length=" + indices.length);
if (indices.length == 1)
newIndices = indices[0];
else
newIndices = mergeAll(indices);
console.log("--mergeIndices end");
return newIndices;
}
/*
* Utility function
*/
resetExecuteButton = function() {
publicLink = null;
disableExecuteButton();
}
/*
* Resize the annotation table based on the screen geometry
*/
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(" ");
}
var annotationElement = " " + annotations[i] + " ";
if(annotations[i].toLowerCase() == "keyword") {
annotationElement = " " + annotations[i] + " ";
}
$("#" + rowId).append("" + annotationElement + " ");
}
}
/*
* Resize the page logo image based on the screen geometry
*/
resizeLogo = function() {
if (window.innerWidth < 200)
$("#logo-image").width(window.innerWidth - 10);
}
/*
* Build the annotation list for the service invocation
*/
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;
}
/*
* Handler for the window resize event
*/
window.onresize = function(event) {
resizeTable();
resizeLogo();
};
/*
* Handler for the file upload control
*/
$(".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");
}
});
/*
* Build the option list of supported language
*/
buildLanguageList = function() {
// build the language selection input control
for (i in languages) {
var opt = "" + languages[i] + " ";
if (i > 1)
opt = "" + languages[i]
+ " ";
$("#language-select").append(opt);
}
$("#language-select").on("change", function() {
selectAnnotationsByLanguage();
});
}
/*
* Utility
*/
selectAnnotationsByLanguage = function() {
buildAnnotations();
resizeTable();
}
/*
* Enable/disable the input text area
*/
textAreaEnable = function(enable) {
if (enable == true)
$("#input-textarea").prop('disabled', false);
else
$("#input-textarea").prop('disabled', true);
}
/*
* Get a random RGB color
*/
randomRGB = function() {
var color = '';
var couple = '';
for (var i = 0; i < 3; i++) {
couple = '' + hexLetters[Math.floor(Math.random() * 10)] + hexLetters[Math.floor(Math.random() * 16)];
color += couple;
}
return color;
}