nlphub/src/main/webapp/js/main.js

1274 lines
33 KiB
JavaScript
Executable File

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;
var checkedAnnotation = "";
var algIndexedArray = [];
var computedLanguage = "";
var dataMiner = "";
var appLocation = window.location.href;
var appRoot = "";
var linkToAlgorithmsConfiguration = "https://data.d4science.org/shub/E_R0M0WUZncEdBbWd0NWpjZTQ3a0VQMlYxZ0t5aGZSM2w3WE12K3FlenI0RFErSms3NFN6UURGM2ZyVGdTU2ovQw==";
// ------------------------------------------------------------------------------------------------------
// Starting point: get the csv file with algorithm parameters and set the page
// with valid algs info.
// ------------------------------------------------------------------------------------------------------
$(document).ready(function() {
console.log('HREF: '+appLocation);
appRoot=contextPath;
console.log('appRoot: '+ appRoot );
evaluateRequest();
});
evaluateRequest = function(){
$(".popup-text").hide();
disableExecuteButton();
showAnnotationsList();
checkAuth();
}
checkAuth = function(){
if(gCubeToken ===undefined || gCubeToken==null){
alert("Unexpected error token is null!\n.");
return null;
}
dataMinerClusterInfo();
checkInputLink();
}
dataMinerClusterInfo = function(){
if(gCubeToken ===undefined || gCubeToken==null){
alert("Unexpected error token is null!\n.");
return null;
}
var discoverDataMinerServiceUrl=appRoot+"/discover-dataminer-servlet?gcube-token="+gCubeToken;
$.ajax({
url : discoverDataMinerServiceUrl,
type : "GET",
async : true,
success : function(data) {
var dataminerHost=data;
console.log("Retrieved dataMinerServiceUrl: "+dataminerHost);
dataMiner=dataminerHost;
//alert("DataMiner Host: "+dataminerHost);
return;
},
error : function(request, error) {
alert("Unexpected error reading from link: '" + discoverDataMinerServiceUrl
+ "'\nStatus: " + request.status + "\nError: "
+ error + "\n.");
hideProgress();
initApplication();
}
});
}
checkInputLink = function() {
if (inputFile != "") {
showProgress();
$.ajax({
url : inputFile,
type : "GET",
async : true,
success : function(data, stato) {
freeText = data;
var uploaderUrl = appRoot
+ "/nlphub-uploader-servlet?getlang=on&freetext="
+ encodeURIComponent(freeText) + "&dataminer="
+ dataMiner; //encodeURIComponent(dataMiner);
if (gCubeToken.length > 0)
uploaderUrl += "&gcube-token=" + gCubeToken;
$.ajax({
url : uploaderUrl,
type : "POST",
async : true,
contentType : "text/plain; charset=utf-8",
success : function(data, stato) {
hideProgress();
$("#input-textarea").val(freeText);
computedLanguage = data.language;
initApplication();
},
error : function(richiesta, stato, errori) {
alert("Unexpected Error. Status: " + richiesta.status);
hideProgress();
textAreaEnable(true);
$("#file-info").empty();
initApplication();
}
});
},
error : function(richiesta, stato, errori) {
alert("Unexpected error reading from link: '" + inputFile
+ "'.\nStatus: " + richiesta.status + " Error: "
+ errori + "\nClick OK to start application.");
hideProgress();
initApplication();
}
});
} else
initApplication();
}
initApplication = function() {
$
.ajax({
url : linkToAlgorithmsConfiguration,
type : "GET",
async : true,
contentType : "text/plain; charset=utf-8",
success : function(data, stato) {
$("#ner-result-container").hide();
var algorithmsEnable = manageCsvData(data);
getAlgorithms(algorithmsEnable);
buildLanguageSelection();
buildLanguageList();
buildAnnotations();
resizeTable();
resizeLogo();
enableAjaxFileUpload();
collapsibleHandler();
$("#logo-image").click(function() {
backHandler();
});
$("#back-ner-ui-button").click(function() {
backHandler();
});
disableExecuteButton();
var uploaderUrl = appRoot
+ "/nlphub-uploader-servlet?dataminer="
//+ encodeURIComponent(dataMiner);
+ dataMiner;
if (gCubeToken.length > 0)
uploaderUrl += "&gcube-token=" + gCubeToken;
$("#upload-button")
.uploadFile(
{
url : uploaderUrl,
fileName : "mytxtfile",
maxFileCount : 100,
multiple : false,
maxFileSize : 1024 * 1000 * 1,
showFileCounter : false,
showCancel : true,
// allowedTypes: "txt,.txt",
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) {
txtFlag = true;
$("#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) {
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)");
}
publicLink = null;
textAreaEnable(false);
$("#input-textarea").val("");
},
onSubmit : function(files) {
var submitFlag = txtFlag;
txtFlag = true;
return submitFlag;
},
onSuccess : function(files, data, xhr) {
hideProgress();
checkLanguage(data.language);
selectAnnotationsByLanguage();
$("#reset-upload").css("display",
"inline");
$("#file-info").empty();
$("#file-info")
.append(
"Uploaded: <span style=\"color:#4CAF50; letter-spacing: 1px; font-weight: bold;\">"
+ files
+ "</span>");
publicLink = data.message;
enableExecuteButton();
if (publicLink == null) {
alert("Error uploading file.");
}
},
onError : function(files, status,
errMsg, pd) {
hideProgress();
textAreaEnable(true);
alert(errMsg);
}
});
if ($("#input-textarea").val() != "") {
disableAjaxFileUpload();
if (computedLanguage != "") {
checkLanguage(computedLanguage);
selectAnnotationsByLanguage();
computedLanguage = "";
}
enableExecuteButton();
}
},
error : function(richiesta, stato, errori) {
alert("Unexpected Error. Status: " + richiesta.status);
}
});
}
/*
* Set the listeners on the text area and the execute button
*/
setEventListeners = function() {
$(".ajax-file-upload").attr("id", "ajax-file-upload-id");
$("#input-textarea").on("keyup", function() {
enableDisableTextArea();
});
$("#input-textarea").change(function() {
enableDisableTextArea();
});
window.addEventListener('contextmenu', function(e) {
enableDisableTextArea();
}, false);
$(".popup-text").click(function(e) {
hidePopupText();
});
$("#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) {
// if(publicLink == null) {
freeText = $("#input-textarea").val();
var uploaderUrl = appRoot
+ "/nlphub-uploader-servlet?freetext="
+ encodeURIComponent(freeText)
+ "&dataminer="
//+ encodeURIComponent(dataMiner);
+dataMiner;
if (gCubeToken.length > 0)
uploaderUrl += "&gcube-token=" + gCubeToken;
$.ajax({
url : uploaderUrl,
type : "POST",
async : true,
contentType : "text/plain; charset=utf-8",
success : function(data, stato) {
publicLink = data.message;
if (publicLink == null) {
alert("Error uploading file.");
}
runAlgorithm();
},
error : function(richiesta, stato, errori) {
alert("Unexpected Error. Status: "
+ richiesta.status);
hideProgress();
textAreaEnable(true);
$("#file-info").empty();
}
});
}
else {
runAlgorithm();
}
});
}
collapsibleHandler = function() {
// $('.collapsible').collapsible();
// $('.collapsible').collapsible({
// onOpen: function(el) {
// if(el.index() == 0)
// $('.collapsible').collapsible('close', 1);
// else
// $('.collapsible').collapsible('close', 0);
// },
// onClose: function(el) {
// if(el.index() == 0)
// $('.collapsible').collapsible('open', 1);
// else
// $('.collapsible').collapsible('open', 0);
// }
// });
}
enableAjaxFileUpload = function() {
$(".ajax-file-upload").attr("enabled", "true");
$(".ajax-file-upload").css("background", pageGreen);
try {
var fUploadElement=document.getElementById("ajax-file-upload-id");
if(fUploadElement!=null){
fUploadElement.removeEventListener(
"click", listenAjaxFileUpload);
}
} catch (err) {
console.log(err.message);
}
}
disableAjaxFileUpload = function() {
$(".ajax-file-upload").attr("enabled", "false");
$(".ajax-file-upload").css("background", pageGray);
try {
document.getElementById("ajax-file-upload-id").removeEventListener(
"click", listenAjaxFileUpload);
document.getElementById("ajax-file-upload-id").addEventListener(
"click", listenAjaxFileUpload);
} catch (err) {
document.getElementById("ajax-file-upload-id").addEventListener(
"click", listenAjaxFileUpload);
}
}
listenAjaxFileUpload = function(event) {
event.preventDefault();
}
backHandler = function() {
if ($("#ner-ui").is(":visible"))
return;
$("#ner-result-container").hide();
$(".popup-text").hide();
$("#ner-ui").show();
if (publicLink != null) {
enableExecuteButton();
if (document.getElementById("reset-upload") != null) {
if ($("#reset-upload").is(":visible"))
textAreaEnable(false);
}
}
}
/*
* 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 < options.length; i++) {
if (options[i].innerText.toLowerCase() == lang.toLowerCase()) {
$("#language-select").val(options[i].innerText);
buildAnnotations();
return;
}
}
alert("The uploaded file seems to be in "
+ lang
+ ", but this language is not currently supported. Please, be aware of this, should you decide to continue and use the tools of another language... \"Praemonitus praemunitus!\"");
}
/*
* CSV parser
*/
manageCsvData = function(data) {
var tokensPerLine = 8;
// 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.push(line.substring(tokenStart + 1, j));
tokenStart = j;
}
}
}
// get the new token and push it in the array
tokens.push(line.substring(tokenStart + 1));
if (tokens.length != tokensPerLine)
continue; // skip...
lineTokens.push(tokens);
var description = tokens[1].toUpperCase().trim();
/*if (description == "CLOUD COMPUTING")
dataMiner = tokens[2];*/
tokens = [];
}
return lineTokens;
}
/*
* Map the supported algorithms (from CSV) in the internal global algorithm
* array
*/
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][1].toUpperCase().trim() != activePage.toUpperCase())
continue;
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.push({
"name" : algName,
"description" : algDescription,
"id" : algId,
"lang" : language,
"annotations" : annotationList
});
algIndexedArray[algorithms[algorithms.length - 1].id
.substr(algorithms[0].id.lastIndexOf(".") + 1)] = algorithms[algorithms.length - 1];
}
}
}
/*
* Build the annotation list based on the language selected
*/
buildAnnotations = function() {
annotations = [];
var language = $("#language-select").val();
for (i in algorithms) {
if (algorithms[i].lang.toLowerCase() != language.toLowerCase())
continue;
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];
}
}
}
}
/*
* 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();
enableAjaxFileUpload();
} else {
enableExecuteButton();
disableAjaxFileUpload();
}
}
/*
* show the in-progress popup
*/
showProgress = function() {
$(".hidden-div").css("display", "block");
$(".hidden-div").show();
}
/*
* hide the in-progress popup
*/
hideProgress = function() {
$(".hidden-div").css("display", "none");
$(".hidden-div").hide();
}
/*
* run the algorithms selected by the chosen language
*/
runAlgorithm = 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.");
hideProgress();
return;
}
algList = algList.substring(0, algList.length - 1);
var parameters = "annotations=" + annList;
parameters += "&dataminer=" +dataMiner; //+ encodeURIComponent(dataMiner);
parameters += "&lang=" + $("#language-select").val();
parameters += "&plink=" + encodeURIComponent(publicLink);
parameters += "&algs=" + algList;
var nlphubUrl = appRoot + "/nlphub-servlet?" + parameters;
if (gCubeToken.length > 0)
nlphubUrl += "&gcube-token=" + gCubeToken;
$.ajax({
url : nlphubUrl,
type : "POST",
async : true,
success : function(data, stato) {
textAreaEnable(true);
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");
}
},
error : function(richiesta, stato, errori) {
hideProgress();
textAreaEnable(true);
alert("Unexpected Error. Status: " + richiesta.status);
}
});
}
/*
* Get the final json returned by the server
*/
getOutputJson = function(message) {
var tobemap = "";
for (var i = 0; i < message.length; i++) {
var splitted = message[i].split(":::");
if (splitted[1].toLowerCase().trim() == "error") {
alert("Some error occurrend running algorithm " + splitted[0]
+ ". Trying to get other results...");
} else {
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);
var mapperUrl = appRoot + "/nlphub-mapper-servlet?" + parameters;
if (gCubeToken.length > 0)
mapperUrl += "&gcube-token=" + gCubeToken;
$.ajax({
url : mapperUrl,
type : "POST",
async : true,
success : function(data, stato) {
hideProgress();
if ((typeof (data.response) != "undefined")
&& (data.response.trim().toUpperCase() == "ERROR")) {
alert("ERROR\n" + data.message);
} else {
savedAnnotations = "";
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 <a href='"
+ jsonContent.link + "'>here</a>");
$("#result-header-right").append("&nbsp;");
var localText = resultText;
localText = resultText.replace(/\n/g, "<br>");
$("#result-text-div").empty();
$("#result-text-div").append("<p>" + localText + "</p>");
buildAlgortihmList();
buildAnnotationList(jsonContent.output.annotations);
}
/*
* Build the list of radio-button controls with the annotations
*/
buildAnnotationList = 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("<form id='colored-annotations'></form>");
var firstRadio = true;
for (var i = 0; i < annotations.length; i++) {
var cb = "<input type='radio' name='foo-ner-annotations' ";
if (!checkAnnotation(annotations[i])) {
cb += "disabled ";
colors[i] = colorDisabled;
}
if (firstRadio) {
if (cb.indexOf("disabled") < 0) {
firstRadio = false;
cb += "checked ";
}
}
cb += "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) {
checkedAnnotation = this.getAttribute("named");
filterAlgorithmsByAnnotation(checkedAnnotation);
rewriteText("#" + this.value);
}
});
showAnnotationsList();
$("#colored-annotations :radio").change();
}
/*
* Utility
*/
showAnnotationsList = function() {
$('.collapsible').collapsible('close', 0);
$('.collapsible').collapsible('close', 1);
$('.collapsible').collapsible('open', 1);
}
/*
* build the list of check-box controls for algorithms
*/
buildAlgortihmList = function() {
$("#algorithm-params-div").empty();
for (var i = 0; i < jsonContent.output.result.length; i++) {
if (typeof jsonContent.output.result[i] === 'undefined'
|| jsonContent.output.result[i] == null) {
console.log("No result for " + i);
} else {
var cb = "<div class='alg-info-p'><input type='checkbox' name='foo-ner-algs' checked named='"
+ jsonContent.output.result[i].algorithm
+ "' id='algorithm" + i + "'>";
cb += "<label class='label-alg-info' for='algorithm" + i
+ "'></label></div>";
cb += "<div class='alg-info-p' onclick='getAlgInformation(\""
+ jsonContent.output.result[i].algorithm
+ "\")'>"
+ findNameByAlgorithmId(jsonContent.output.result[i].algorithm)
+ "</div><div class='clearfix'></div>";
$("#algorithm-params-div").append(cb);
}
}
$("#algorithm-params-div :checkbox").change(function() {
// buildCheckedAlgs();
rewriteText($("#colored-annotations :checked")[0].value);
});
}
getAlgInformation = function(alg) {
var algId = "";
for ( var i in algorithms) {
if (algorithms[i].id.indexOf(alg) > 0) {
algId = algorithms[i].id;
break;
}
}
if (algId == "") {
alert("Invalid algorithm identifier.");
return;
}
console.log("getAlgorithm from dataMiner: "+dataMiner);
var parameters = "getInfo=on";
parameters += "&dataminer=" + dataMiner; //encodeURIComponent(dataMiner);
parameters += "&algId=" + algId;
console.log("parameters: "+parameters);
var nlphubUrl = appRoot + "/nlphub-servlet?" + parameters;
if (gCubeToken.length > 0)
nlphubUrl += "&gcube-token=" + gCubeToken;
$.ajax({
url : nlphubUrl,
type : "GET",
async : true,
success : function(data, stato) {
// alert(data.message);
let linkMessage="<a target='_blank' rel='noopener noreferrer' href='"+data.message+"'>"+data.message+"</a>";
showPopupText(linkMessage);
},
error : function(richiesta, stato, errori) {
alert("Unexpected Error. Status: " + richiesta.status);
}
});
}
showPopupText = function(text) {
$(".popup-text-content").empty();
$(".popup-text-content").append("<p>" + text + "</p>");
$(".popup-text").show();
}
hidePopupText = function() {
$(".popup-text-content").empty();
$(".popup-text").hide();
}
/*
* Utility function
*/
findNameByAlgorithmId = function(id) {
for (i in algorithms) {
if (algorithms[i].id.substr(algorithms[i].id.lastIndexOf(".") + 1) == id)
return algorithms[i].name;
}
return id;
}
/*
* 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 <p> containing the text highlighted on annotation
* value
*/
rewriteText = function(color) {
if (color.startsWith("#"))
color = color.substring(1);
$("#result-text-div").empty();
var complemetar = 0xFFFFFF - eval("0x" + color);
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;
showProgress();
$(".hidden-div").show();
window.setTimeout(function() {
var indices = getIndices();
$(".hidden-div").hide();
$("#result-header-right").empty();
$("#result-header-right").append(
"<span style='color:" + color + ";'>" + checkedAnnotation
+ "</span> occurs " + indices.length + " times.");
if (indices.length != 0) {
var indexedText = "";
if ((typeof (indices) == 'undefined') || (indices.length == 0)) {
indexedText = resultText;
indexedText = indexedText.replace(/\n/g, "<br>");
indexedText = indexedText.replace(/</g, "&lt;");
indexedText = indexedText.replace(/>/g, "&gt;");
$("#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);
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>");
} else {
$("#result-text-div").append("<p>" + resultText + "</p>");
}
}, 50);
}
filterAlgorithmsByAnnotation = function() {
if ($("#result-params-div input[type=radio]:checked").length < 1)
return;
var annotation = $("#result-params-div input[type=radio]:checked")[0]
.getAttribute("named");
var algs = $("#algorithm-params-div input[type=checkbox]");
for (var i = 0; i < algs.length; i++) {
var named = $("#algorithm-params-div input[type=checkbox]")[i]
.getAttribute("named");
var annList = algIndexedArray[named].annotations;
if (annList.indexOf(annotation) >= 0) {
$($("#algorithm-params-div input[type=checkbox]")[i]).prop(
"checked", true);
} else {
$($("#algorithm-params-div input[type=checkbox]")[i]).prop(
"checked", false);
}
}
}
/*
* Find if the annotation is present in the json
*/
checkAnnotation = function(annotation) {
for (var i = 0; i < jsonContent.output.result.length; i++) {
if (typeof jsonContent.output.result[i] === 'undefined'
|| jsonContent.output.result[i] == null) {
console.log("No result for " + i);
} else {
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() {
var checkedAlgs = $("#algorithm-params-div input[type=checkbox]:checked");
var indices = [];
// get indices
for (var i = 0; i < jsonContent.output.result.length; i++) {
if (typeof jsonContent.output.result[i] === 'undefined'
|| jsonContent.output.result[i] == null) {
console.log("No result for " + i);
} else {
// filter on algorithm
var found = false;
for (var j = 0; j < checkedAlgs.length; j++) {
if (checkedAlgs[j].getAttribute("named") == jsonContent.output.result[i].algorithm) {
found = true;
break;
}
}
if (!found)
continue;
var entities = jsonContent.output.result[i].entities;
for (var j = 0; j < entities.length; j++) {
// filter on annotation
a = entities[j][checkedAnnotation];
if (typeof a != 'undefined') {
indices[i] = [];
for (var k = 0; k < a.length; k++) {
var index = a[k].indices;
indices[i][k] = index;
}
}
}
}
}
if (indices.length == 0)
return indices;
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) {
var newIndices = [];
newIndices = mergeAll(indices);
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("<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>";
if ((annotations[i].toLowerCase() == "keyword")
|| (annotations[i].toLowerCase() == "event")) {
annotationElement = "<input type=\"checkbox\" id=\"check-" + i
+ "\" value=\"" + annotations[i]
+ "\"></input> <label for=\"check-" + i + "\">"
+ annotations[i] + "</label>";
}
$("#" + rowId).append("<td>" + annotationElement + "</td>");
}
}
/*
* 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
var defaultLanguage = null;
for (i in languages) {
languages[i] = languages[i].trim();
languages[i] = languages[i].replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
if (languages[i] == "English")
defaultLanguage = languages[i];
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);
}
if (defaultLanguage != null)
$("#language-select").val(defaultLanguage);
$("#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;
}