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 appRoot = "/nlphub"; // ------------------------------------------------------------------------------------------------------ // Starting point: get the csv file with algorithm parameters and set the page // with valid algs info. // ------------------------------------------------------------------------------------------------------ $(document).ready(function() { disableExecuteButton(); showAnnotationsList(); checkInputLink(); }); 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=" + 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 : "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(); enableAjaxFileUpload(); collapsibleHandler(); $("#logo-image").click(function() { backHandler(); }); $("#back-ner-ui-button").click(function() { backHandler(); }); disableExecuteButton(); var uploaderUrl = appRoot + "/nlphub-uploader-servlet?dataminer=" + encodeURIComponent(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 : "", 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)"); } 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: " + files + ""); 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) { //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) { //if(publicLink == null) { freeText = $("#input-textarea").val(); var uploaderUrl = appRoot + "/nlphub-uploader-servlet?freetext=" + encodeURIComponent(freeText) + "&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) { 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(); } 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 { document.getElementById("ajax-file-upload-id").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(); $("#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 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=" + 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); //console.log(parameters); 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(); //console.log(data); 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 here"); $("#result-header-right").append(" "); var localText = resultText; localText = resultText.replace(/\n/g, "
"); $("#result-text-div").empty(); $("#result-text-div").append("

" + localText + "

"); 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("
"); var firstRadio = true; for (var i = 0; i < annotations.length; i++) { var cb = ""; cb += "
"; $("#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++) { var cb = "

"; cb += "

"; $("#algorithm-params-div").append(cb); } $("#algorithm-params-div :checkbox").change(function () { //buildCheckedAlgs(); rewriteText($("#colored-annotations :checked")[0].value); }); } /* * 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

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("" + checkedAnnotation + " occurs " + indices.length + " times."); if(indices.length != 0) { 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); 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 + "

"); } else { $("#result-text-div").append("

" + resultText + "

"); } }, 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++) { 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++) { // filter on algorithm var found = false; for(var j=0; j 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 = " "; if((annotations[i].toLowerCase() == "keyword") || (annotations[i].toLowerCase() == "event")) { annotationElement = " "; } $("#" + 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 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 = ""; if (i > 1) opt = ""; $("#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; }